Example #1
0
def renew_survey_published_date(context):
    """Update the published attr of surveys to set the date to now.
    This will force all surveys to redirect to the @@update page from where
    users' session trees can be updated.
    """
    site = getSite()
    client = getattr(site, "client")
    # Loop through all client surveys
    for country in client.objectValues():
        for sector in country.objectValues():
            if not IClientSector.providedBy(sector):
                continue
            for survey in sector.objectValues():
                if not ISurvey.providedBy(survey):
                    continue
                published = getattr(survey, "published", None)
                if isinstance(published, tuple):
                    survey.published = (
                        published[0],
                        published[1],
                        datetime.datetime.now(),
                    )
                else:
                    # BBB: Euphorie 1.x did not use a tuple to store extra
                    # information.
                    published = datetime.datetime.now()
Example #2
0
    def get_survey_templates(self):
        # this is a list of tuples of the form
        # (category name, survey object, survey id)
        survey_items = []
        language = self.request.locale.id.language or ""
        for sector in aq_inner(self.context).values():
            if not IClientSector.providedBy(sector):
                continue

            for survey in sector.values():
                if not ISurvey.providedBy(survey):
                    continue
                if getattr(survey, "preview", False):
                    continue
                if (survey.language and survey.language != language
                        and not survey.language.strip().startswith(language)):
                    continue
                if getattr(survey, "obsolete", False):
                    continue
                categories = getattr(survey, "tool_category", None)
                id = "%s/%s" % (sector.id, survey.id)
                if not isinstance(categories, list):
                    categories = [categories]
                if not categories:
                    categories = ["None"]
                for category in categories:
                    survey_items.append((category, survey, id))
        return sorted(survey_items, key=lambda x: (x[0], x[1].title))
Example #3
0
    def _updateSurveys(self):
        self.surveys = []
        self.obsolete_surveys = []

        language = self.request.locale.id.language or ""
        for sector in aq_inner(self.context).values():
            if not IClientSector.providedBy(sector):
                continue

            for survey in sector.values():
                if not ISurvey.providedBy(survey):
                    continue
                if getattr(survey, "preview", False):
                    continue
                if (survey.language and survey.language != language
                        and not survey.language.strip().startswith(language)):
                    continue
                info = {
                    "id": "%s/%s" % (sector.id, survey.id),
                    "title": survey.title
                }
                if getattr(survey, "obsolete", False):
                    # getattr needed for surveys which were published before
                    # the obsolete flag added.
                    self.obsolete_surveys.append(info)
                else:
                    self.surveys.append(info)
        self.surveys.sort(key=lambda s: s["title"])
        self.obsolete_surveys.sort(key=lambda s: s["title"])
Example #4
0
    def _updateSurveys(self):
        self.surveys = []
        self.obsolete_surveys = []

        language = self.request.locale.id.language
        for sector in aq_inner(self.context).values():
            if not IClientSector.providedBy(sector):
                continue

            for survey in sector.values():
                if not ISurvey.providedBy(survey):
                    continue
                if getattr(survey, "preview", False):
                    continue
                if survey.language and survey.language != language and not \
                        survey.language.strip().startswith(language):
                    continue
                info = {"id": "%s/%s" % (sector.id, survey.id),
                        "title": survey.title}
                if getattr(survey, 'obsolete', False):
                    # getattr needed for surveys which were published before
                    # the obsolete flag added.
                    self.obsolete_surveys.append(info)
                else:
                    self.surveys.append(info)
        self.surveys.sort(key=lambda s: s["title"])
        self.obsolete_surveys.sort(key=lambda s: s["title"])
Example #5
0
 def __init__(self, context, request):
     super(WebHelpers, self).__init__(context, request)
     for obj in aq_chain(aq_inner(context)):
         if IClientSector.providedBy(obj):
             self.sector = obj
             break
     self.debug_mode = Globals.DevelopmentMode
