def handleSurveyUnpublish(survey, event): """Event handler (subscriber) to take care of unpublishing a survey from the client. """ surveygroup = aq_parent(survey) sector = aq_parent(surveygroup) country = aq_parent(sector) pas = getToolByName(survey, "acl_users") clientuser = pas.getUserById("client") sm = getSecurityManager() try: newSecurityManager(None, clientuser) client = getPortal(survey).client try: clientcountry = client[country.id] clientsector = clientcountry[sector.id] clientsector[surveygroup.id] except KeyError: log.info( "Trying to unpublish unpublished survey %s", "/".join(survey.getPhysicalPath()), ) return clientsector.manage_delObjects([surveygroup.id]) if not clientsector.keys(): clientcountry.manage_delObjects([clientsector.id]) finally: setSecurityManager(sm)
def verify(self, container, context): if not checkPermission(container, "Delete objects"): raise zExceptions.Unauthorized flash = IStatusMessage(self.request).addStatusMessage sector = context country = container client = getPortal(container).client if country.id not in client: return True cl_country = client[country.id] if sector.id not in cl_country: return True # Look for any published surveys in the client sector, and prevent # deletion if any are found cl_sector = cl_country[sector.id] surveys = [s for s in cl_sector.values() if s.id != 'preview'] if surveys: flash( _("message_not_delete_published_sector", default=u"You can not delete a sector that contains published " u"OiRA Tools."), "error") self.request.response.redirect(context.absolute_url()) return False return True
def handleSurveyUnpublish(survey, event): """Event handler (subscriber) to take care of unpublishing a survey from the client. """ surveygroup = aq_parent(survey) sector = aq_parent(surveygroup) country = aq_parent(sector) pas = getToolByName(survey, "acl_users") clientuser = pas.getUserById("client") sm = getSecurityManager() try: newSecurityManager(None, clientuser) client = getPortal(survey).client try: clientcountry = client[country.id] clientsector = clientcountry[sector.id] clientsector[surveygroup.id] except KeyError: log.info("Trying to unpublish unpublished survey %s", "/".join(survey.getPhysicalPath())) return clientsector.manage_delObjects([surveygroup.id]) if not clientsector.keys(): clientcountry.manage_delObjects([clientsector.id]) finally: setSecurityManager(sm)
def verify(self, container, context): flash = IStatusMessage(self.request).addStatusMessage surveygroup = context sector = container country = aq_parent(sector) client = getPortal(container).client if country.id not in client: return True cl_country = client[country.id] if sector.id not in cl_country: return True cl_sector = cl_country[sector.id] if surveygroup.id not in cl_sector: return True surveys = [s for s in cl_sector[surveygroup.id].values() if s.id != 'preview'] if surveys: flash( _("message_not_delete_published_surveygroup", default=u"You can not delete an OiRA tool that has been published."), "error" ) self.request.response.redirect(context.absolute_url()) return False return True
def __init__(self, *a): super(Tools, self).__init__(*a) self.user=getSecurityManager().getUser() self.anonymous=self.user is None or self.user.getUserName()=="Anonymous User" self.portal=utils.getPortal(self.context) self.portal_url=self.portal.absolute_url() self.navroot=utils.getNavigationRoot(self.context) self.navroot_url=self.navroot.absolute_url() self.context_url=aq_inner(self.context).absolute_url()
def settings_url(self): user = getSecurityManager().getUser() if IMembraneUser.providedBy(user): mt = getToolByName(self.context, "membrane_tool") home = mt.getUserObject(user_id=user.getUserId()) return "%s/@@edit" % home.absolute_url() else: home = getPortal(self.context) return "%s/@@settings" % home.absolute_url()
def __init__(self, *a): super(Tools, self).__init__(*a) self.user = getSecurityManager().getUser() self.anonymous = self.user is None or self.user.getUserName( ) == "Anonymous User" self.portal = utils.getPortal(self.context) self.portal_url = self.portal.absolute_url() self.navroot = utils.getNavigationRoot(self.context) self.navroot_url = self.navroot.absolute_url() self.context_url = aq_inner(self.context).absolute_url()
def client_url(self): """Return the URL this survey will have after it is published.""" client_url = api.portal.get_registry_record("euphorie.client_url", default="") if client_url: client_url = client_url.rstrip("/") else: client_url = getPortal(self.context).client.absolute_url() source = aq_inner(self.context) surveygroup = aq_parent(source) sector = aq_parent(surveygroup) country = aq_parent(sector) return "/".join([client_url, country.id, sector.id, surveygroup.id])
def client_url(self): """Return the URL this survey will have after it is published.""" config = getUtility(IAppConfig) client_url = config.get("euphorie", {}).get("client") if client_url: client_url = client_url.rstrip("/") else: client_url = getPortal(self.context).client.absolute_url() source = aq_inner(self.context) surveygroup = aq_parent(source) sector = aq_parent(surveygroup) country = aq_parent(sector) return "/".join([client_url, country.id, sector.id, surveygroup.id])
def get_library(context): """Get a list of sectors, based on the the euphorie.library registry record :returns: A list of dicts with details for sectors :rtype: list """ record = api.portal.get_registry_record("euphorie.library", default="") if not record: return [] paths = [path.lstrip("/") for path in safe_nativestring(record).split()] if not paths: return [] site = getPortal(context) library = [] for path in paths: try: sector = site.restrictedTraverse(path) except (AttributeError, KeyError): log.warning("Invalid library path (not found): %s" % path) continue if not ISector.providedBy(sector): log.warning("Invalid library path (not a sector): %s", path) continue sector_library = [] survey_groups = [ sg for sg in sector.values() if ISurveyGroup.providedBy(sg) and not sg.obsolete ] for sg in survey_groups: surveys = [s for s in sg.values() if ISurvey.providedBy(s)] if len(surveys) != 1: log.warning( "Ignoring surveygroup due to multiple versions: %s", "/".join(sg.getPhysicalPath()), ) continue tree = build_survey_tree(aq_inner(context), surveys[0]) tree["title"] = sg.title sector_library.append(tree) if sector_library: sector_library.sort(key=lambda s: s["title"]) library.append({ "title": sector.title, "url": sector.absolute_url(), "path": "/".join(sector.getPhysicalPath()), "surveys": sector_library, }) library.sort(key=lambda s: s["title"]) return library
def is_structure_changed(self): source = aq_inner(self.context) surveygroup = aq_parent(source) sector = aq_parent(surveygroup) country = aq_parent(sector) client = getPortal(self.context).client if country.id not in client: return False cl_country = client[country.id] if sector.id not in cl_country: return False cl_sector = cl_country[sector.id] if surveygroup.id not in cl_sector: return False target = cl_sector[surveygroup.id] return not self._has_same_structure(source, target)
def render(self): flash = IStatusMessage(self.request).addStatusMessage if setLanguage(self.request, self.context): flash(_('message_switch_language', default=u'Language updated'), 'success') else: flash(_('message_switch_language_error', default=u'Failed to switch language'), 'error') next_url = self.request.get('came_from') if not next_url: next_url = self.request.environ.get('HTTP_REFERER') if not next_url or not \ next_url.startswith(getPortal(self.context).absolute_url()): next_url = aq_inner(self.context).absolute_url() self.request.response.redirect(next_url)
def render(self): flash = IStatusMessage(self.request).addStatusMessage if setLanguage(self.request, self.context): flash(_('message_switch_language', default='Language updated'), 'success') else: flash(_('message_switch_language_error', default='Failed to switch language'), 'error') next_url = self.request.get('came_from') if not next_url: next_url = self.request.environ.get('HTTP_REFERER') if not next_url or not \ next_url.startswith(getPortal(self.context).absolute_url()): next_url = aq_inner(self.context).absolute_url() self.request.response.redirect(next_url)
def get_library(context): """ Get a list of sectors, based on the configuration in euphorie.ini :returns: A list of dicts with details for sectors :rtype: list """ config = getUtility(IAppConfig).get('euphorie', {}) paths = [path.lstrip('/') for path in config.get('library', '').split()] if not paths: return [] site = getPortal(context) library = [] for path in paths: try: sector = site.restrictedTraverse(path) except (AttributeError, KeyError): log.warning('Invalid library path (not found): %s' % path) continue if not ISector.providedBy(sector): log.warning('Invalid library path (not a sector): %s', path) continue sector_library = [] survey_groups = [sg for sg in sector.values() if ISurveyGroup.providedBy(sg) and not sg.obsolete] for sg in survey_groups: surveys = [s for s in sg.values() if ISurvey.providedBy(s)] if len(surveys) != 1: log.warning('Ignoring surveygroup due to multiple versions: %s', '/'.join(sg.getPhysicalPath())) continue tree = build_survey_tree(aq_inner(context), surveys[0]) tree['title'] = sg.title sector_library.append(tree) if sector_library: sector_library.sort(key=lambda s: s['title']) library.append({'title': sector.title, 'url': sector.absolute_url(), 'path': '/'.join(sector.getPhysicalPath()), 'surveys': sector_library}) library.sort(key=lambda s: s['title']) return library
def CopyToClient(survey, preview=False): """Copy the survey to the online client part of the site. :param survey: the survey to copy :param bool preview: indicates if this is a preview or a normal publication :rtype: :py:class:`euphorie.content.survey.Survey` The public area is hardcoded to be a container with id ``client`` within the site root. The ''id'' and ''title'' of the survey group will be used for the published survey. If another object with the same ''id'' already exists it will be removed first. Any missing country and sector folders are created if needed. If this is a preview (as indicated by the ``preview`` parameter) the id of the survey will be set to ``preview``, guaranteeing that an existing published survey will not be replaced. This also means only a sector can only have one preview online. This method assumes the current user has permissions to create content in the online client. This is normally done by using the :py:func:`PublishToClient` function which switches the current user for the copy operation. Returns the new public survey instance. """ # This is based on OFS.CopyContainer.manage_clone, modified to # use the sector id and title, skip security checks and remove # an existing object with the same id. client = getPortal(survey).client source = aq_inner(survey) surveygroup = aq_parent(source) sector = aq_parent(surveygroup) country = aq_parent(sector) from euphorie.content.sector import ISector assert ISector.providedBy(sector) if country.id not in client: client.invokeFactory("euphorie.clientcountry", country.id, title=country.title, country_type=country.country_type) cl_country = client[country.id] if sector.id not in cl_country: cl_country.invokeFactory("euphorie.clientsector", sector.id) target = cl_country[sector.id] target.title = sector.title target.logo = sector.logo # Clear any scaled logos AnnotationStorage(target).storage.clear() target.main_background_colour = getattr(sector, "main_colour", None) if target.main_background_colour: target.main_foreground_colour = utils.MatchColour( target.main_background_colour, 0.0, 0.6, 0.3) target.main_background_bright = \ utils.IsBright(target.main_background_colour) target.support_background_colour = getattr(sector, "support_colour", None) if target.support_background_colour: target.support_foreground_colour = \ utils.MatchColour(target.support_background_colour) target.support_background_bright = \ utils.IsBright(target.support_background_colour) copy = source._getCopy(target) if preview: copy.id = "preview" else: copy.id = surveygroup.id copy.title = surveygroup.title copy.obsolete = surveygroup.obsolete copy.evaluation_algorithm = surveygroup.evaluation_algorithm copy.version = source.id copy.published = datetime.datetime.now() copy.preview = preview if copy.id in target: # We must suppress events to prevent the can-not-delete-published- # content check from blocking us. # XXX: We need however the ObjectWillBeRemovedEvent event to be called # otherwise the removed objects are not uncatalogged. to_delete = target._getOb(copy.id) notify(ObjectWillBeRemovedEvent(to_delete, target, copy.id)) target._delObject(copy.id, suppress_events=True) target._setObject(copy.id, copy, suppress_events=True) copy = target[copy.id] copy._postCopy(target, op=0) notify(ObjectPublishedEvent(source)) return copy
def update(self): context = aq_inner(self.context) portal = getPortal(context) currentUrl = self.request.getURL()[len(portal.absolute_url()):] user = getSecurityManager().getUser() if IMembraneUser.providedBy(user): mt = getToolByName(self.context, "membrane_tool") user_object = mt.getUserObject(user_id=user.getUserId()) else: user_object = None for (test, id) in self.current_map: if test.match(currentUrl): current = id break else: current = None results = [{ "id": "sectors", "title": _("nav_surveys", default=u"OiRA Tools"), "url": portal.sectors.absolute_url(), "class": "current" if current == "sectors" else None }] if checkPermission(portal, "Manage portal"): for country in aq_chain(context): if ICountry.providedBy(country): url = "%s/@@manage-users" % country.absolute_url() break else: countries = sorted(portal.sectors.keys()) url = "%s/@@manage-users" % \ portal.sectors[countries[0]].absolute_url() results.append({ "id": "usermgmt", "title": _("nav_usermanagement", default=u"User management"), "url": url, "class": "current" if current == "usermgmt" else None }) results.append({ "id": "documents", "title": _("nav_documents", default=u"Documents"), "url": portal.documents.absolute_url(), "class": "current" if current == "documents" else None }) elif ICountryManager.providedBy(user_object): country = aq_parent(user_object) results.append({ "id": "usermgmt", "title": _("nav_usermanagement", default=u"User management"), "url": "%s/@@manage-users" % country.absolute_url(), "class": "current" if current == "usermgmt" else None }) if user_object is not None: country = aq_parent(user_object) results.append({ "id": "help", "title": _("nav_help", default=u"Help"), "url": "%s/help" % country.absolute_url(), "class": "current" if current == "help" else None }) self.tabs = results self.home_url = portal.absolute_url()
def portal(self): return utils.getPortal(self.context)
def client_url(self): config = getUtility(IAppConfig) client_url = config.get("euphorie", {}).get("client") if not client_url: client_url = getPortal(self.context).client.absolute_url() return client_url.rstrip('/')
def update(self): context = aq_inner(self.context) portal = getPortal(context) currentUrl = self.request.getURL()[len(portal.absolute_url()):] user = getSecurityManager().getUser() if IMembraneUser.providedBy(user): mt = getToolByName(self.context, "membrane_tool") user_object = mt.getUserObject(user_id=user.getUserId()) else: user_object = None for (test, id) in self.current_map: if test.match(currentUrl): current = id break else: current = None results = [{"id": "sectors", "title": _("nav_surveys", default=u"OiRA Tools"), "url": portal.sectors.absolute_url(), "class": "current" if current == "sectors" else None}] if checkPermission(portal, "Manage portal"): for country in aq_chain(context): if ICountry.providedBy(country): url = "%s/@@manage-users" % country.absolute_url() break else: countries = sorted(portal.sectors.keys()) url = "%s/@@manage-users" % \ portal.sectors[countries[0]].absolute_url() results.append({"id": "usermgmt", "title": _("nav_usermanagement", default=u"User management"), "url": url, "class": "current" if current == "usermgmt" else None}) results.append({"id": "documents", "title": _("nav_documents", default=u"Documents"), "url": portal.documents.absolute_url(), "class": "current" if current == "documents" else None}) elif ICountryManager.providedBy(user_object): country = aq_parent(user_object) results.append({"id": "usermgmt", "title": _("nav_usermanagement", default=u"User management"), "url": "%s/@@manage-users" % country.absolute_url(), "class": "current" if current == "usermgmt" else None}) if user_object is not None: country = aq_parent(user_object) results.append({"id": "help", "title": _("nav_help", default=u"Help"), "url": "%s/help" % country.absolute_url(), "class": "current" if current == "help" else None}) self.tabs = results self.home_url = portal.absolute_url()