Example #1
0
def create_dummy_user():
    """
    Creates a dummy user for testing purposes
    """
    avatar = Avatar()

    avatar.setName("fake")
    avatar.setSurName("fake")
    avatar.setOrganisation("fake")
    avatar.setLang("en_GB")
    avatar.setEmail("*****@*****.**")

    # registering user
    ah = AvatarHolder()
    ah.add(avatar)

    # setting up the login info
    li = LoginInfo("dummyuser", "dummyuser")
    ih = AuthenticatorMgr()
    userid = ih.createIdentity(li, avatar, "Local")
    ih.add(userid)

    # activate the account
    avatar.activateAccount()

    # since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()

    al = minfo.getAdminList()
    al.grant(avatar)

    dc = DefaultConference()
    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(dc)
    return avatar
Example #2
0
def create_dummy_user():
    """
    Creates a dummy user for testing purposes
    """
    avatar = Avatar()

    avatar.setName("fake")
    avatar.setSurName("fake")
    avatar.setOrganisation("fake")
    avatar.setLang("en_GB")
    avatar.setEmail("*****@*****.**")

    # registering user
    ah = AvatarHolder()
    ah.add(avatar)

    # setting up the login info
    li = LoginInfo("dummyuser", "dummyuser")
    ih = AuthenticatorMgr()
    userid = ih.createIdentity(li, avatar, "Local")
    ih.add(userid)

    # activate the account
    avatar.activateAccount()

    # since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()

    al = minfo.getAdminList()
    al.grant(avatar)

    dc = DefaultConference()
    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(dc)
    return avatar
def create_dummy_users(dummyuser_has_password=False):
    """
    Creates a dummy user for testing purposes.

    If dummyuser_has_password is set, "dummyuser" and "fake-1" can be used for logging in.
    """
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ah = AvatarHolder()
    authManager = AuthenticatorMgr()
    avatars = []
    al = minfo.getAdminList()

    avatar = create_user("fake", "dummyuser", authManager, dummyuser_has_password)
    ah.add(avatar)
    avatars.append(avatar)
    al.grant(avatar)

    for i in xrange(1, 5):
        avatar = create_user("fake-%d" % i, "fake-%d" % i, authManager, dummyuser_has_password and i == 1)
        avatar.setId("fake-%d" % i)
        ah.add(avatar)
        avatars.append(avatar)

    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(DefaultConference())
    return avatars
Example #4
0
def create_dummy_users():
    """
    Creates a dummy user for testing purposes
    """
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ah = AvatarHolder()
    authManager = AuthenticatorMgr()
    avatars = []
    al = minfo.getAdminList()

    avatar = create_user("fake", "dummyuser", authManager)
    ah.add(avatar)
    avatars.append(avatar)
    al.grant(avatar)

    for i in xrange(1, 5):
        avatar = create_user("fake-%d" % i, "fake-%d" % i, authManager)
        avatar.setId("fake-%d" % i)
        ah.add(avatar)
        avatars.append(avatar)

    # since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()

    dc = DefaultConference()
    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(dc)
    return avatars
def create_dummy_users(dummyuser_has_password=False):
    """
    Creates a dummy user for testing purposes.

    If dummyuser_has_password is set, "dummyuser" and "fake-1" can be used for logging in.
    """
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    ah = AvatarHolder()
    authManager = AuthenticatorMgr()
    avatars = []
    al = minfo.getAdminList()

    avatar = create_user("fake", "dummyuser", authManager,
                         dummyuser_has_password)
    ah.add(avatar)
    avatars.append(avatar)
    al.grant(avatar)

    for i in xrange(1, 5):
        avatar = create_user("fake-%d" % i, "fake-%d" % i, authManager,
                             dummyuser_has_password and i == 1)
        avatar.setId("fake-%d" % i)
        ah.add(avatar)
        avatars.append(avatar)

    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(
        DefaultConference())
    return avatars
Example #6
0
 def remote_addr(self):
     """The remote address of the client."""
     with DBMgr.getInstance().global_connection():
         if HelperMaKaCInfo.getMaKaCInfoInstance().useProxy():
             if self.access_route:
                 return self.access_route[0]
     return super(IndicoRequest, self).remote_addr
Example #7
0
def server_to_utc(dt):
    """Converts the given datetime in the server's TZ to UTC.

    The given datetime **MUST** be naive but already contain the correct time in the server's TZ.
    """
    server_tz = get_timezone(HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone())
    return server_tz.localize(dt).astimezone(pytz.utc)
Example #8
0
 def remote_addr(self):
     """The remote address of the client."""
     with DBMgr.getInstance().global_connection():
         if HelperMaKaCInfo.getMaKaCInfoInstance().useProxy():
             if self.access_route:
                 return self.access_route[0]
     return super(IndicoRequest, self).remote_addr
