Esempio n. 1
0
 def _wrapper(self, func, *args, **kwargs):
     # if there is a locale already defined, use it
     # (unless we have forced "lazy mode")
     if 'translation' in ContextManager.get() and not self.force:
         # straight translation
         translation = ContextManager.get('translation')
         return getattr(translation, func)(*args, **kwargs)
     else:
         # otherwise, defer translation to eval time
         return LazyProxy(_tr_eval, func, *args, **kwargs)
Esempio n. 2
0
 def _wrapper(self, func, *args, **kwargs):
     # if there is a locale already defined, use it
     # (unless we have forced "lazy mode")
     if 'translation' in ContextManager.get() and not self.force:
         # straight translation
         translation = ContextManager.get('translation')
         return getattr(translation, func)(*args, **kwargs)
     else:
         # otherwise, defer translation to eval time
         return LazyProxy(_tr_eval, func, *args, **kwargs)
Esempio n. 3
0
def _tr_eval(func, *args, **kwargs):
    # ok, eval time... is there a translation?

    if 'translation' in ContextManager.get():
        # yes? good, let's do it
        tr = ContextManager.get('translation')
    else:
        # no? too bad, just don't translate anything
        tr = nullTranslations
    res = getattr(tr, func)(*args, **kwargs).encode('utf-8')
    return res
Esempio n. 4
0
def _tr_eval(func, *args, **kwargs):
    # ok, eval time... is there a translation?

    if 'translation' in ContextManager.get():
        # yes? good, let's do it
        tr = ContextManager.get('translation')
    else:
        # no? too bad, just don't translate anything
        tr = nullTranslations
    res = getattr(tr, func)(*args, **kwargs).encode('utf-8')
    return res
Esempio n. 5
0
 def getInstance(cls):
     connector = ContextManager.get('ldap.connector', default=None)
     if not connector:
         connector = cls()
         connector.open()
         connector.login()
     return connector
Esempio n. 6
0
 def url(self):
     # explicit _external=False since offline site creation forces
     # _external=True if not specified and we want to be able to mangle
     # the generated urls into something suitable as filenames
     if self.is_user_link:
         return self.link_url
     elif self.is_internal_link:
         data = self.default_data
         if data.static_site and isinstance(data.static_site, basestring) and ContextManager.get('offlineMode'):
             return data.static_site
         kwargs = {}
         if self.name == 'timetable':
             from indico.modules.events. layout import layout_settings
             if layout_settings.get(self.event, 'timetable_by_room'):
                 kwargs['ttLyt'] = 'room'
             if layout_settings.get(self.event, 'timetable_detailed'):
                 start_date = self.event.getSchedule().getAdjustedStartDate()
                 kwargs['_anchor'] = start_date.strftime('%Y%m%d.detailed')
         return url_for(data.endpoint, self.event, _external=False, **kwargs)
     elif self.is_plugin_link:
         from indico.core.plugins import url_for_plugin
         return url_for_plugin(self.default_data.endpoint, self.event, _external=False)
     elif self.is_page:
         return url_for('event_pages.page_display', self.event, page_id=self.page_id, slug=slugify(self.title),
                        _external=False)
     else:
         return None
Esempio n. 7
0
def _define_lookup():
    return IndicoTemplateLookup(directories=[TEMPLATE_DIR],
                                module_directory=os.path.join(Config.getInstance().getTempDir(), "mako_modules"),
                                disable_unicode=True,
                                filesystem_checks=True,
                                imports=FILTER_IMPORTS,
                                cache_enabled=not ContextManager.get('offlineMode'))
Esempio n. 8
0
    def getPluginIconURL(self, pluginName, iconId):
        rh = ContextManager.get('currentRH', None)

        if rh and rh._req.is_https() and self.getBaseSecureURL():
            baseURL = self.getBaseSecureURL()
        else:
            baseURL = self.getBaseURL()
        return "%s/%s/images/%s.png" % (baseURL, pluginName, iconId)
