예제 #1
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"])
예제 #2
0
 def label(self):
     from euphorie.content.survey import ISurvey
     container = aq_parent(aq_inner(self.context))
     if ISurvey.providedBy(container):
         return _(u"Edit Module")
     else:
         return _(u"Edit Submodule")
예제 #3
0
def getSurvey(context):
    from euphorie.content.surveygroup import ISurveyGroup
    from euphorie.content.survey import ISurvey
    obj = context
    while obj and not ISurveyGroup.providedBy(obj):
        if ISurvey.providedBy(obj):
            return obj
        obj = aq_parent(obj)
예제 #4
0
def get_survey(request, path):
    client = request.client
    try:
        survey = client.restrictedTraverse(path.split('/'))
        if ISurvey.providedBy(survey):
            return survey
    except KeyError:
        pass
    return None
예제 #5
0
def item_depth(item):
    """Return the survey depth of an item.
    """
    from euphorie.content.survey import ISurvey
    depth = 0
    for position in aq_chain(item):
        if ISurvey.providedBy(position):
            break
        depth += 1
    else:
        return None  # Not in a survey
    return depth
예제 #6
0
파일: utils.py 프로젝트: garbas/osha.oira
    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
예제 #7
0
    def _NewSurvey(self, info):
        """Utility method to start a new survey session."""
        context = aq_inner(self.context)
        survey = info.get("survey")
        survey = context.restrictedTraverse(survey)
        if not ISurvey.providedBy(survey):
            log.error('Tried to start invalid survey %r' % info.get('survey'))
            # Things are sufficiently messed up at this point that rendering
            # breaks, so trigger a redirect to the same URL again.
            self.request.response.redirect(context.absolute_url())
            return
        title = info.get("title", u"").strip()
        if not title:
            title = survey.Title()

        SessionManager.start(title=title, survey=survey)
        self.request.response.redirect("%s/start" % survey.absolute_url())
예제 #8
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]
예제 #9
0
파일: library.py 프로젝트: EU-OSHA/Euphorie
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
예제 #10
0
    def _NewSurvey(self, info, account=None):
        """Utility method to start a new survey session."""
        context = aq_inner(self.context)
        survey = info.get("survey")
        survey = context.restrictedTraverse(survey)
        if not ISurvey.providedBy(survey):
            logger.error("Tried to start invalid survey %r",
                         info.get("survey"))
            # Things are sufficiently messed up at this point that rendering
            # breaks, so trigger a redirect to the same URL again.
            self.request.response.redirect(context.absolute_url())
            return

        title = info.get("title", "").strip()

        survey_view = api.content.get_view("index_html", survey, self.request)
        survey_session = survey_view.create_survey_session(title, account)
        self.request.response.redirect(
            "{base_url}/++session++{session_id}/@@start"
            "?initial_view=1&new_session=1".format(
                base_url=survey.absolute_url(), session_id=survey_session.id))
예제 #11
0
    def do_POST(self):
        try:
            survey = self.request.client.restrictedTraverse(
                self.input['survey'].split('/'))
            if not ISurvey.providedBy(survey):
                raise TypeError('Not a survey')
        except (KeyError, TypeError):
            return {'type': 'error', 'message': 'Unknown survey'}

        title = self.input.get('title', survey.title)
        survey_session = create_survey_session(title, survey)
        survey_session = survey_session.__of__(aq_inner(self.context))
        view = SessionView(survey_session, self.request)
        response = view.do_GET()
        survey_session_url = survey_session.absolute_url()
        if survey.ProfileQuestions():
            response['next-step'] = '%s/profile' % survey_session_url
        else:
            survey_session = set_session_profile(survey, survey_session, {})
            response['next-step'] = '%s/identification' % survey_session_url
        return response
예제 #12
0
파일: login.py 프로젝트: euphorie/Euphorie
 def update(self):
     came_from = self.request.form.get("came_from")
     if not came_from:
         return self.request.response.redirect(api.portal.get().absolute_url())
     account = self.createGuestAccount()
     self.login(account, False)
     client_url = self.request.client.absolute_url()
     came_from = came_from.replace(client_url, '')
     if came_from.startswith('/'):
         came_from = came_from[1:]
     try:
         survey = self.context.restrictedTraverse(came_from)
     except KeyError:
         survey = None
     if not ISurvey.providedBy(survey):
         return self.request.response.redirect(came_from)
     title = survey.Title()
     SessionManager.start(title=title, survey=survey, account=account)
     survey_url = survey.absolute_url()
     v_url = urlparse.urlsplit(survey_url + '/resume').path
     trigger_extra_pageview(self.request, v_url)
     self.request.response.redirect("%s/start" % survey_url)