Example #9
0
 def __init__(self, conference):
     if conference.getId() == "default":
         #Best values for CERN printing service
         self.__topMargin = 1.6
         self.__bottomMargin = 1.1
         self.__leftMargin = 1.6
         self.__rightMargin = 1.4
         self.__marginColumns = 1.0
         self.__marginRows = 0.0
         self._pageSize = "A4"
         self._landscape = False
         self._drawDashedRectangles = True
     else:
         defaultConferencePDFOptions = (
             HelperMaKaCInfo.getMaKaCInfoInstance().getDefaultConference(
             ).getBadgeTemplateManager().getPDFOptions())
         self.__topMargin = defaultConferencePDFOptions.getTopMargin()
         self.__bottomMargin = defaultConferencePDFOptions.getBottomMargin()
         self.__leftMargin = defaultConferencePDFOptions.getLeftMargin()
         self.__rightMargin = defaultConferencePDFOptions.getRightMargin()
         self.__marginColumns = defaultConferencePDFOptions.getMarginColumns(
         )
         self.__marginRows = defaultConferencePDFOptions.getMarginRows()
         self._pageSize = defaultConferencePDFOptions.getPagesize()
         self._landscape = defaultConferencePDFOptions.getLandscape()
         self._drawDashedRectangles = defaultConferencePDFOptions.getDrawDashedRectangles(
         )
Example #10
0
    def _create_user(self, form, handler):
        data = form.data
        existing_user_id = session.get('register_pending_user')
        if existing_user_id:
            # Get pending user and set it as non-pending
            user = User.get(existing_user_id)
            user.is_pending = False
        else:
            user = User(first_name=data['first_name'], last_name=data['last_name'], email=data['email'],
                        address=data.get('address', ''), phone=data.get('phone', ''), affiliation=data['affiliation'])

        identity = handler.create_identity(data)
        user.identities.add(identity)
        user.secondary_emails = handler.extra_emails - {user.email}
        user.favorite_users.add(user)
        db.session.add(user)
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        timezone = session.timezone
        if timezone == 'LOCAL':
            timezone = minfo.getTimezone()
        user.settings.set('timezone', timezone)
        user.settings.set('lang', session.lang or minfo.getLang())
        handler.update_user(user, form)
        db.session.flush()
        login_user(user, identity)
        msg = _('You have sucessfully registered your Indico profile. '
                'Check <a href="{url}">your profile</a> for further details and settings.')
        flash(Markup(msg).format(url=url_for('users.user_profile')), 'success')
        return handler.redirect_success()
Example #11
0
def server_to_utc(dt):
    """Converts the given datetime in the server's TZ to UTC.

    The given datetime **MUST** be naive but already contain the correct time in the server's TZ.
    """
    server_tz = get_timezone(
        HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone())
    return server_tz.localize(dt).astimezone(pytz.utc)
Example #12
0
def _can_access(cls, obj, user, **kwargs):
    """Grant full access to attachments/folders to certain IPs"""
    from MaKaC.common import HelperMaKaCInfo
    if not has_request_context():
        return
    full_access_ips = HelperMaKaCInfo.getMaKaCInfoInstance().getIPBasedACLMgr().get_full_access_acl()
    if request.remote_addr in full_access_ips:
        return True
