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)
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
def getInstance(cls): connector = ContextManager.get('ldap.connector', default=None) if not connector: connector = cls() connector.open() connector.login() return connector
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
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'))
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)
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)
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
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
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
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)
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()
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'))
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)
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
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()
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)
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)
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
def getScriptBaseURL(self): if ContextManager.get('offlineMode', False): return 'static/js' else: return url_parse('%s/js' % self.getBaseURL()).path
def getFontsBaseURL(self): if ContextManager.get('offlineMode', False): return "static/fonts" else: return url_parse("%s/fonts" % self.getBaseURL()).path
def getImagesBaseSecureURL(self): if ContextManager.get('offlineMode', False): return "static/images" else: return url_parse("%s/images" % self.getBaseSecureURL()).path
def flush_after_commit_queue(execute): queue = ContextManager.get('afterCommitQueue', []) if execute: for func in queue: func() del queue[:]
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)
def getImagesBaseSecureURL(self): if ContextManager.get('offlineMode', False): return "static/images" else: return "%s/images" % self.getBaseSecureURL()
def getImagesBaseSecureURL(self): if ContextManager.get("offlineMode", False): return "static/images" else: return url_parse("%s/images" % self.getBaseSecureURL()).path
def getCssBaseURL(self): if ContextManager.get('offlineMode', False): return "static/css" else: return url_parse("%s/css" % self.getBaseURL()).path
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)
def wrapper(*args, **kwargs): func = partial(f, *args, **kwargs) if not ContextManager.get('currentRH', None): return func() ContextManager.setdefault('afterCommitQueue', []).append(func)
def getCssBaseURL(self): if ContextManager.get("offlineMode", False): return "static/css" else: return "%s/css" % self.getBaseURL()
def getScriptBaseURL(self): if ContextManager.get("offlineMode", False): return "static/js" else: return url_parse("%s/js" % self.getBaseURL()).path
def getCssBaseURL(self): if ContextManager.get('offlineMode', False): return "static/css" else: return "%s/css" % self.getBaseURL()
def _get_redis_write_client(): if ContextManager.get('currentRH', None): return _get_redis_pipeline() return _get_redis_client()
def _tr_eval(func, *args, **kwargs): if 'translation' in ContextManager.get(): tr = ContextManager.get('translation') else: tr = nullTranslations return getattr(tr, func)(*args, **kwargs)
def getFontsBaseURL(self): if ContextManager.get('offlineMode', False): return "static/fonts" else: return "%s/fonts" % self.getBaseURL()
def destroy(cls): connector = ContextManager.get('ldap.connector', default=None) if connector: connector.close() ContextManager.delete('ldap.connector', silent=True)