예제 #13
0
    def do_POST(self):
        try:
            survey = self.request.client.restrictedTraverse(
                    self.input['survey'].split('/'))
            if not ISurvey.providedBy(survey):
                raise TypeError('Not a survey')
        except (KeyError, TypeError):
            return {'type': 'error',
                    'message': 'Unknown survey'}

        title = self.input.get('title', survey.title)
        survey_session = create_survey_session(title, survey)
        survey_session = survey_session.__of__(aq_inner(self.context))
        view = SessionView(survey_session, self.request)
        response = view.do_GET()
        survey_session_url = survey_session.absolute_url()
        if survey.ProfileQuestions():
            response['next-step'] = '%s/profile' % survey_session_url
        else:
            survey_session = set_session_profile(survey, survey_session, {})
            response['next-step'] = '%s/identification' % survey_session_url
        return response
예제 #14
0
    def organise(self):
        menu = super(EuphorieSitemenu, self).organise()
        if menu is not None:
            children = menu["children"]
        else:
            menu = {"title": nu_("menu_organise", default=u"Organise")}
            children = menu["children"] = []

        context_url = aq_inner(self.context).absolute_url()
        if ISurvey.providedBy(self.context) and \
                checkPermission(self.context, "View"):
            children.append({"title": _("menu_export", default=u"XML export"),
                             "url": "%s/@@export" % context_url})
        if ISector.providedBy(self.context) and \
                checkPermission(self.context, "Euphorie: Add new RIE Content"):
            children.append(
                    {"title": _("menu_import", default=u"Import OiRA Tool"),
                     "url": "%s/@@upload" % context_url})
        if children:
            return menu
        else:
            return None
예제 #15
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
예제 #16
0
파일: login.py 프로젝트: EU-OSHA/Euphorie
 def update(self):
     came_from = self.request.form.get("came_from")
     if not came_from:
         return self.request.response.redirect(
             api.portal.get().absolute_url())
     account = self.createGuestAccount()
     self.login(account, False)
     client_url = self.request.client.absolute_url()
     came_from = came_from.replace(client_url, '')
     if came_from.startswith('/'):
         came_from = came_from[1:]
     try:
         survey = self.context.restrictedTraverse(came_from)
     except KeyError:
         survey = None
     if not ISurvey.providedBy(survey):
         return self.request.response.redirect(came_from)
     title = survey.Title()
     SessionManager.start(title=title, survey=survey, account=account)
     survey_url = survey.absolute_url()
     v_url = urlparse.urlsplit(survey_url + '/resume').path
     trigger_extra_pageview(self.request, v_url)
     self.request.response.redirect("%s/start" % survey_url)
예제 #17
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()
예제 #18
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()
예제 #19
0
 def surveys(self):
     templates = [dict(title=survey.title, url=survey.absolute_url())
                   for survey in self.context.values()
                   if ISurvey.providedBy(survey)]
     return templates
예제 #20
0
파일: risk.py 프로젝트: EU-OSHA/Euphorie
def evaluation_algorithm(risk):
    for parent in aq_chain(aq_inner(risk)):
        if ISurvey.providedBy(parent):
            return getattr(parent, 'evaluation_algorithm', u'kinney')
    else:
        return u'kinney'