Esempio n. 9
0
    def getPluginIconURL( self, pluginName, iconId ):
        rh = ContextManager.get('currentRH', None)

        if rh and request.is_secure and self.getBaseSecureURL():
            baseURL = self.getBaseSecureURL()
        else:
            baseURL = self.getBaseURL()
        return "%s/%s/images/%s.png"%(baseURL, pluginName, iconId)
Esempio n. 10
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 `locator` property or `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(get_locator(target))
        intersection = set(locator.iterkeys()) & set(values.iterkeys())
        if intersection:
            raise ValueError('url_for kwargs collide with locator: %s' %
                             ', '.join(intersection))
        values.update(locator)

    static_site_mode = bool(ContextManager.get('offlineMode'))
    values.setdefault('_external', static_site_mode)

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

    url = _url_for(endpoint, **values)
    if static_site_mode and not values['_external']:
        # for static sites we assume all relative urls need to be
        # mangled to a filename
        # we should really fine a better way to handle anything
        # related to offline site urls...
        from indico.modules.events.static.util import url_to_static_filename
        url = url_to_static_filename(url)
    return url
Esempio n. 11
0
 def add(self, newItem):
     oid = ""
     try:
         oid = newItem._p_oid
     except:
         raise MaKaCError( _("Cannot put an object which is not persistent in the trash can."))
     tree = self._getIdx()
     if not (ContextManager.get('test_env')):
         tree[oid] = newItem
Esempio n. 12
0
    def getCssConfTemplateBaseURL(self):
        rh = ContextManager.get('currentRH', None)

        if rh and request.is_secure and self.getBaseSecureURL():
            baseURL = self.getBaseSecureURL()
        else:
            baseURL = self.getBaseURL()

        return "%s/css/confTemplates" % baseURL
Esempio n. 13
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 `locator` property or `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(get_locator(target))
        intersection = set(locator.iterkeys()) & set(values.iterkeys())
        if intersection:
            raise ValueError('url_for kwargs collide with locator: %s' % ', '.join(intersection))
        values.update(locator)

    static_site_mode = bool(ContextManager.get('offlineMode'))
    values.setdefault('_external', static_site_mode)

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

    url = _url_for(endpoint, **values)
    if static_site_mode and not values['_external']:
        # for static sites we assume all relative urls need to be
        # mangled to a filename
        # we should really fine a better way to handle anything
        # related to offline site urls...
        from indico.modules.events.static.util import url_to_static_filename
        url = url_to_static_filename(url)
    return url
Esempio n. 14
0
    def getCssConfTemplateBaseURL(self):
        rh = ContextManager.get('currentRH', None)

        if rh and request.is_secure and self.getBaseSecureURL():
            baseURL = self.getBaseSecureURL()
        else:
            baseURL = self.getBaseURL()

        return "%s/css/confTemplates" % baseURL
Esempio n. 15
0
    def is_visible(self):
        if not self.is_enabled:
            return False
        if not self.name:
            return True
        if self.is_orphaned:
            return False

        data = self.default_data
        if not data.static_site and ContextManager.get('offlineMode'):
            return False
        return data.visible(self.event)
Esempio n. 16
0
    def setNotifyMgrNewParticipant(self, value):
        currentUser = ContextManager.get('currentUser')
        self._notifyMgrNewParticipant = value
        logData = {}

        if value:
            logData["subject"] = _("Manager notification of participant application has been enabled")
        else:
            logData["subject"] = _("Manager notification of participant application has been disabled")

        self._conference.getLogHandler().logAction(logData, "participants", currentUser)
        self.notifyModification()
Esempio n. 17
0
    def is_visible(self):
        if not self.is_enabled:
            return False
        if not self.name:
            return True
        if self.is_orphaned:
            return False

        data = self.default_data
        if not data.static_site and ContextManager.get('offlineMode'):
            return False
        return data.visible(self.event)