Example #13
0
 def _process(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     cfg = minfo.getSocialAppConfig()
     if 'socialActive' in self._params:
         cfg['active'] = self._params.get('socialActive') == 'yes'
     if 'facebook_appId' in self._params:
         cfg.setdefault('facebook', PersistentDict())['appId'] = self._params.get('facebook_appId')
     self._redirect( urlHandlers.UHAdminLayoutGeneral.getURL() )
Example #14
0
def _can_access(cls, obj, user, **kwargs):
    """Grant full access to attachments/folders to certain IPs"""
    from MaKaC.common import HelperMaKaCInfo
    if not has_request_context():
        return
    full_access_ips = HelperMaKaCInfo.getMaKaCInfoInstance().getIPBasedACLMgr().get_full_access_acl()
    if request.remote_addr in full_access_ips:
        return True
Example #15
0
 def _process(self):
     minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
     cfg = minfo.getSocialAppConfig()
     if 'socialActive' in self._params:
         cfg['active'] = self._params.get('socialActive') == 'yes'
     if 'facebook_appId' in self._params:
         cfg.setdefault('facebook', PersistentDict())['appId'] = self._params.get('facebook_appId')
     self._redirect( urlHandlers.UHAdminLayoutGeneral.getURL() )
Example #16
0
 def _checkProtection(self):
     RHProtected._checkProtection(self)
     if not session.user and not self._doProcess:
         return
     self._al = HelperMaKaCInfo.getMaKaCInfoInstance().getAdminList()
     if not session.user.isAdmin():
         if not self._al.getList():  # XXX can we just fail here instead of pretending the user is an admin?!
             return
         raise AdminError("area")
 def _create_home(self):
     # get default/selected view
     styleMgr = HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
     view = self._rh._target.getDefaultStyle()
     # if no default view was attributed, then get the configuration default
     if view == "" or not styleMgr.existsStyle(view) or view in styleMgr.getXSLStyles():
         view = styleMgr.getDefaultStyleForEventType(self._eventType)
     p = WPTPLStaticConferenceDisplay(self._rh, self._rh._target, view, self._eventType, self._rh._reqParams)
     self._html = p.display(**self._rh._getRequestParams())
Example #18
0
 def _save_file(self, srcPath, static_site_id):
     volume = HelperMaKaCInfo.getMaKaCInfoInstance().getArchivingVolume()
     path = os.path.join(Config.getInstance().getOfflineStore(), volume, 'offline', self._conf.getId())
     file_path = os.path.join(path, '{}.zip'.format(static_site_id))
     try:
         os.makedirs(path)
     except OSError as e:
         if e.errno != errno.EEXIST:
             raise
     shutil.copyfile(srcPath, file_path)
     return file_path
Example #19
0
 def _process( self ):
     modPay = self._conf.getModPay().getModPayById(self._epayment)
     if modPay is not None:
         if modPay.getId() == "CERNYellowPay":
             minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
             al = minfo.getAdminList()
             if al.isAdmin( self._getUser() ):
                 modPay.setEnabled(not modPay.isEnabled())
         else:
             modPay.setEnabled(not modPay.isEnabled())
     self._redirect(urlHandlers.UHConfModifEPayment.getURL(self._conf))
Example #20
0
    def _getSectionsHTML(self):
        modPay=self._conf.getModPay()
        html=[]
        enabledBulb = Configuration.Config.getInstance().getSystemIconURL( "enabledSection" )
        notEnabledBulb = Configuration.Config.getInstance().getSystemIconURL( "disabledSection" )
        enabledText = _("Click to disable")
        disabledText = _("Click to enable")
        for gs in modPay.getSortedModPay():
                      
            urlStatus = urlHandlers.UHConfModifEPaymentEnableSection.getURL(self._conf)
            urlStatus.addParam("epayment", gs.getId())
            urlModif = gs.getConfModifEPaymentURL(self._conf)
            img = enabledBulb
            text = enabledText
            if not gs.isEnabled():
                img = notEnabledBulb
                text = disabledText

            # CERN Plugin: Just admins can see and modify it
            if gs.getId() == "CERNYellowPay":
                minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
                al = minfo.getAdminList()
                if not al.isAdmin( self._user ):
                    from MaKaC.plugins.EPayment.CERNYellowPay.options import globalOptions
                    endis="enable"
                    departmentName = globalOptions[1][1]["defaultValue"]
                    emailAddress = globalOptions[0][1]["defaultValue"]
                    if gs.isEnabled():
                        endis="disable"
                        emailAddress = minfo.getSupportEmail()
                        departmentName = "Indico support"
                    html.insert(0, """
                        <tr>
                        <td>
                            <img src=%s alt="%s" class="imglink">&nbsp;&nbsp;<b>CERN E-Payment</b> <small>
                            (please, contact <a href="mailto:%s?subject=Indico Epayment - Conference ID: %s">%s</a> to %s 
                            the CERN e-payment module)</small>
                        </td>
                        </tr>
                        """%(img, text, emailAddress, self._conf.getId(), departmentName, endis))
                    continue
            #################################################
            
            selbox = ""
            html.append("""
                        <tr>
                        <td>
                            <a href=%s><img src=%s alt="%s" class="imglink"></a>&nbsp;%s&nbsp;<a href=%s>%s</a>
                        </td>
                        </tr>
                        """%(quoteattr(str(urlStatus)), img, text, selbox, quoteattr(str(urlModif)), gs.getTitle()) )
        html.insert(0, """<a href="" name="sections"></a><input type="hidden" name="oldpos"><table align="left">""")
        html.append("</table>")
        return "".join(html)
Example #21
0
 def _create_home(self):
     # get default/selected view
     styleMgr = HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
     view = self._rh._target.getDefaultStyle()
     # if no default view was attributed, then get the configuration default
     if view == "" or not styleMgr.existsStyle(
             view) or view in styleMgr.getXSLStyles():
         view = styleMgr.getDefaultStyleForEventType(self._eventType)
     p = WPTPLStaticConferenceDisplay(self._rh, self._rh._target, view,
                                      self._eventType, self._rh._reqParams)
     self._html = p.display(**self._rh._getRequestParams())
 def _save_file(self, srcPath, static_site_id):
     volume = HelperMaKaCInfo.getMaKaCInfoInstance().getArchivingVolume()
     path = os.path.join(Config.getInstance().getOfflineStore(), volume, 'offline', self._conf.getId())
     file_path = os.path.join(path, '{}.zip'.format(static_site_id))
     try:
         os.makedirs(path)
     except OSError as e:
         if e.errno != errno.EEXIST:
             raise
     shutil.copyfile(srcPath, file_path)
     return file_path
Example #23
0
def setup_jinja(app):
    config = Config.getInstance()
    # Unicode hack
    app.jinja_env.add_extension(EnsureUnicodeExtension)
    app.add_template_filter(EnsureUnicodeExtension.ensure_unicode)
    # Useful (Python) builtins
    app.add_template_global(dict)
    # Global functions
    app.add_template_global(url_for)
    app.add_template_global(url_for_plugin)
    app.add_template_global(url_rule_to_js)
    app.add_template_global(IndicoConfigWrapper(config), 'indico_config')
    app.add_template_global(config.getSystemIconURL, 'system_icon')
    app.add_template_global(include_css_assets)
    app.add_template_global(include_js_assets)
    app.add_template_global(include_plugin_css_assets)
    app.add_template_global(include_plugin_js_assets)
    app.add_template_global(call_template_hook, 'template_hook')
    app.add_template_global(is_single_line_field, '_is_single_line_field')
    app.add_template_global(render_field, '_render_field')
    app.add_template_global(iter_form_fields, '_iter_form_fields')
    app.add_template_global(format_currency)
    app.add_template_global(get_currency_name)
    app.add_template_global(url_for_login)
    app.add_template_global(url_for_logout)
    app.add_template_global(lambda: unicode(uuid.uuid4()), 'uuid')
    app.add_template_global(icon_from_mimetype)
    # Filters (indico functions returning UTF8)
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_time))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta))
    # Filters (new ones returning unicode)
    app.add_template_filter(date_time_util.format_human_timedelta)
    app.add_template_filter(lambda d: Markup(html_params(**d)), 'html_params')
    app.add_template_filter(underline)
    app.add_template_filter(markdown)
    app.add_template_filter(dedent)
    app.add_template_filter(natsort)
    app.add_template_filter(groupby)
    app.add_template_filter(any)
    app.add_template_filter(strip_tags)
    app.add_template_filter(alpha_enum)
    # Tests
    app.add_template_test(instanceof)  # only use this test if you really have to!
    app.add_template_test(subclassof)  # only use this test if you really have to!
    # i18n
    app.jinja_env.add_extension('jinja2.ext.i18n')
    app.jinja_env.install_gettext_callables(gettext_context, ngettext_context, True)
    app.add_template_global(lambda: HelperMaKaCInfo.getMaKaCInfoInstance().getLang(), 'get_default_language')
    # webassets
    app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
    app.jinja_env.assets_environment = core_env