Example #6
0
def enable_custom_risks_on_all_modules(context):
    """ """
    if not api.portal.get_registry_record("euphorie.allow_user_defined_risks"):
        log.warning(
            "Custom risks are not enabled. Set 'allow_user_defined_risks' to "
            "true in euphorie.ini for enabling them."
        )
        return
    portal = api.portal.get()
    client = portal.client
    count = 0
    for country in client.objectValues():
        if IClientCountry.providedBy(country):
            for sector in country.objectValues():
                if IClientSector.providedBy(sector):
                    for survey in sector.objectValues():
                        try:
                            is_new = EnableCustomRisks(survey)
                            count += 1
                            custom = getattr(survey, "custom-risks", None)
                            if custom:
                                custom.title = _(
                                    "title_other_risks",
                                    default="Added risks (by you)",
                                )
                                custom.description = _(
                                    "description_other_risks",
                                    default="In case you have identified risks not included in "  # noqa: E501
                                    "the tool, you are able to add them now:",
                                )
                                custom.question = _(
                                    "question_other_risks",
                                    default="<p>Would you now like to add your own defined risks "  # noqa: E501
                                    "to this tool?</p><p><strong>Important:</strong> In "  # noqa: E501
                                    "order to avoid duplicating risks, we strongly recommend you "  # noqa: E501
                                    "to go first through all the previous modules, if you have not "  # noqa: E501
                                    "done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>",  # noqa: E501
                                )
                            if is_new:
                                survey.published = (
                                    survey.id,
                                    survey.title,
                                    datetime.datetime.now(),
                                )
                        except Exception as e:
                            log.error(
                                "Could not enable custom risks for module. %s" % e
                            )
    log.info("All %d published surveys can now have custom risks." % count)
    session = Session()
    if TableExists(session, "tree"):
        session.execute(
            "UPDATE tree SET title = 'title_other_risks' WHERE zodb_path ='custom-risks'"  # noqa: E501
        )
        model.metadata.create_all(session.bind, checkfirst=True)
        datamanager.mark_changed(session)
        transaction.get().commit()
        log.info("Set correct title on all exisiting sessions for custom risks module.")
Example #7
0
    def __init__(self, context, request):
        from euphorie.client.session import SessionManager
        from euphorie.client.country import IClientCountry
        super(WebHelpers, self).__init__(context, request)
        for obj in aq_chain(aq_inner(context)):
            if IClientSector.providedBy(obj):
                self.sector = obj
                break
        self.debug_mode = Globals.DevelopmentMode
        user = getSecurityManager().getUser()
        self.anonymous = isAnonymous(user)
        account = getattr(user, 'account_type', None)
        self.is_guest_account = account == config.GUEST_ACCOUNT
        self.guest_session_id = self.is_guest_account and \
                SessionManager.session and SessionManager.session.id or None

        came_from = self.request.form.get("came_from")
        if came_from:
            if isinstance(came_from, list):
                # If came_from is both in the querystring and the form data
                self.came_from = came_from[0]
            self.came_from = came_from
        else:
            self.came_from = aq_parent(context).absolute_url()

        self.country_name = ''
        self.sector_name = ''
        self.tool_name = ''
        for obj in aq_chain(aq_inner(self.context)):
            if ISurvey.providedBy(obj):
                self.tool_name = obj.Title()
                if self.anonymous:
                    setattr(self.request, 'survey', obj)
            if IClientSector.providedBy(obj):
                self.sector_name = obj.Title()
            if IClientCountry.providedBy(obj):
                self.country_name = obj.Title()
                break
Example #8
0
 def do_GET(self):
     info = {'id': self.context.id,
             'title': self.context.title,
             'type': self.context.country_type,
             }
     sectors = [sector for sector in self.context.values()
                if IClientSector.providedBy(sector)]
     if 'details' in self.request.form:
         info['sectors'] = [SectorView(sector, self.request).do_GET()
                            for sector in sectors]
     else:
         info['sectors'] = [{'id': sector.id,
                             'title': sector.title}
                            for sector in sectors]
     return info