Esempio n. 18
0
def _define_lookup():
    # TODO: disable_unicode shouldn't be used
    # since unicode is disabled, template waits for
    # byte strings provided by default_filters
    # i.e converting SQLAlchemy model unicode properties to byte strings
    return IndicoTemplateLookup(directories=[TEMPLATE_DIR],
                                module_directory=os.path.join(Config.getInstance().getTempDir(), "mako_modules"),
                                disable_unicode=True,
                                input_encoding='utf-8',
                                default_filters=['encode_if_unicode', 'str'],
                                filesystem_checks=True,
                                imports=FILTER_IMPORTS,
                                cache_enabled=not ContextManager.get('offlineMode'))
Esempio n. 19
0
    def get_download_url(self, absolute=False):
        """Returns the download url for the attachment.

        During static site generation this returns a local URL for the
        file or the target URL for the link.

        :param absolute: If the returned URL should be absolute.
        """
        if ContextManager.get('offlineMode'):
            return _offline_download_url(self)
        else:
            filename = self.file.filename if self.type == AttachmentType.file else 'go'
            return url_for('attachments.download', self, filename=filename, _external=absolute)
Esempio n. 20
0
def _define_lookup():
    # TODO: disable_unicode shouldn't be used
    # since unicode is disabled, template waits for
    # byte strings provided by default_filters
    # i.e converting SQLAlchemy model unicode properties to byte strings
    return IndicoTemplateLookup(directories=[TEMPLATE_DIR],
                                module_directory=os.path.join(Config.getInstance().getTempDir(), "mako_modules"),
                                disable_unicode=True,
                                input_encoding='utf-8',
                                default_filters=['encode_if_unicode', 'str'],
                                filesystem_checks=True,
                                imports=FILTER_IMPORTS,
                                cache_enabled=not ContextManager.get('offlineMode'))
Esempio n. 21
0
def _get_redis_pipeline():
    rh = ContextManager.get('currentRH', None)
    if not rh:
        # If you are reading this because you tried to use this e.g. in a migration script
        # or somewhere else outside a RH context: Use `with client.pipeline() as pipe:` and
        # execute it on your own. The sole reason why this pipeline accessor exists is that
        # the pipeline can be properly executed/discarded in case of a DB commit/conflict.
        raise Exception('Cannot get Redis pipeline outside a request')
    if rh._redisPipeline:
        return rh._redisPipeline
    if not client:
        return None
    rh._redisPipeline = client.pipeline(transaction=False)
    return rh._redisPipeline
Esempio n. 22
0
def _get_redis_pipeline():
    rh = ContextManager.get('currentRH', None)
    if not rh:
        # If you are reading this because you tried to use this e.g. in a migration script
        # or somewhere else outside a RH context: Use `with client.pipeline() as pipe:` and
        # execute it on your own. The sole reason why this pipeline accessor exists is that
        # the pipeline can be properly executed/discarded in case of a DB commit/conflict.
        raise Exception('Cannot get Redis pipeline outside a request')
    if rh._redisPipeline:
        return rh._redisPipeline
    if not client:
        return None
    rh._redisPipeline = client.pipeline(transaction=False)
    return rh._redisPipeline
Esempio n. 23
0
    def get_download_url(self, absolute=False):
        """Returns the download url for the attachment.

        During static site generation this returns a local URL for the
        file or the target URL for the link.

        :param absolute: If the returned URL should be absolute.
        """
        if ContextManager.get('offlineMode'):
            return _offline_download_url(self)
        else:
            filename = self.file.filename if self.type == AttachmentType.file else 'go'
            return url_for('attachments.download',
                           self,
                           filename=filename,
                           _external=absolute)