Example #24
0
 def _process(self):
     modPay = self._conf.getModPay().getModPayById(self._epayment)
     if modPay is not None:
         if modPay.getId() == "CERNYellowPay":
             minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
             al = minfo.getAdminList()
             if al.isAdmin(self._getUser()):
                 modPay.setEnabled(not modPay.isEnabled())
         else:
             modPay.setEnabled(not modPay.isEnabled())
     self._redirect(urlHandlers.UHConfModifEPayment.getURL(self._conf))
Example #25
0
def setup_jinja(app):
    config = Config.getInstance()
    # Unicode hack
    app.jinja_env.add_extension(EnsureUnicodeExtension)
    app.add_template_filter(EnsureUnicodeExtension.ensure_unicode)
    # Global functions
    app.add_template_global(url_for)
    app.add_template_global(url_for_plugin)
    app.add_template_global(url_rule_to_js)
    app.add_template_global(IndicoConfigWrapper(config), 'indico_config')
    app.add_template_global(config.getSystemIconURL, 'system_icon')
    app.add_template_global(include_css_assets)
    app.add_template_global(include_js_assets)
    app.add_template_global(include_plugin_css_assets)
    app.add_template_global(include_plugin_js_assets)
    app.add_template_global(call_template_hook, 'template_hook')
    app.add_template_global(is_single_line_field, '_is_single_line_field')
    app.add_template_global(render_field, '_render_field')
    app.add_template_global(format_currency)
    app.add_template_global(get_currency_name)
    app.add_template_global(url_for_login)
    app.add_template_global(url_for_logout)
    # Filters (indico functions returning UTF8)
    app.add_template_filter(
        EnsureUnicodeExtension.wrap_func(date_time_util.format_date))
    app.add_template_filter(
        EnsureUnicodeExtension.wrap_func(date_time_util.format_time))
    app.add_template_filter(
        EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime))
    app.add_template_filter(
        EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date))
    app.add_template_filter(
        EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta))
    # Filters (new ones returning unicode)
    app.add_template_filter(lambda d: Markup(html_params(**d)), 'html_params')
    app.add_template_filter(underline)
    app.add_template_filter(markdown)
    app.add_template_filter(dedent)
    app.add_template_filter(natsort)
    # Tests
    app.add_template_test(
        instanceof)  # only use this test if you really have to!
    app.add_template_test(equalto)
    # i18n
    app.jinja_env.add_extension('jinja2.ext.i18n')
    app.jinja_env.install_gettext_callables(gettext_context, ngettext_context,
                                            True)
    app.add_template_global(
        lambda: HelperMaKaCInfo.getMaKaCInfoInstance().getLang(),
        'get_default_language')
    # webassets
    app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
    app.jinja_env.assets_environment = core_env