Example #9
0
    def get_sectors_dict(self):
        """ Returns a dictionary with keys being countries (and int. orgs) that
            have sectors inside them and the values being the available survey
            langauges.

            We use ZCatalog directly to bypass permission checks, otherwise we
            get zero surveys returned for anon users.

            See #2556.
        """
        context = aq_inner(self.context)
        sectorsfolder = getattr(context, 'sectors')
        if not sectorsfolder:
            return []

        client = getattr(context, 'client')
        if not client:
            return []

        resp = {}
        ltool = getToolByName(self.context, 'portal_languages')
        # Only the countries in the client obj should be considered, as the
        # others are not accessible
        for country in client.values():
            ldict = {}
            for sector in country.values():
                if not IClientSector.providedBy(sector):
                    continue
                for survey in sector.objectValues():
                    lang = survey.language
                    if not lang:
                        continue

                    if not ISurvey.providedBy(survey):
                        continue
                    if getattr(survey, "preview", False):
                        continue
                    supported_langs = ltool.getSupportedLanguages()
                    if lang not in supported_langs:
                        base_lang = lang.split('-')[0].strip()
                        if base_lang in supported_langs:
                            ldict[base_lang] = 'dummy'
                        continue
                    ldict[lang] = 'dummy'

            if ldict:
                resp[country.id] = ldict.keys()
        return resp
Example #10
0
def enable_custom_risks_on_all_modules(context):
    """ """
    appconfig = zope.component.getUtility(IAppConfig)
    if not asBool(appconfig["euphorie"].get("allow_user_defined_risks")):
        log.warning(
            "Custom risks are not enabled. Set 'allow_user_defined_risks' to "
            "true in euphorie.ini for enabling them.")
        return
    portal = api.portal.get()
    client = portal.client
    count = 0
    for country in client.objectValues():
        if IClientCountry.providedBy(country):
            for sector in country.objectValues():
                if IClientSector.providedBy(sector):
                    for survey in sector.objectValues():
                        try:
                            is_new = EnableCustomRisks(survey)
                            count += 1
                            custom = getattr(survey, 'custom-risks', None)
                            if custom:
                                custom.title = _(
                                    u'title_other_risks',
                                    default=u"Added risks (by you)")
                                custom.description = _(
                                    u"description_other_risks",
                                    default=
                                    u"In case you have identified risks not included in "
                                    u"the tool, you are able to add them now:")
                                custom.question = _(
                                    u"question_other_risks",
                                    default=
                                    u"<p>Would you now like to add your own defined risks "
                                    u"to this tool?</p><p><strong>Important:</strong> In "
                                    u"order to avoid duplicating risks, we strongly recommend you "
                                    u"to go first through all the previous modules, if you have not "
                                    u"done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>"
                                )
                            if is_new:
                                survey.published = (survey.id, survey.title,
                                                    datetime.datetime.now())
                        except Exception, e:
                            log.error(
                                "Could not enable custom risks for module. %s"
                                % e)
Example #11
0
 def findSurvey(self, input):
     """Find the survey to match the (already parsed) input data."""
     rie = input.attrib["rie_path"].split("/")[3]
     matches = []
     for sector in aq_inner(self.context).values():
         if not IClientSector.providedBy(sector):
             continue
         for survey in sector.values():
             if ISurvey.providedBy(survey) and \
                     survey.id != 'preview' and \
                     getattr(aq_base(survey), "external_id", None) == rie:
                 matches.append(survey)
     if not matches:
         return None
     # Pick the oldest published survey on the assumption this is not a
     # modified copy.
     matches.sort(key=lambda s: s.published[2], reverse=True)
     return matches[0]
Example #12
0
 def do_GET(self):
     info = {
         'id': self.context.id,
         'title': self.context.title,
         'type': self.context.country_type,
     }
     sectors = [
         sector for sector in self.context.values()
         if IClientSector.providedBy(sector)
     ]
     if 'details' in self.request.form:
         info['sectors'] = [
             SectorView(sector, self.request).do_GET() for sector in sectors
         ]
     else:
         info['sectors'] = [{
             'id': sector.id,
             'title': sector.title
         } for sector in sectors]
     return info
Example #13
0
def _set_skip_evaluation(walker):
    count = 0
    for survey in walker:
        parent = survey.aq_parent
        if IClientSector.providedBy(parent):
            # client
            country = parent.aq_parent
        else:
            # CMS
            country = parent.aq_parent.aq_parent
        count += 1
        if country.getId() in countries_with_simple_measures:
            survey.measures_text_handling = "simple"
        else:
            survey.measures_text_handling = "full"
        if count % 10 == 0:
            log.info("Handled %d items" % count)
        if count % 1000 == 0:
            log.info("Intermediate commit")
            commit()
    log.info("Finished. Updated %d OiRA tools" % count)