Esempio n. 24
0
    def setNotifyMgrNewParticipant(self, value):
        currentUser = ContextManager.get('currentUser')
        self._notifyMgrNewParticipant = value
        logData = {}

        if value:
            logData["subject"] = _(
                "Manager notification of participant application has been enabled"
            )
        else:
            logData["subject"] = _(
                "Manager notification of participant application has been disabled"
            )

        self._conference.getLogHandler().logAction(
            logData, log.ModuleNames.PARTICIPANTS)
        self.notifyModification()
Esempio n. 25
0
    def __init__(self, user, logInfo, module):
        self._logId = None
        self._logDate = nowutc()
        self._logType = "generalLog"

        # User who has performed / authorised the logged action
        self._responsibleUser = user if user else ContextManager.get("currentUser")

        # Indico module, the logged action comes from
        self._module = module

        # DICTIONARY containing infos that have to be logged
        # MUST CONTAIN entry with key : "subject"
        # keys as well as values should be meaningful
        self._logInfo = logInfo
        if self._logInfo.get("subject", None) is None :
            self._logInfo["subject"] = "%s : %s : %s" % (self._logDate,
                                                         self._module,
                                                         self._logType)
Esempio n. 26
0
    def __init__(self, user, logInfo, module):
        self._logId = None
        self._logDate = nowutc()
        self._logType = "generalLog"

        # User who has performed / authorised the logged action
        self._responsibleUser = user if user else ContextManager.get(
            "currentUser")

        # Indico module, the logged action comes from
        self._module = module

        # DICTIONARY containing infos that have to be logged
        # MUST CONTAIN entry with key : "subject"
        # keys as well as values should be meaningful
        self._logInfo = logInfo
        if self._logInfo.get("subject", None) is None:
            self._logInfo["subject"] = "%s : %s : %s" % (
                self._logDate, self._module, self._logType)
Esempio n. 27
0
 def url(self):
     # explicit _external=False since offline site creation forces
     # _external=True if not specified and we want to be able to mangle
     # the generated urls into something suitable as filenames
     if self.is_user_link:
         return self.link_url
     elif self.is_internal_link:
         data = self.default_data
         if data.static_site and isinstance(
                 data.static_site,
                 basestring) and ContextManager.get('offlineMode'):
             return data.static_site
         kwargs = {}
         if self.name == 'timetable':
             from indico.modules.events.layout import layout_settings
             if layout_settings.get(self.event, 'timetable_by_room'):
                 kwargs['ttLyt'] = 'room'
             if layout_settings.get(self.event, 'timetable_detailed'):
                 start_date = self.event.getSchedule().getAdjustedStartDate(
                 )
                 kwargs['_anchor'] = start_date.strftime('%Y%m%d.detailed')
         return url_for(data.endpoint,
                        self.event,
                        _external=False,
                        **kwargs)
     elif self.is_plugin_link:
         from indico.core.plugins import url_for_plugin
         return url_for_plugin(self.default_data.endpoint,
                               self.event,
                               _external=False)
     elif self.is_page:
         return url_for('event_pages.page_display',
                        self.event,
                        page_id=self.page_id,
                        slug=slugify(self.title),
                        _external=False)
     else:
         return None
Esempio n. 28
0
 def getScriptBaseURL(self):
     if ContextManager.get('offlineMode', False):
         return 'static/js'
     else:
         return url_parse('%s/js' % self.getBaseURL()).path
Esempio n. 29
0
 def getFontsBaseURL(self):
     if ContextManager.get('offlineMode', False):
         return "static/fonts"
     else:
         return url_parse("%s/fonts" % self.getBaseURL()).path
Esempio n. 30
0
 def getImagesBaseSecureURL(self):
     if ContextManager.get('offlineMode', False):
         return "static/images"
     else:
         return url_parse("%s/images" % self.getBaseSecureURL()).path
Esempio n. 31
0
def flush_after_commit_queue(execute):
    queue = ContextManager.get('afterCommitQueue', [])
    if execute:
        for func in queue:
            func()
    del queue[:]