Example #26
0
def format_datetime(dt, format='medium', locale=None, timezone=None, server_tz=False):
    """
    Basically a wrapper around Babel's own format_datetime
    """
    if not locale:
        locale = currentLocale()
    if not timezone and dt.tzinfo:
        timezone = DisplayTZ().getDisplayTZ()
    elif server_tz:
        timezone = HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()

    return _format_datetime(dt, format=format, locale=locale, tzinfo=timezone).encode('utf-8')
Example #27
0
 def _process( self ):
     if not self._cancel:
         modpay = self._conf.getModPay()
         params = self._getRequestParams()
         #modpay.getModPayLater().setValues(params)
         modpay.setPaymentDetails(params.get("detailPayment", ""))
         modpay.setPaymentSpecificConditions(params.get("specificConditionsPayment", ""))
         from MaKaC.common import HelperMaKaCInfo
         minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
         al = minfo.getAdminList()
         if al.isAdmin( self._getUser() ):
             modpay.setPaymentConditions(params.get("conditionsPayment", ""))
             modpay.setPaymentConditionsEnabled(params.has_key("conditionsEnabled"))
     self._redirect(urlHandlers.UHConfModifEPayment.getURL(self._conf))    
Example #28
0
    def hasRights(request = None, user = None):
        """ Returns True if the user is a Server Admin
            request: an RH or Service object
            user: an Avatar object
            If user is not None, the request object will be used to check the user's privileges.
            Otherwise the user will be retrieved from the request object
        """
        if user is None:
            if request is None:
                return False
            else:
                user = request._getUser()

        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        serverAdmins = minfo.getAdminList()
        return serverAdmins.isAdmin(user)
Example #29
0
    def _checkParams(self, params):
        admins.RHAdminBase._checkParams(self, params)
        self.__defaultConferencePDFOptions = (
            HelperMaKaCInfo.getMaKaCInfoInstance().getDefaultConference(
            ).getBadgeTemplateManager().getPDFOptions())

        try:
            self.__marginTop = float(params.get("marginTop", ''))
        except ValueError:
            self.__marginTop = self.__defaultConferencePDFOptions.getTopMargin(
            )

        try:
            self.__marginBottom = float(params.get("marginBottom", ''))
        except ValueError:
            self.__marginBottom = self.__defaultConferencePDFOptions.getBottomMargin(
            )

        try:
            self.__marginLeft = float(params.get("marginLeft", ''))
        except ValueError:
            self.__marginLeft = self.__defaultConferencePDFOptions.getLeftMargin(
            )

        try:
            self.__marginRight = float(params.get("marginRight", ''))
        except ValueError:
            self.__marginRight = self.__defaultConferencePDFOptions.getRightMargin(
            )

        try:
            self.__marginColumns = float(params.get("marginColumns", ''))
        except ValueError:
            self.__marginColumns = self.__defaultConferencePDFOptions.getMarginColumns(
            )

        try:
            self.__marginRows = float(params.get("marginRows", ''))
        except ValueError:
            self.__marginRows = self.__defaultConferencePDFOptions.getMarginRows(
            )

        self.__pagesize = params.get("pagesize", 'A4')

        self.__drawDashedRectangles = params.get("drawDashedRectangles",
                                                 False) is not False
        self.__landscape = params.get('landscape') == '1'