Example #14
0
def enable_custom_risks_on_all_modules(context):
    """ """
    appconfig = zope.component.getUtility(IAppConfig)
    if not asBool(appconfig["euphorie"].get("allow_user_defined_risks")):
        log.warning(
            "Custom risks are not enabled. Set 'allow_user_defined_risks' to "
            "true in euphorie.ini for enabling them.")
        return
    portal = api.portal.get()
    client = portal.client
    count = 0
    for country in client.objectValues():
        if IClientCountry.providedBy(country):
            for sector in country.objectValues():
                if IClientSector.providedBy(sector):
                    for survey in sector.objectValues():
                        try:
                            is_new = EnableCustomRisks(survey)
                            count += 1
                            custom = getattr(survey, 'custom-risks', None)
                            if custom:
                                custom.title = _(u'title_other_risks', default=u"Added risks (by you)")
                                custom.description = _(
                                    u"description_other_risks",
                                    default=u"In case you have identified risks not included in "
                                    u"the tool, you are able to add them now:")
                                custom.question = _(
                                    u"question_other_risks",
                                    default=u"<p>Would you now like to add your own defined risks "
                                    u"to this tool?</p><p><strong>Important:</strong> In "
                                    u"order to avoid duplicating risks, we strongly recommend you "
                                    u"to go first through all the previous modules, if you have not "
                                    u"done it yet.</p><p>If you don't need to add risks, please select 'No.'</p>")
                            if is_new:
                                survey.published = (
                                    survey.id, survey.title, datetime.datetime.now())
                        except Exception, e:
                            log.error("Could not enable custom risks for module. %s" % e)
Example #15
0
def renew_survey_published_date(context):
    """ Update the published attr of surveys to set the date to now.
        This will force all surveys to redirect to the @@update page from where
        users' session trees can be updated.
    """
    site = getSite()
    client = getattr(site, 'client')
    # Loop through all client surveys
    for country in client.objectValues():
        for sector in country.objectValues():
            if not IClientSector.providedBy(sector):
                continue
            for survey in sector.objectValues():
                if not ISurvey.providedBy(survey):
                    continue
                published = getattr(survey, "published", None)
                if isinstance(published, tuple):
                    survey.published = (
                        published[0], published[1], datetime.datetime.now())
                else:
                    # BBB: Euphorie 1.x did not use a tuple to store extra
                    # information.
                    published = datetime.datetime.now()
Example #16
0
def update_custom_risks_module_texts(context):
    """ """
    if not api.portal.get_registry_record("euphorie.allow_user_defined_risks"):
        log.warning(
            "Custom risks are not enabled. Set 'allow_user_defined_risks' to "
            "true in euphorie.ini for enabling them.")
        return
    portal = api.portal.get()
    client = portal.client
    count = 0
    for country in client.objectValues():
        if IClientCountry.providedBy(country):
            for sector in country.objectValues():
                if IClientSector.providedBy(sector):
                    for survey in sector.objectValues():

                        is_new = EnableCustomRisks(survey)
                        count += 1
                        custom = getattr(survey, "custom-risks", None)
                        if custom:
                            custom.question = _(
                                "question_other_risks",
                                default=
                                ("<p><strong>Important:</strong> In "
                                 "order to avoid duplicating risks, "
                                 "we strongly recommend you "
                                 "to go first through all the previous modules, "
                                 "if you have not done it yet.</p>"
                                 "<p>If you don't need to add risks, "
                                 "please continue.</p>"),
                            )
                        if is_new:
                            survey.published = (
                                survey.id,
                                survey.title,
                                datetime.datetime.now(),
                            )
Example #17
0
 def sectors(self):
     country_obj = self.request.client.restrictedTraverse(self.country)
     return [
         sector for sector in aq_inner(country_obj).values()
         if IClientSector.providedBy(sector)
     ]
Example #18
0
 def sector_name(self):
     for obj in aq_chain(aq_inner(self.context)):
         if IClientSector.providedBy(obj):
             return obj.Title()