def getLanguage(self): try: request = get_request() if request and IHTTPRequest.providedBy(request): return request.getCookies().get(I18N_COOKIE_NAME) except zope.security.interfaces.NoInteraction: return None
def getter(item, formatter): value = getattr(item, name) if value: request = common.get_request() date_formatter = date.getLocaleFormatter(request, category, length) return date_formatter.format(value) return ""
def as_json(self): is_text = IScheduleText.implementedBy(self.domain_class) date_formatter = date.getLocaleFormatter(common.get_request(), "date", "medium") items = [ dict( item_type = self.item_type, item_id = orm.object_mapper(item).primary_key_from_instance( item )[0], item_title = item.text if \ is_text else IDCDescriptiveProperties(item).title, status = IWorkflow(item).get_state(item.status).title if not \ is_text else None, status_date = date_formatter.format(item.submission_date) if \ getattr(item, "submission_date", None) else None, registry_number = item.registry_number if \ hasattr(item, "registry_number") else None, item_mover = IDCDescriptiveProperties(item.owner).title if \ hasattr(item, "owner") else None, item_uri = "%s-%d" % (self.item_type, orm.object_mapper(item).primary_key_from_instance(item)[0] ) ) for item in self.query() ] items = sorted(items, key=lambda item: item.get("status_date"), reverse=True) return json.dumps(dict(items=items))
def get_request_context_roles(request): """Get the list of user's roles (including whether admin or not) relevant for this request layer. Wraps get_context_roles(context), with the following differences: - auto determines the context, a needed param for get_context_roles() - when within a public layer, always returns ["bungeni.Anonymous"] - handles case when user is not authenticated - handles case for when user is "admin" """ request = request or common.get_request() if request is None: context = None principal = None else: context = get_traversed_context(request) principal = request.principal # within a public layer, just proceed as "bungeni.Anonymous" if is_public_layer(request): return ["bungeni.Anonymous"] # other layers if IUnauthenticatedPrincipal.providedBy(principal): roles = ["bungeni.Anonymous"] else: roles = get_context_roles(context, principal) roles.append("bungeni.Authenticated") if is_admin(context): roles.append("bungeni.Admin") log.debug(""" [get_request_context_roles] PRINCIPAL: %s CONTEXT: %s ROLES: %s """ % (principal, context, roles)) return roles
def group_id(self): if IDoc.providedBy(self.context): if hasattr(self.context, "group_id") and self.context.group is not None: return IDCDescriptiveProperties(self.context.group).short_title elif hasattr(self.context, "chamber_id"): return IDCDescriptiveProperties(self.context.chamber).short_tile return translate("n/a", context=get_request())
def as_json(self): is_text = IScheduleText.implementedBy(self.domain_class) date_formatter = date.getLocaleFormatter(common.get_request(), "date", "medium" ) items = [ dict( item_type = self.item_type, item_id = orm.object_mapper(item).primary_key_from_instance( item )[0], item_title = item.text if \ is_text else IDCDescriptiveProperties(item).title, status = IWorkflow(item).get_state(item.status).title if not \ is_text else None, status_date = date_formatter.format(item.submission_date) if \ getattr(item, "submission_date", None) else None, registry_number = item.registry_number if \ hasattr(item, "registry_number") else None, item_mover = IDCDescriptiveProperties(item.owner).title if \ hasattr(item, "owner") else None, item_uri = "%s-%d" % (self.item_type, orm.object_mapper(item).primary_key_from_instance(item)[0] ) ) for item in self.query() ] items = sorted(items, key=lambda item:item.get("status_date"), reverse=True ) return json.dumps(dict(items=items))
def items_container(self): """The URL to a container listing documents available for scheduling """ site = getSite() container = site["workspace"]["scheduling"]["documents"] request = common.get_request() app_url = request.getApplicationURL() return url.absoluteURL(container, request).replace(app_url, "")
def getLanguage(self): try: request = get_request() if request: identity = request.environment.get('repoze.who.identity') if identity: return identity.get("home_language") except (zope.security.interfaces.NoInteraction, AttributeError): return None
def date_input_search_widget(table_id, field_id): form = DateFilterWidget(common.get_application(), common.get_request(), table_id, field_id) html = '<div id="date_input_search_widget_%(table_id)s_%(field_id)s" style="display: none;">%(html)s</div>' \ % {"table_id": table_id, "field_id": field_id, "html": form.render()} script = open("%s/templates/date-input-search-widget.js" % (_path)).read() return html, script % {"table_id": table_id, "field_id": field_id}
def translation_status(self): if ITranslatable.providedBy(self.context) and len(capi.pivot_languages): untranslated = list(capi.pivot_languages) if self.context.language in untranslated: untranslated.remove(self.context.language) for pivot_lang in untranslated: if translation.get_field_translations(self.context, pivot_lang): untranslated.remove(pivot_lang) if len(untranslated): i18n_langs = [] locale = locales.getLocale(get_default_language().split("-")[0], None) for lang in untranslated: if locale and locale.displayNames and locale.displayNames.languages: i18n_langs.append(locale.displayNames.languages.get(lang, lang)) continue i18n_langs.append(lang) return ", ".join(i18n_langs) return translate(_("translated"), context=get_request()) return translate("n/a", context=get_request())
def getter(item, formatter): request = common.get_request() start = getattr(item, from_name) if start: start = date.getLocaleFormatter(request, "dateTime", format_length).format(start) end = getattr(item, to_name) if end: end = date.getLocaleFormatter(request, "time", format_length).format(end) return "%s - %s" % (start, end)
def get_request_language(request=None, default=capi.default_language): """Get current request's language; if no request use specified default. If the request instance is handy, it may be passed in as a parameter thus avoidng the need to call for it. """ if request is None: request = get_request() if IHTTPRequest.providedBy(request): return request.locale.getLocaleID() return default
def make_admin_url(obj_id, type_name, status, context, chamber_id): """Use traversal to find parent parliament """ url = None chamber = get_parl_container(context, chamber_id) if chamber: items_container = get_type_container(chamber, type_name) if items_container: url = "/".join([ absoluteURL(items_container, get_request()), container_obj_key(obj_id) ]) return url
def translation_status(self): if ITranslatable.providedBy(self.context) and len(capi.pivot_languages): untranslated = list(capi.pivot_languages) if self.context.language in untranslated: untranslated.remove(self.context.language) for pivot_lang in untranslated: if translation.get_field_translations(self.context, pivot_lang): untranslated.remove(pivot_lang) if len(untranslated): i18n_langs = [] locale = locales.getLocale(get_default_language().split("-")[0], None) for lang in untranslated: if (locale and locale.displayNames and locale.displayNames.languages ): i18n_langs.append( locale.displayNames.languages.get(lang, lang)) continue i18n_langs.append(lang) return ", ".join(i18n_langs) return translate(_("translated"), context=get_request()) return translate("n/a", context=get_request())
def getLanguage(self): try: request = get_request() except zope.security.interfaces.NoInteraction: request=None if request is not None: browser_langs = BrowserLanguages(request) langs = browser_langs.getPreferredLanguages() try: return langs[0] except IndexError: return None else: return None
def _get_change_data(self): """If request defines change_data, use it, else return a dummy dict. !+ui.forms.workflow adds entries for: note, date_active, registry_number """ try: cd = IAnnotations(common.get_request()).get("change_data") assert cd is not None, "change_data dict is None." except (TypeError, AssertionError): # Could not adapt... under testing, the "request" is a # participation that has no IAnnotations. cd = {} cd.setdefault("note", cd.get("note", "")) cd.setdefault("date_active", cd.get("date_active", None)) return cd
def get_traversed_context(request=None, index=-1): """ (request:either(IRequest, None), indix:int) -> either(IRequest, None) Requires that the "contexts" list has been prepared on the request, see the event handler: bungeni.ui.publication.remember_traversed_context() As an optimization, if the caller already has a reference to the current request, it may optionally be passed in as a parameter. By default, we pick off the last traversed (as per "index"). """ if request is None: request = common.get_request() if request is not None: return IAnnotations(request).get("contexts")[index]
def getLocaleFormatter( request=None, category="date", # "date" | "time" | "dateTime" length="medium" # "short" | "medium" | "long" | "full" | None ): """See: zope.i18n.locales.LocaleDates.getFormatter """ if request is None: try: request = common.get_request() except NoInteraction: request = None if request and hasattr(request, "locale"): return request.locale.dates.getFormatter(category, length) else: return locales.getLocale(capi.default_language).dates.getFormatter( category, length)
def getter(item_user, formatter): related_user = _get_related_user(item_user, related_user_attribute_name) request = common.get_request() # !+ replace with: bungeni.ui.widgets._render_link_to_mp_or_user ? if IAdminSectionLayer.providedBy(request): # under admin, we link to the natural "view" of the schema relation parent = item_user while parent and not IAlchemistContainer.providedBy(parent): parent = removeSecurityProxy(parent.__parent__) item_user.__parent__ = parent href = url.absoluteURL(item_user, request) else: return related_user.combined_name return zope.formlib.widget.renderElement("a", contents=related_user.combined_name, # User.combined_name derived property href=href )
def getter(item, formatter): state_title = get_wf_state(item) request = common.get_request() state_title = translate(state_title, domain="bungeni", context=request) # !+MY_LISTING_ROWS(mr, aug-2012) the following is a (exploratory) # mechanism to add a distinction between what rows are owned by the # current user and others. Here it is added only to "status" columns # but a generic "row-level" means to mark such rows as different # from the others may be a useful feature. if IWorkspaceSectionLayer.providedBy(request): item_user = None if hasattr(item, "owner"): item_user = item.owner elif hasattr(item, "drafter"): item_user = item.drafter # !+delegation? if item_user and (item_user == get_login_user()): state_title = "<b>%s</b> *" % (state_title) return state_title
def getter(item_user, formatter): related_user = _get_related_user(item_user, related_user_attribute_name) request = common.get_request() # !+ replace with: bungeni.ui.widgets._render_link_to_mp_or_user ? if IAdminSectionLayer.providedBy(request): # under admin, we link to the natural "view" of the schema relation parent = item_user while parent and not IAlchemistContainer.providedBy(parent): parent = removeSecurityProxy(parent.__parent__) item_user.__parent__ = parent href = url.absoluteURL(item_user, request) else: return related_user.combined_name return zope.formlib.widget.renderElement( "a", contents=related_user. combined_name, # User.combined_name derived property href=href)
def __call__(self, context): try: request = get_request() except zope.security.interfaces.NoInteraction: request = None def get_locale_lang(code): if request and hasattr(request, "locale"): return request.locale.displayNames.languages.get(code) return None languages = get_all_languages() items = [ ( lang, (request and get_locale_lang(lang) or languages[lang]["name"]) ) for lang in languages.keys() ] items.sort(key=lambda language: language[1]) items = [ SimpleTerm(i[0], i[0], i[1]) for i in items ] return SimpleVocabulary(items)
def get_destination_url_path(request=None): """Get the (effective, sans any "traversal namespace notation" components and other such "traversal processing instruction" url components) target URL path of the (current) request. """ if request is None: request = common.get_request() #_url = request.URL #_url = request.getURL(level=0, path_only=True) # NOTE: both URL and getURL() depend on where we are in the traversal # process i.e. they return the *currently* traversed URL path and not # the full requested path. # # So, we use the request's PATH_INFO but as this may contain: # - (++) any number of Zope "traversal namespace notation" url components # - (@@/) to indicate that the URL is for an object that is a resource # - (@@)) to indicate a view name # we need to get rid of them: _url = "/".join([ url_component for url_component in request.get("PATH_INFO").split("/") if not url_component.startswith("++") and not url_component.startswith("@@") ]) log.debug(" [get_destination_url_path] %s ", _url) return _url
def status_date(self): value = self.context.status_date request = get_request() date_formatter = date.getLocaleFormatter(request, "dateTime", "medium") return date_formatter.format(value)
def status(self): status_title = get_object_state(self.context).title request = get_request() return translate(_(status_title), context=request)
def type(self): descriptor = utils.get_descriptor(self.context.__class__) item_type = descriptor.display_name if descriptor else self.context.type request = get_request() return translate(item_type, context=request)
def getLanguage(self): try: request = get_request() return get_request_language() except zope.security.interfaces.NoInteraction: return None
def default_reports(sitting, event): #!+REPORTS(mb, Feb-2013) - remove this handler for workflow events: # EITHER a publish_report action, maybe configure this as a workflow action # (so not hardwired to status/workflow event) # OR make it part of sitting feature options e.g. publish state and report # template. if "published" in sitting.status: sitting = removeSecurityProxy(sitting) report_type = "sitting_agenda" report_title = _("report_title_order_of_the_day", default=u"Order of the day") if "minutes" in sitting.status: report_type = "sitting_minutes" report_title = _("report_title_votes_and_proceedings", default=u"Votes and Proceedings") sittings = [ExpandedSitting(sitting)] report = domain.Report() session = Session() # !+GROUP_AS_OWNER(mr, apr-2012) we assume for now that the "owner" of # the report is the currently logged in user. report.owner_id = get_login_user().user_id report.created_date = datetime.datetime.now() report.group_id = sitting.group_id # !+ReportXHTMLTemplateFactory # generate using html template in bungeni_custom vocab = vocabulary.report_xhtml_template_factory(sitting) try: report_template_path = vocab.getTermByToken(report_type).value except LookupError: vtokens = [t.token for t in vocab._terms] # first check if we have any values in the reports vocab for this context if not vtokens: log.error( "Sitting %s Workflow Transition Handler - " "entry for report type %r NOT found in EMPTY vocabulary: %s", sitting, report_type, vtokens) raise # ok, as a tmp workaround, pick off the first term value in the reports vocab log.warning( "Sitting %s Workflow Transition Handler - " "entry for report type %r NOT found in vocabulary: %s - " "proceeding with the template for first entry found: %r ", sitting, report_type, vtokens, vtokens[0]) report_template_path = vocab._terms[0].value generator = generators.ReportGeneratorXHTML(report_template_path) generator.title = report_title report_title_i18n = translate(report_title, target_language=generator.language) report_context = ReportContext(sittings=sittings, title=report_title_i18n) generator.context = report_context report.title = report_title_i18n report.language = generator.language report.body = generator.generate_report(common.get_request()) session.add(report) session.flush() notify(ObjectCreatedEvent(report)) sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) session.flush() notify(ObjectCreatedEvent(sr))
def get_formatter(): return date.getLocaleFormatter(get_request(), "date")
def in_add_mode(): """Is current UI view in mode "add" i.e. are we adding content? """ return bungeni.ui.interfaces.IFormAddLayer.providedBy(common.get_request())
def in_edit_mode(): """Is current UI view in mode "edit" i.e. are we modifying content? """ return bungeni.ui.interfaces.IFormEditLayer.providedBy(common.get_request())
def default_reports(sitting, event): #!+REPORTS(mb, Feb-2013) - remove this handler for workflow events: # EITHER a publish_report action, maybe configure this as a workflow action # (so not hardwired to status/workflow event) # OR make it part of sitting feature options e.g. publish state and report # template. if "published" in sitting.status: sitting = removeSecurityProxy(sitting) report_type = "sitting_agenda" report_title = _("report_title_order_of_the_day", default=u"Order of the day") if "minutes" in sitting.status: report_type = "sitting_minutes" report_title = _("report_title_votes_and_proceedings", default=u"Votes and Proceedings") sittings = [ExpandedSitting(sitting)] report = domain.Report() session = Session() # !+GROUP_AS_OWNER(mr, apr-2012) we assume for now that the "owner" of # the report is the currently logged in user. report.owner_id = get_login_user().user_id report.created_date = datetime.datetime.now() report.group_id = sitting.group_id # !+ReportXHTMLTemplateFactory # generate using html template in bungeni_custom vocab = vocabulary.report_xhtml_template_factory(sitting) try: report_template_path = vocab.getTermByToken(report_type).value except LookupError: vtokens = [ t.token for t in vocab._terms ] # first check if we have any values in the reports vocab for this context if not vtokens: log.error("Sitting %s Workflow Transition Handler - " "entry for report type %r NOT found in EMPTY vocabulary: %s", sitting, report_type, vtokens) raise # ok, as a tmp workaround, pick off the first term value in the reports vocab log.warning("Sitting %s Workflow Transition Handler - " "entry for report type %r NOT found in vocabulary: %s - " "proceeding with the template for first entry found: %r ", sitting, report_type, vtokens, vtokens[0]) report_template_path = vocab._terms[0].value generator = generators.ReportGeneratorXHTML(report_template_path) generator.title = report_title report_title_i18n = translate(report_title, target_language=generator.language) report_context = ReportContext(sittings=sittings, title=report_title_i18n) generator.context = report_context report.title = report_title_i18n report.language = generator.language report.body = generator.generate_report(common.get_request()) session.add(report) session.flush() notify(ObjectCreatedEvent(report)) sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) session.flush() notify(ObjectCreatedEvent(sr))