Example #30
0
File: app.py Project: k3njiy/indico
def setup_jinja(app):
    config = Config.getInstance()
    # Unicode hack
    app.jinja_env.add_extension(EnsureUnicodeExtension)
    app.add_template_filter(EnsureUnicodeExtension.ensure_unicode)
    # Global functions
    app.add_template_global(url_for)
    app.add_template_global(url_for_plugin)
    app.add_template_global(url_rule_to_js)
    app.add_template_global(IndicoConfigWrapper(config), "indico_config")
    app.add_template_global(config.getSystemIconURL, "system_icon")
    app.add_template_global(include_css_assets)
    app.add_template_global(include_js_assets)
    app.add_template_global(include_plugin_css_assets)
    app.add_template_global(include_plugin_js_assets)
    app.add_template_global(call_template_hook, "template_hook")
    app.add_template_global(is_single_line_field, "_is_single_line_field")
    app.add_template_global(render_field, "_render_field")
    app.add_template_global(format_currency)
    app.add_template_global(get_currency_name)
    app.add_template_global(url_for_login)
    app.add_template_global(url_for_logout)
    # Filters (indico functions returning UTF8)
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_time))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta))
    # Filters (new ones returning unicode)
    app.add_template_filter(date_time_util.format_human_timedelta)
    app.add_template_filter(lambda d: Markup(html_params(**d)), "html_params")
    app.add_template_filter(underline)
    app.add_template_filter(markdown)
    app.add_template_filter(dedent)
    app.add_template_filter(natsort)
    app.add_template_filter(groupby)
    app.add_template_filter(any)
    # Tests
    app.add_template_test(instanceof)  # only use this test if you really have to!
    app.add_template_test(equalto)
    # i18n
    app.jinja_env.add_extension("jinja2.ext.i18n")
    app.jinja_env.install_gettext_callables(gettext_context, ngettext_context, True)
    app.add_template_global(lambda: HelperMaKaCInfo.getMaKaCInfoInstance().getLang(), "get_default_language")
    # webassets
    app.jinja_env.add_extension("webassets.ext.jinja2.AssetsExtension")
    app.jinja_env.assets_environment = core_env
Example #31
0
 def _process(self):
     if not self._cancel:
         modpay = self._conf.getModPay()
         params = self._getRequestParams()
         #modpay.getModPayLater().setValues(params)
         modpay.setPaymentDetails(params.get("detailPayment", ""))
         modpay.setPaymentSpecificConditions(
             params.get("specificConditionsPayment", ""))
         from MaKaC.common import HelperMaKaCInfo
         minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
         al = minfo.getAdminList()
         if al.isAdmin(self._getUser()):
             modpay.setPaymentConditions(params.get("conditionsPayment",
                                                    ""))
             modpay.setPaymentConditionsEnabled(
                 params.has_key("conditionsEnabled"))
     self._redirect(urlHandlers.UHConfModifEPayment.getURL(self._conf))
Example #32
0
def format_time(t,
                format='short',
                locale=None,
                timezone=None,
                server_tz=False):
    """
    Basically a wrapper around Babel's own format_time
    """
    if not locale:
        locale = get_current_locale()
    if not timezone and t.tzinfo:
        timezone = DisplayTZ().getDisplayTZ()
    elif server_tz:
        timezone = HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()
    if timezone:
        timezone = get_timezone(timezone)

    return _format_time(t, format=format, locale=locale,
                        tzinfo=timezone).encode('utf-8')
Example #33
0
def initialize_new_db(root):
    """
    Initializes a new DB in debug mode
    """

    # Reset everything
    for e in root.keys():
        del root[e]

    # initialize db root
    cm = CategoryManager()
    cm.getRoot()

    home = cm.getById('0')

    # set debug mode on
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    minfo.setDebugActive(True)

    return home
Example #34
0
def initialize_new_db(root):
    """
    Initializes a new DB in debug mode
    """

    # Reset everything
    for e in root.keys():
        del root[e]

    # initialize db root
    cm = CategoryManager()
    cm.getRoot()

    home = cm.getById('0')

    # set debug mode on
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    minfo.setDebugActive(True)

    return home
Example #35
0
def format_datetime(dt,
                    format='medium',
                    locale=None,
                    timezone=None,
                    server_tz=False,
                    keep_tz=False):
    """
    Basically a wrapper around Babel's own format_datetime
    """
    if not locale:
        locale = get_current_locale()
    if keep_tz:
        assert timezone is None
        timezone = dt.tzinfo
    elif not timezone and dt.tzinfo:
        timezone = DisplayTZ().getDisplayTZ()
    elif server_tz:
        timezone = HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone()

    return _format_datetime(dt, format=format, locale=locale,
                            tzinfo=timezone).encode('utf-8')