Esempio n. 32
0
 def _getMenu(self):
     for link in self._sectionMenu.getLinkList():
         if isinstance(link, SystemLink) and link.getName(
         ) not in ContextManager.get("_menu_offline_items"):
             link.setVisible(False)
Esempio n. 33
0
 def getImagesBaseSecureURL(self):
     if ContextManager.get('offlineMode', False):
         return "static/images"
     else:
         return "%s/images" % self.getBaseSecureURL()
Esempio n. 34
0
 def getImagesBaseSecureURL(self):
     if ContextManager.get("offlineMode", False):
         return "static/images"
     else:
         return url_parse("%s/images" % self.getBaseSecureURL()).path
Esempio n. 35
0
 def getCssBaseURL(self):
     if ContextManager.get('offlineMode', False):
         return "static/css"
     else:
         return url_parse("%s/css" % self.getBaseURL()).path
Esempio n. 36
0
 def getScriptBaseURL(self):
     if ContextManager.get('offlineMode', False):
         return 'static/js'
     else:
         return url_parse('%s/js' % self.getBaseURL()).path
Esempio n. 37
0
 def _getMenu(self):
     for link in self._sectionMenu.getLinkList():
         if isinstance(link, SystemLink) and link.getName() not in ContextManager.get("_menu_offline_items"):
             link.setVisible(False)
Esempio n. 38
0
 def wrapper(*args, **kwargs):
     func = partial(f, *args, **kwargs)
     if not ContextManager.get('currentRH', None):
         return func()
     ContextManager.setdefault('afterCommitQueue', []).append(func)
Esempio n. 39
0
def flush_after_commit_queue(execute):
    queue = ContextManager.get('afterCommitQueue', [])
    if execute:
        for func in queue:
            func()
    del queue[:]
Esempio n. 40
0
 def getCssBaseURL(self):
     if ContextManager.get("offlineMode", False):
         return "static/css"
     else:
         return "%s/css" % self.getBaseURL()
Esempio n. 41
0
 def getScriptBaseURL(self):
     if ContextManager.get("offlineMode", False):
         return "static/js"
     else:
         return url_parse("%s/js" % self.getBaseURL()).path
Esempio n. 42
0
 def getCssBaseURL(self):
     if ContextManager.get('offlineMode', False):
         return "static/css"
     else:
         return "%s/css" % self.getBaseURL()
Esempio n. 43
0
def _get_redis_write_client():
    if ContextManager.get('currentRH', None):
        return _get_redis_pipeline()
    return _get_redis_client()
Esempio n. 44
0
def _tr_eval(func, *args, **kwargs):
    if 'translation' in ContextManager.get():
        tr = ContextManager.get('translation')
    else:
        tr = nullTranslations
    return getattr(tr, func)(*args, **kwargs)
Esempio n. 45
0
def _tr_eval(func, *args, **kwargs):
    if 'translation' in ContextManager.get():
        tr = ContextManager.get('translation')
    else:
        tr = nullTranslations
    return getattr(tr, func)(*args, **kwargs)
Esempio n. 46
0
 def getFontsBaseURL(self):
     if ContextManager.get('offlineMode', False):
         return "static/fonts"
     else:
         return "%s/fonts" % self.getBaseURL()
Esempio n. 47
0
 def destroy(cls):
     connector = ContextManager.get('ldap.connector', default=None)
     if connector:
         connector.close()
         ContextManager.delete('ldap.connector', silent=True)
Esempio n. 48
0
def _get_redis_write_client():
    if ContextManager.get('currentRH', None):
        return _get_redis_pipeline()
    return _get_redis_client()
Esempio n. 49
0
 def wrapper(*args, **kwargs):
     func = partial(f, *args, **kwargs)
     if not ContextManager.get('currentRH', None):
         return func()
     ContextManager.setdefault('afterCommitQueue', []).append(func)