예제 #21
0
def getSurveys(context):
    """Return a list of all surveys for the current sector.

    The return value is a sorted list of dictionaries describing the
    surveygroups for the sector. Each dictionary has the following
    keys:

    * ``id``: surveygroup id
    * ``title`` surveygroup title
    * ``url``: URL for the surveygroup
    * ``published``: boolean indicating if this surveygroup is published
    * ``surveys``: list of surveys for the surveygroup. Each entry is a
      dictionary with the following keys:

      * ``id``: survey id
      * ``title``: survey title
      * ``url``: URL for the survey
      * ``published``: boolean indicating if this survey is the currently
        published version of the surveygroup
      * ``current``: boolean indicating if the *context* is inside this survey
      * ``versions``: list of published versions

    """
    current_version = None
    for sector in aq_chain(aq_inner(context)):
        if ISurvey.providedBy(sector):
            current_version = aq_base(sector)
        if ISector.providedBy(sector):
            break
    else:
        return []

    result = []
    groups = [group for group in sector.values()
                if ISurveyGroup.providedBy(group)]
    repository = getToolByName(context, "portal_repository")
    allow_history = checkPermission(context, AccessPreviousVersions)

    def morph(group, survey):
        info = {'id': survey.id,
                'title': survey.title,
                'url': survey.absolute_url(),
                'published': survey.id == group.published,
                'current': aq_base(survey) is current_version,
                'modified': isDirty(survey),
                'versions': []}
        if not allow_history:
            return info

        history = repository.getHistoryMetadata(survey)
        if history:
            for id in range(history.getLength(countPurged=False) - 1, -1, -1):
                meta = history.retrieve(id,
                        countPurged=False)["metadata"]["sys_metadata"]
                info["versions"].append({
                    'timestamp': datetime.datetime.fromtimestamp(
                        meta["timestamp"]),
                    'history_id': meta["parent"]["history_id"],
                    'version_id': meta["parent"]["version_id"],
                    'location_id': meta["parent"]["location_id"]})
            info["versions"].sort(key=lambda x: x["timestamp"], reverse=True)
        return info

    for group in groups:
        info = {'id': group.id,
                'title': group.title,
                'url': group.absolute_url(),
                'published': bool(group.published)}
        info["surveys"] = [morph(group, survey)
                           for survey in group.values()
                           if ISurvey.providedBy(survey)]
        info["surveys"].sort(key=lambda s: s["title"].lower())
        result.append(info)
    result.sort(key=lambda g: g["title"].lower())
    return result
예제 #22
0
파일: sector.py 프로젝트: euphorie/Euphorie
def getSurveys(context):
    """Return a list of all surveys for the current sector.

    The return value is a sorted list of dictionaries describing the
    surveygroups for the sector. Each dictionary has the following
    keys:

    * ``id``: surveygroup id
    * ``title`` surveygroup title
    * ``url``: URL for the surveygroup
    * ``published``: boolean indicating if this surveygroup is published
    * ``surveys``: list of surveys for the surveygroup. Each entry is a
      dictionary with the following keys:

      * ``id``: survey id
      * ``title``: survey title
      * ``url``: URL for the survey
      * ``published``: boolean indicating if this survey is the currently
        published version of the surveygroup
      * ``current``: boolean indicating if the *context* is inside this survey
      * ``versions``: list of published versions

    """
    current_version = None
    for sector in aq_chain(aq_inner(context)):
        if ISurvey.providedBy(sector):
            current_version = aq_base(sector)
        if ISector.providedBy(sector):
            break
    else:
        return []

    result = []
    groups = [group for group in sector.values() if ISurveyGroup.providedBy(group)]
    repository = getToolByName(context, "portal_repository")
    allow_history = checkPermission(context, AccessPreviousVersions)

    def morph(group, survey):
        published = survey.id == group.published
        info = {
            "id": survey.id,
            "title": survey.title,
            "url": survey.absolute_url(),
            "published": published,
            "publication_date": published and survey.published or None,
            "current": aq_base(survey) is current_version,
            "modified": isDirty(survey),
            "versions": [],
        }
        if not allow_history:
            return info

        history = repository.getHistoryMetadata(survey)
        if history:
            for id in range(history.getLength(countPurged=False) - 1, -1, -1):
                meta = history.retrieve(id, countPurged=False)["metadata"][
                    "sys_metadata"
                ]
                info["versions"].append(
                    {
                        "timestamp": datetime.datetime.fromtimestamp(meta["timestamp"]),
                        "history_id": meta["parent"]["history_id"],
                        "version_id": meta["parent"]["version_id"],
                        "location_id": meta["parent"]["location_id"],
                    }
                )
            info["versions"].sort(key=lambda x: x["timestamp"], reverse=True)
        return info

    for group in groups:
        info = {
            "id": group.id,
            "title": group.title,
            "url": group.absolute_url(),
            "published": bool(group.published),
        }
        info["surveys"] = [
            morph(group, survey)
            for survey in group.values()
            if ISurvey.providedBy(survey)
        ]
        info["surveys"].sort(key=lambda s: s["title"].lower())
        result.append(info)
    result.sort(key=lambda g: g["title"].lower())
    return result
예제 #23
0
def evaluation_algorithm(risk):
    for parent in aq_chain(aq_inner(risk)):
        if ISurvey.providedBy(parent):
            return getattr(parent, 'evaluation_algorithm', u'kinney')
    else:
        return u'kinney'
예제 #24
0
 def _survey(self):
     for parent in aq_chain(aq_inner(self.context)):
         if ISurvey.providedBy(parent):
             return parent
예제 #25
0
 def my_context(self):
     if IClientCountry.providedBy(self.context):
         return "country"
     elif ISurvey.providedBy(self.context):
         return "survey"