Example #36
0
    def _checkParams( self, params ):
        admins.RHAdminBase._checkParams( self, params )
        self.__defaultConferencePDFOptions = (HelperMaKaCInfo.getMaKaCInfoInstance().getDefaultConference()
                                              .getBadgeTemplateManager().getPDFOptions())

        try:
            self.__marginTop = float(params.get("marginTop",''))
        except ValueError:
            self.__marginTop = self.__defaultConferencePDFOptions.getTopMargin()

        try:
            self.__marginBottom = float(params.get("marginBottom",''))
        except ValueError:
            self.__marginBottom = self.__defaultConferencePDFOptions.getBottomMargin()

        try:
            self.__marginLeft = float(params.get("marginLeft",''))
        except ValueError:
            self.__marginLeft = self.__defaultConferencePDFOptions.getLeftMargin()

        try:
            self.__marginRight = float(params.get("marginRight",''))
        except ValueError:
            self.__marginRight = self.__defaultConferencePDFOptions.getRightMargin()

        try:
            self.__marginColumns = float(params.get("marginColumns",''))
        except ValueError:
            self.__marginColumns = self.__defaultConferencePDFOptions.getMarginColumns()

        try:
            self.__marginRows = float(params.get("marginRows",''))
        except ValueError:
            self.__marginRows = self.__defaultConferencePDFOptions.getMarginRows()

        self.__pagesize = params.get("pagesize",'A4')

        self.__drawDashedRectangles = params.get("drawDashedRectangles", False) is not False
        self.__landscape = params.get('landscape') == '1'
Example #37
0
    def _create_user(self, form, handler, pending_user):
        data = form.data
        if pending_user:
            user = pending_user
            user.is_pending = False
        else:
            user = User()
        form.populate_obj(user, skip={'email'})
        if form.email.data 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(form.email.data)
        else:
            user.email = form.email.data
        identity = handler.create_identity(data)
        user.identities.add(identity)
        user.secondary_emails |= handler.get_all_emails(form) - {user.email}
        user.favorite_users.add(user)
        db.session.add(user)
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        timezone = session.timezone
        if timezone == 'LOCAL':
            timezone = Config.getInstance().getDefaultTimezone()
        user.settings.set('timezone', timezone)
        user.settings.set('lang', session.lang or minfo.getLang())
        handler.update_user(user, form)
        db.session.flush()

        # notify everyone of user creation
        signals.users.registered.send(user)

        login_user(user, identity)
        msg = _('You have sucessfully registered your Indico profile. '
                'Check <a href="{url}">your profile</a> for further details and settings.')
        flash(Markup(msg).format(url=url_for('users.user_profile')), 'success')
        db.session.flush()
        return handler.redirect_success()
Example #38
0
    def _create_user(self, form, handler, pending_user):
        data = form.data
        if pending_user:
            user = pending_user
            user.is_pending = False
        else:
            user = User()
        form.populate_obj(user, skip={'email'})
        if form.email.data 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(form.email.data)
        else:
            user.email = form.email.data
        identity = handler.create_identity(data)
        user.identities.add(identity)
        user.secondary_emails |= handler.get_all_emails(form) - {user.email}
        user.favorite_users.add(user)
        db.session.add(user)
        minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
        timezone = session.timezone
        if timezone == 'LOCAL':
            timezone = Config.getInstance().getDefaultTimezone()
        user.settings.set('timezone', timezone)
        user.settings.set('lang', session.lang or minfo.getLang())
        handler.update_user(user, form)
        db.session.flush()

        # notify everyone of user creation
        signals.users.registered.send(user)

        login_user(user, identity)
        msg = _('You have sucessfully registered your Indico profile. '
                'Check <a href="{url}">your profile</a> for further details and settings.')
        flash(Markup(msg).format(url=url_for('users.user_profile')), 'success')
        db.session.flush()
        return handler.redirect_success()
Example #39
0
 def __init__(self, conference):
     if conference.getId() == "default":
         #Best values for CERN printing service
         self.__topMargin = 1.6
         self.__bottomMargin = 1.1
         self.__leftMargin = 1.6
         self.__rightMargin = 1.4
         self.__marginColumns = 1.0
         self.__marginRows = 0.0
         self._pageSize = "A4"
         self._landscape = False
         self._drawDashedRectangles = True
     else:
         defaultConferencePDFOptions = (HelperMaKaCInfo.getMaKaCInfoInstance().getDefaultConference()
                                        .getBadgeTemplateManager().getPDFOptions())
         self.__topMargin = defaultConferencePDFOptions.getTopMargin()
         self.__bottomMargin = defaultConferencePDFOptions.getBottomMargin()
         self.__leftMargin = defaultConferencePDFOptions.getLeftMargin()
         self.__rightMargin = defaultConferencePDFOptions.getRightMargin()
         self.__marginColumns = defaultConferencePDFOptions.getMarginColumns()
         self.__marginRows = defaultConferencePDFOptions.getMarginRows()
         self._pageSize = defaultConferencePDFOptions.getPagesize()
         self._landscape = defaultConferencePDFOptions.getLandscape()
         self._drawDashedRectangles = defaultConferencePDFOptions.getDrawDashedRectangles()
Example #40
0
 def unique(self):
     # We cannot have self.env available here so we take the debug flag from makacinfo instead.
     debug = HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
     return self.name, self.required_level, debug
Example #41
0
def utc_to_server(dt):
    """Converts the given UTC datetime to the server's TZ."""
    server_tz = get_timezone(
        HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone())
    return dt.astimezone(server_tz)
Example #42
0
 def _checkParams(self, params):
     RHProtected._checkParams(self, params)
     self._minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
Example #43
0
 def getTimezone(self):
     return self.user.settings.get('timezone', HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone())
Example #44
0
 def _checkParams(self, params):
     RHProtected._checkParams(self, params)
     self._minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
Example #45
0
 def getTimezone(self):
     return self.user.settings.get(
         'timezone',
         HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone())
Example #46
0
def utc_to_server(dt):
    """Converts the given UTC datetime to the server's TZ."""
    server_tz = get_timezone(HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone())
    return dt.astimezone(server_tz)
Example #47
0
 def debug(self):
     with DBMgr.getInstance().global_connection():
         return HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
Example #48
0
 def getLang(self):
     return self.user.settings.get('lang') if self.user else HelperMaKaCInfo.getMaKaCInfoInstance().getLang()
Example #49
0
 def _handleSet(self):
     styleMgr = HelperMaKaCInfo.getMaKaCInfoInstance().getStyleManager()
     if self._value == styleMgr.getDefaultStyleForEventType(self._conf.getType()):
         layout_settings.delete(self._conf, 'timetable_theme')
     else:
         layout_settings.set(self._conf, 'timetable_theme', self._value)
Example #50
0
    def _getSectionsHTML(self):
        modPay = self._conf.getModPay()
        html = []
        enabledBulb = Configuration.Config.getInstance().getSystemIconURL(
            "enabledSection")
        notEnabledBulb = Configuration.Config.getInstance().getSystemIconURL(
            "disabledSection")
        enabledText = _("Click to disable")
        disabledText = _("Click to enable")
        for gs in modPay.getSortedModPay():

            urlStatus = urlHandlers.UHConfModifEPaymentEnableSection.getURL(
                self._conf)
            urlStatus.addParam("epayment", gs.getId())
            urlModif = gs.getConfModifEPaymentURL(self._conf)
            img = enabledBulb
            text = enabledText
            if not gs.isEnabled():
                img = notEnabledBulb
                text = disabledText

            # CERN Plugin: Just admins can see and modify it
            if gs.getId() == "CERNYellowPay":
                minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
                al = minfo.getAdminList()
                if not al.isAdmin(self._user):
                    from MaKaC.plugins.EPayment.CERNYellowPay.options import globalOptions
                    endis = "enable"
                    departmentName = globalOptions[1][1]["defaultValue"]
                    emailAddress = globalOptions[0][1]["defaultValue"]
                    if gs.isEnabled():
                        endis = "disable"
                        emailAddress = minfo.getSupportEmail()
                        departmentName = "Indico support"
                    html.insert(
                        0, """
                        <tr>
                        <td>
                            <img src=%s alt="%s" class="imglink">&nbsp;&nbsp;<b>CERN E-Payment</b> <small>
                            (please, contact <a href="mailto:%s?subject=Indico Epayment - Conference ID: %s">%s</a> to %s 
                            the CERN e-payment module)</small>
                        </td>
                        </tr>
                        """ % (img, text, emailAddress, self._conf.getId(),
                               departmentName, endis))
                    continue
            #################################################

            selbox = ""
            html.append("""
                        <tr>
                        <td>
                            <a href=%s><img src=%s alt="%s" class="imglink"></a>&nbsp;%s&nbsp;<a href=%s>%s</a>
                        </td>
                        </tr>
                        """ % (quoteattr(str(urlStatus)), img, text, selbox,
                               quoteattr(str(urlModif)), gs.getTitle()))
        html.insert(
            0,
            """<a href="" name="sections"></a><input type="hidden" name="oldpos"><table align="left">"""
        )
        html.append("</table>")
        return "".join(html)
Example #51
0
 def getLang(self):
     return self.user.settings.get(
         'lang') if self.user else HelperMaKaCInfo.getMaKaCInfoInstance(
         ).getLang()