Exemplo n.º 1
0
    def handle(self, message, info, text, attachments):
        """ See IMailinHandler.
        """
        entry = create_content(
            IBlogEntry,
            title=info['subject'],
            creator=info['author'],
            text=text,
            description=extract_description(text),
            )
        entry.created = info['date']

        if attachments:
            if 'attachments' not in entry:
                # XXX Not a likely code path, left here for safety
                entry['attachments'] = att_folder = AttachmentsFolder()
                att_folder.title = 'Attachments'
                att_folder.creator = info['author']
            else:
                att_folder = entry['attachments']
            _addAttachments(att_folder, info, attachments)

        entry_id = make_unique_name(self.context, entry.title)
        self.context[entry_id] = entry

        workflow = get_workflow(IBlogEntry, 'security', self.context)
        if workflow is not None:
            workflow.initialize(entry)

        alerts = queryUtility(IAlerts, default=Alerts())
        alerts.emit(entry, offline_request)
Exemplo n.º 2
0
    def sync(self, data):
        context = self.context
        timestamp = data.pop('timestamp', None)
        if timestamp:
            context.usersync_timestamp = timestamp
        elif hasattr(context, 'usersync_timestamp'):
            del context.usersync_timestamp

        deactivate_missing = data.pop('deactivate_missing', False)
        if deactivate_missing:
            profiles = find_profiles(self.context)
            missing = set([p.__name__ for p in profiles.values()
                           if p.security_state == 'active' and
                           getattr(p, 'usersync_managed', False)])
        else:
            missing = Empty()

        users = data.pop('users')
        for user in users:
            self.syncuser(user, missing)
        if data:
            raise ValueError("Unrecognized keys in user sync data: %s" %
                             data.keys())

        if missing:
            users = find_users(self.context)
            for username in missing:
                profile = profiles[username]
                workflow = get_workflow(IProfile, 'security', profile)
                workflow.transition_to_state(profile, None, 'inactive')
                users.remove(username)
Exemplo n.º 3
0
    def state_contract_change(self):
        new_state = self.request.POST['new_state']
        new_contract = self.request.POST['new_contract']
        invoice_number = self.request.POST['invoice_number']

        te_ids = set(int(s[3:])
                     for s, checkbox_state in self.request.POST.iteritems()
                     if s.startswith('te_') and checkbox_state=='on')

        qry = DBSession.query(TimeEntry).filter(TimeEntry.id.in_(te_ids))

        done_state = set()
        done_contract = set()
        errors = {}

        for te in qry:
            if new_state:
                try:
                    workflow = get_workflow(te, te.__class__.__name__)
                    workflow.transition_to_state(te, self.request, new_state, skip_same=True)
                    done_state.add(te.id)
                    if new_state == 'invoiced' and invoice_number:
                        te.invoice_number = invoice_number
                except WorkflowError as msg:
                    errors[te.id] = msg
            if new_contract:
                done_contract.add(te.id)
                te.contract_id = new_contract

        return done_state, done_contract, errors
Exemplo n.º 4
0
def evolve(root):
    former_id = 'formeruser'

    profiles = find_profiles(root)
    search = ICatalogSearch(root)
    catalog = find_catalog(root)
    creators = catalog['creator']._fwd_index.keys()
    modifiers = catalog['modified_by']._fwd_index.keys()
    userids = set(creators) | set(modifiers)
    for userid in userids:
        if userid not in profiles:
            if former_id not in profiles:
                workflow = get_workflow(IProfile, 'security')
                former_id = make_unique_name(profiles, 'formeruser')

                print "Creating profile for former user content:", former_id
                former_profile = create_content(
                    IProfile, firstname='Former', lastname='User'
                )
                profiles[former_id] = former_profile
                workflow.initialize(former_profile)
                workflow.transition_to_state(former_profile, None, 'inactive')

            count, docids, resolver = search(creator=userid)
            for docid in docids:
                doc = resolver(docid)
                print "Updating 'creator' for", model_path(doc)
                doc.creator = former_id


            count, docids, resolver = search(modified_by=userid)
            for docid in docids:
                doc = resolver(docid)
                print "Updating 'modified_by' for", model_path(doc)
                doc.modified_by = former_id
Exemplo n.º 5
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.workflow = get_workflow(ICommunityFile, 'security', context)
     self.filestore = get_filestore(context, request, 'add-file')
     self.show_sendalert = get_show_sendalert(self.context, self.request)
     self.check_upload_size = check_upload_size # for testing
Exemplo n.º 6
0
def evolve(context):
    out = codecs.getwriter('UTF-8')(sys.stdout)

    # Fix strange user db inconsistency from (hopefully) distant past.
    # Some users in the db have user info but their login is missing from
    # the logins dict.
    users = find_users(context)
    logins = users.logins
    for id in users.byid.keys():
        login = users.get_by_id(id)['login']
        if login not in logins:
            logins[login] = id

    # Convert profiles to new workflow.
    workflow = get_workflow(IProfile, 'security')
    for profile in find_profiles(context).values():
        print >>out, ("Updating security workflow for profile: %s" %
                      profile.__name__)
        if not hasattr(profile, 'security_state'):
            # 'formeruser' was added without initializing workflow, oops.
            workflow.initialize(profile)
            workflow.transition_to_state(profile, None, 'inactive')
            continue
        assert profile.security_state == 'profile'
        assert not has_custom_acl(profile)
        profile.security_state = 'active'
        workflow.reset(profile)
Exemplo n.º 7
0
def get_wf_state_titles(request, iface, type_name):
    wf = get_workflow(iface, type_name)
    results = {}
    tstring = _
    for sinfo in wf.state_info(None, request):
        results[sinfo['name']] = request.localizer.translate(tstring(sinfo['title']))
    return results
Exemplo n.º 8
0
    def handle_submit(self, converted):
        context = self.context
        request = self.request
        userid = converted['login']
        users = self.users
        if (users.get_by_id(userid) is not None or
            users.get_by_login(userid) is not None or
            userid in context):
            msg = "User ID '%s' is already in use" % userid
            raise ValidationError(login=msg)
        users.add(userid, userid, converted['password'], converted['groups'])

        # prepend http:// to the website URL if necessary
        if converted.get('website', '').startswith('www.'):
            converted['website'] = 'http://%s' % converted['website']
        kw = {}
        for k, v in converted.items():
            if k in ('login', 'password', 'password_confirm',
                     'photo', 'groups'):
                continue
            kw[k] = v
        profile = create_content(IProfile, **kw)
        context[userid] = profile

        workflow = get_workflow(IProfile, 'security', context)
        if workflow is not None:
            workflow.initialize(profile)

        handle_photo_upload(profile, converted, thumbnail=True)
        location = model_url(profile, request)
        return HTTPFound(location=location)
Exemplo n.º 9
0
    def stop(self):
        """
        PATCH /arc2box/communities/<community>/
        {"action": "stop"}

        Tell the archiver to stop copying content from this community to box
        and to take the community out of the 'copying' state.  The community
        must be in the 'copying' or 'reviewing' state.  The community will
        return to normal operation and will not be in any archiving state.
        """
        community = self.context
        status = getattr(community, 'archive_status', None)
        if status not in ('copying', 'reviewing', 'exception'):
            return HTTPBadRequest(
                "Community must be in 'copying' or 'reviewing' state.")

        # Restore normal ACL for workflow state
        wf = get_workflow(ICommunity, 'security', community)
        wf.reset(community)
        del community.__custom_acl__

        # If still in the copy queue, the archiver will skip this community
        del community.archive_status

        logger.info('arc2box: stop community: ' + community.title)
        return HTTPAccepted()
Exemplo n.º 10
0
    def handle_submit(self, converted):
        context = self.context
        request = self.request
        parent = context.__parent__
        creator = authenticated_userid(request)
        comment = create_content(
            IComment,
            'Re: %s' % parent.title,
            converted['add_comment'],
            extract_description(converted['add_comment']),
            creator,
            )
        next_id = parent['comments'].next_id
        parent['comments'][next_id] = comment
        workflow = get_workflow(IComment, 'security', context)
        if workflow is not None:
            workflow.initialize(comment)
            if 'security_state' in converted:
                workflow.transition_to_state(comment, request,
                                             converted['security_state'])

        if support_attachments(comment):
            upload_attachments(converted['attachments'], comment,
                               creator, request)
        relocate_temp_images(comment, request)

        if converted.get('sendalert'):
            alerts = queryUtility(IAlerts, default=Alerts())
            alerts.emit(comment, request)

        location = resource_url(parent, request)
        msg = 'Comment added'
        location = '%s?status_message=%s' % (location, urllib.quote(msg))
        self.filestore.clear()
        return HTTPFound(location=location)
Exemplo n.º 11
0
def deactivate_profile_view(context, request):
    name = context.__name__
    myself = authenticated_userid(request) == context.__name__

    confirm = request.params.get('confirm')
    if confirm:
        try:
            find_users(context).remove(name)
        except KeyError:
            pass
        workflow = get_workflow(IProfile, 'security', context)
        workflow.transition_to_state(context, request, 'inactive')
        if myself:
            return logout_view(context, request, reason='User removed')
        query = {'status_message': 'Deactivated user account: %s' % name}
        parent = context.__parent__
        location = resource_url(parent, request, query=query)

        return HTTPFound(location=location)

    page_title = 'Deactivate user account for %s %s' % (context.firstname,
                                                        context.lastname)
    api = TemplateAPI(context, request, page_title)

    # Show confirmation page.
    return dict(api=api, myself=myself)
Exemplo n.º 12
0
def evolve(site):
    offices = site.get('offices')
    if offices is None:
        return

    for doc in postorder(offices):
        if hasattr(doc, '__custom_acl__'):
            continue

        try:
            ct = get_content_type(doc)
        except:
            continue

        if ct is None:
            continue

        wf = get_workflow(ct, 'security', doc)
        if wf is None:
            continue

        if wf.name != 'intranet-content':
            continue

        print 'Resetting workflow for', model_path(doc)
        wf.reset(doc)

    _reindex(offices)
Exemplo n.º 13
0
    def handle(self, message, info, text, attachments):
        """ See IMailinHandler.
        """
        target = self.context['comments']
        reply = create_content(
            IComment,
            title=info['subject'],
            creator=info['author'],
            text=text,
            description=extract_description(text),
        )

        reply.title = info['subject']
        reply.creator = info['author']
        reply.created = info['date']
        reply.text = text

        target[target.next_id] = reply

        workflow = get_workflow(IComment, 'security', target)
        if workflow is not None:
            workflow.initialize(reply)

        if attachments:
            _addAttachments(reply, info, attachments)

        # Mailin always sends alerts
        alerts = queryUtility(IAlerts, default=Alerts())
        alerts.emit(reply, offline_request)
Exemplo n.º 14
0
def move_content(root, src, dst, wf_state):
    try:
        context = find_resource(root, src)
    except KeyError:
        print >> sys.stderr, "Source content not found: %s" % src
        sys.exit(-1)

    try:
        dest_folder = find_resource(root, dst)
    except KeyError:
        print >> sys.stderr, "Destination folder not found: %s" % dst
        sys.exit(-1)

    src_community = find_community(context)

    catalog = find_catalog(root)
    assert catalog is not None
    users = find_users(root)
    assert users is not None

    if src_community is not None:
        move_header = ('<p><em>This was originally authored '
                       'in the "%s" community.</em></p>' % src_community.title)
    else:
        move_header = ''

    src_folder = context.__parent__
    name = context.__name__

    log.info("Moving %s", resource_path(context))
    for obj in postorder(context):
        if hasattr(obj, 'docid'):
            docid = obj.docid
            catalog.document_map.remove_docid(docid)
            catalog.unindex_doc(docid)
    del src_folder[name]

    if (context.creator != 'admin'
            and users.get_by_id(context.creator) is None):
        # give the entry to the system admin
        log.warning("User %s not found; reassigning to admin", context.creator)
        context.creator = 'admin'

    if name in dest_folder:
        name = make_unique_name(dest_folder, context.title)

    dest_folder[name] = context
    for obj in postorder(context):
        if hasattr(obj, 'docid'):
            docid = obj.docid
            catalog.document_map.add(resource_path(obj), docid)
            catalog.index_doc(docid, obj)

    if wf_state is not None:
        wf = get_workflow(get_content_type(context), 'security', context)
        wf.transition_to_state(context, None, wf_state)

    if hasattr(context, 'text'):
        context.text = "%s\n%s" % (move_header, context.text)
Exemplo n.º 15
0
    def wf_state(self):
        """ get the workflow state via the repoze.workflow API """
        state = ''
        if HAS_WORKFLOW:
            workflow = get_workflow(self, 'security')
            state = workflow.state_of(self) or ''

        return state
Exemplo n.º 16
0
def get_wf_state_titles(request, iface, type_name):
    wf = get_workflow(iface, type_name)
    results = {}
    tstring = _
    for sinfo in wf.state_info(None, request):
        results[sinfo['name']] = request.localizer.translate(
            tstring(sinfo['title']))
    return results
    def __init__(self, context, request):

        self.context = context
        self.request = request

        self.wf = get_workflow(self.context, 'security')

        assert(self.wf is not None)
Exemplo n.º 18
0
Arquivo: acl.py Projeto: Falmarri/karl
def get_context_workflow(context):
    """
    If context is content and part of a workflow will return the workflow.
    Otherwise returns None.
    """
    if is_content(context):
        content_type = get_content_type(context)
        return get_workflow(content_type, 'security', context)
Exemplo n.º 19
0
Arquivo: acl.py Projeto: zagy/karl
def get_context_workflow(context):
    """
    If context is content and part of a workflow will return the workflow.
    Otherwise returns None.
    """
    if is_content(context):
        content_type = get_content_type(context)
        return get_workflow(content_type, 'security', context)
Exemplo n.º 20
0
 def _callFUT(self, iface, name, workflows=None, context=None):
     if workflows is None:
         wokflows = []
     def process_workflow_list(wf_list, context):
         if workflows:
             return workflows.pop()
     from repoze.workflow import get_workflow
     return get_workflow(iface, name, context, process_workflow_list)
Exemplo n.º 21
0
    def syncuser(self, data, missing):
        for key in self.required_keys:
            if not data.get(key):
                raise ValueError("Invalid user data: '%s' key is required" % key)
        users = find_users(self.context)
        profiles = find_profiles(self.context)
        username = data.pop("username")
        profile = profiles.get(username)
        active = profile and profile.security_state == "active"
        if username in missing:
            missing.remove(username)
        if not profile:
            profile = self.createuser(data)
            self.update(profile, data)
            profiles[username] = profile
            activate = data.pop("active", "true")
            security_state = "active" if activate else "inactive"
            log.info("Created user: %s", username)
        else:
            objectEventNotify(ObjectWillBeModifiedEvent(profile))
            self.update(profile, data)
            objectEventNotify(ObjectModifiedEvent(profile))
            activate = data.pop("active", None)
            if activate is not None:
                security_state = "active" if activate else "inactive"
            else:
                security_state = profile.security_state
                activate = active
            if type(missing) is Empty:
                log.info("Updated user: %s", username)
        profile.usersync_managed = True

        if active:
            info = users.get(username)
            password = data.pop("password", info["password"])
            groups = data.pop("groups", info["groups"])
            login = data.pop("login", info["login"])
            users.remove(username)

        elif activate:  # reactivate
            log.info("Reactivating user: %s", username)
            login = data.pop("login", username)
            password = data.pop("password", None)
            groups = data.pop("groups", [])
            if not password:
                raise ValueError("Invalid user data: 'password' key is required to " "reactivate user")

        if activate:
            users.add(username, login, password, groups, encrypted=True)

        if security_state != getattr(profile, "security_state", None):
            workflow = get_workflow(IProfile, "security", profile)
            workflow.transition_to_state(profile, None, security_state)
            if security_state == "inactive":
                log.info("Deactivated user: %s", username)

        if data:
            raise ValueError("Unrecognized keys in sync data for user: %s: %s" % (username, data.keys()))
Exemplo n.º 22
0
def proposal_states_widget(node, kw):
    wf = get_workflow(IProposal, 'Proposal')
    state_values = []
    ts = _
    for info in wf._state_info(IProposal):  # Public API goes through permission checker
        item = [info['name']]
        item.append(ts(info['title']))
        state_values.append(item)
    return deform.widget.CheckboxChoiceWidget(values=state_values)
Exemplo n.º 23
0
def proposal_states_widget(node, kw):
    wf = get_workflow(IProposal, 'Proposal')
    state_values = []
    ts = _
    for info in wf._state_info(
            IProposal):  # Public API goes through permission checker
        item = [info['name']]
        item.append(ts(info['title']))
        state_values.append(item)
    return deform.widget.CheckboxChoiceWidget(values=state_values)
Exemplo n.º 24
0
    def _callFUT(self, iface, name, workflows=None, context=None):
        if workflows is None:
            wokflows = []

        def process_workflow_list(wf_list, context):
            if workflows:
                return workflows.pop()

        from repoze.workflow import get_workflow
        return get_workflow(iface, name, context, process_workflow_list)
Exemplo n.º 25
0
def test_workflow_permission(config):
    from repoze.workflow import get_workflow
    from kotti_actions.resources import LinkAction

    config.include('pyramid_zcml')
    config.include('kotti_actions')
    context = LinkAction()
    wf = get_workflow(context, 'security', context=context)
    assert wf.__dict__['_state_data']['public']['system.Everyone'] == \
        u'viewaction'
Exemplo n.º 26
0
def add_sample_users(site):
    profiles = site['profiles']
    users = site.users

    for login, firstname, lastname, email, groups in [
        ('staff1','Staff','One','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff2','Staff','Two','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff3','Staff','Three','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff4','Staff','Four','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff5','Staff','Five','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff6','Staff','Six','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff7','Staff','Seven','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff8','Staff','Eight','*****@*****.**',
         ('group.KarlStaff',)),
        ('staff9','Staff','Nine','*****@*****.**',
         ('group.KarlStaff',)),
        ('affiliate1','Affiliate','One','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate2','Affiliate','Two','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate3','Affiliate','Three','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate4','Affiliate','Four','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate5','Affiliate','Five','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate6','Affiliate','Six','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate7','Affiliate','Seven','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate8','Affiliate','Eight','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ('affiliate9','Affiliate','Nine','*****@*****.**',
         ('groups.KarlAffiliate',)),
        ]:
        if users.get(login=login) is None:
            users.add(login, login, login, groups)
        if not login in profiles:
            profile = profiles[login] = create_content(
                IProfile,
                firstname=firstname,
                lastname=lastname,
                email=email,
                )
            workflow = get_workflow(IProfile, 'security', profiles)
            if workflow is not None:
                workflow.initialize(profile)
Exemplo n.º 27
0
    def to_state(self, to_state, workflow='status', request=None):
        """Transition to selected state.

        By default, it uses the ``status`` workflow. If you want to transition
        some other workflow, pass its name in the ``workflow`` argument.

        If you want to use a ``permission_checker`` you need to set the
        ``request`` parameter. Otherwise, None is OK.
        """
        wf = get_workflow(self.__class__, workflow)
        wf.transition_to_state(self, request, to_state)
Exemplo n.º 28
0
    def workflow(self):
        try:
            self.content_type
        except AttributeError:
            raise WorkflowError("context doesn't have content_type attribute set")

        for iface in self.__class__.__implemented__.interfaces():
            wf = get_workflow(iface, self.content_type, self)
            if wf is not None:
                return wf
        raise WorkflowError("Workflow not found for %s" % self)
Exemplo n.º 29
0
def change_groupmembership_state(context, request):
    try:
        wf = get_workflow(context.group_membership, 'GroupMembershipWorkflow')
    except WorkflowError:
        raise HTTPNotFound
    try:
        wf.transition_to_state(context, request, request.params.get('destination'), skip_same=False)
    except WorkflowError:
        request.session.flash({'title': u'Błąd!', 'body': u'Nie udało się zmienić statusu.'}, queue='error')
        return HTTPFound(location='/groups/%s/manage_group_members' % context.group.id)
    request.session.flash({'title': u'Gotowe!', 'body': u'Status użytkownika został uaktualniony.'}, queue='success')
    return HTTPFound(location='/groups/%s/manage_group_members' % context.group.id)
Exemplo n.º 30
0
    def workflow(self):
        try:
            self.content_type
        except AttributeError:
            raise WorkflowError(
                "context doesn't have content_type attribute set")

        for iface in self.__class__.__implemented__.interfaces():
            wf = get_workflow(iface, self.content_type, self)
            if wf is not None:
                return wf
        raise WorkflowError("Workflow not found for %s" % self)
Exemplo n.º 31
0
def evolve(root):
    search = ICatalogSearch(root)
    num, docids, resolver = search(interfaces=[IProfile])
    allowed_index = find_catalog(root)['allowed']
    for docid in docids:
        profile = resolver(docid)
        if profile.security_state != 'inactive':
            continue

        print "Updating acl for %s" % resource_path(profile)
        workflow = get_workflow(IProfile, 'security', profile)
        workflow.reset(profile)
        allowed_index.reindex_doc(docid, profile)
Exemplo n.º 32
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.workflow = get_workflow(ICommunity, 'security', context)
     self.available_tools = get_available_tools(context, request)
     self.tools = [(x['name'], x['title']) for x in self.available_tools]
     selected_tools = []
     for info in self.available_tools:
         component = info['component']
         present = component.is_present(context, request)
         if present:
             selected_tools.append((info['name'], info['title']))
     self.selected_tools = selected_tools
Exemplo n.º 33
0
def goto_state(context, request):
    state = request.params.get('state')
    if not state:
        request.add_message(u'Missing state parameter.', 'error')
        return HTTPFound(location=request.fa_url(request.model_name, request.model_id))
    try:
        workflow = get_workflow(request.model_instance, request.model_name)
        workflow.transition_to_state(context.get_instance(), request, state, skip_same=False)
        request.add_message(u'Workflow status has been changed. New workflow state is: <strong>%s</strong>.' % state)
        return HTTPFound(location=request.fa_url(request.model_name, request.model_id))
    except WorkflowError, msg:
        request.add_message(msg, 'error')
        return HTTPFound(location=request.fa_url(request.model_name, request.model_id))
Exemplo n.º 34
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.workflow = get_workflow(ICommunity, 'security', context)
     self.available_tools = get_available_tools(context, request)
     self.tools = [(x['name'], x['title']) for x in self.available_tools]
     selected_tools = []
     for info in self.available_tools:
         component = info['component']
         present = component.is_present(context, request)
         if present:
             selected_tools.append((info['name'], info['title']))
     self.selected_tools = selected_tools
Exemplo n.º 35
0
def evolve(root):
    search = ICatalogSearch(root)
    num, docids, resolver = search(interfaces=[IProfile])
    allowed_index = find_catalog(root)["allowed"]
    for docid in docids:
        profile = resolver(docid)
        if profile.security_state != "inactive":
            continue

        print "Updating acl for %s" % resource_path(profile)
        workflow = get_workflow(IProfile, "security", profile)
        workflow.reset(profile)
        allowed_index.reindex_doc(docid, profile)
Exemplo n.º 36
0
    def handle_submit(self, converted):
        context = self.context
        community = self.community
        request = self.request
        users = find_users(context)
        profiles = self.profiles

        password = converted['password']
        password_confirm = converted['password_confirm']

        if password != password_confirm:
            msg = 'Mismatched password and confirm'
            raise ValidationError(password_confirm=msg, password=msg)

        username = converted['username']
        if username in profiles:
            raise ValidationError(username='******')

        community_href = model_url(community, request)
        groups = [ community.members_group_name ]
        users.add(username, username, password, groups)
        plugin = request.environ['repoze.who.plugins']['auth_tkt']
        identity = {'repoze.who.userid':username}
        remember_headers = plugin.remember(request.environ, identity)
        profile = create_content(
            IProfile,
            firstname=converted['firstname'],
            lastname=converted['lastname'],
            email=context.email,
            phone=converted['phone'],
            extension=converted['extension'],
            department=converted['department'],
            position=converted['position'],
            organization=converted['organization'],
            location=converted['location'],
            country=converted['country'],
            website=converted['website'],
            languages=converted['languages']
            )
        profiles[username] = profile
        workflow = get_workflow(IProfile, 'security')
        if workflow is not None:
            workflow.initialize(profile)
        handle_photo_upload(profile, converted, thumbnail=True)

        del context.__parent__[context.__name__]
        url = model_url(community, request,
                        query={'status_message':'Welcome!'})
        _send_ai_email(community, community_href, username, profile)
        self.filestore.clear()
        return HTTPFound(headers=remember_headers, location=url)
Exemplo n.º 37
0
    def ai_contents(self):
        query = Eq('path', resource_path(self.context))
        query &= Eq('type_name', 'Proposal')
        results = []
        for obj in self.catalog_query(query, resolve=True):
            results.append(
                dict(
                    text=self.request.render_proposal_text(obj, tag_func=proj_tags2links),
                    aid=obj.aid,
                    prop_wf_url=self.request.resource_url(obj, '__change_state_projector__.json'),
                    wf_state=obj.get_workflow_state(),
                    uid=obj.uid,
                    creator=self.request.creators_info(obj.creator, portrait=False, no_tag=True),
                    tags=obj.tags,
                )
            )
        next_obj = self.next_ai()
        next_url = ''
        next_title = getattr(next_obj, 'title', '')
        if next_obj:
            next_url = self.request.resource_url(next_obj, '__ai_contents__.json')
        previous_obj = self.previous_ai()
        previous_url = ''
        previous_title = getattr(previous_obj, 'title', '')
        wf_counter = Counter()
        for r in results:
            wf_counter[r['wf_state']] += 1
        wf = get_workflow(IProposal, 'Proposal')
        workflow_states = []
        for info in wf._state_info(IProposal):  # Public API goes through permission checker
            workflow_states.append({
                'name': info['name'],
                'title': self.request.localizer.translate(core_ts(info['title'])),
                'checked': info['name'] in DEFAULT_CHECKED_WORKFLOW_STATES,
                'count': wf_counter[info['name']],
            })

        if previous_obj:
            previous_url = self.request.resource_url(previous_obj, '__ai_contents__.json')
        return {'agenda_item': self.context.title,
                'ai_url': self.request.resource_url(self.request.meeting, '__projector__',
                                                    anchor=self.context.__name__),
                'ai_regular_url': self.request.resource_url(self.context),
                'proposals': results,
                'workflow_states': workflow_states,
                'next_url': next_url,
                'previous_url': previous_url,
                'next_title': next_title,
                'previous_title': previous_title}
Exemplo n.º 38
0
def adduser(root, userid, password):
    users = find_users(root)
    if users.get_by_id(userid) is not None:
        raise ValueError("User already exists with id: %s" % userid)

    profiles = find_profiles(root)
    if userid in profiles:
        raise ValueError("Profile already exists with id: %s" % userid)

    users.add(userid, userid, password, ['group.KarlAdmin'])
    profiles[userid] = create_content(
        IProfile, firstname='System', lastname='User'
    )
    wf = get_workflow(IProfile, 'security')
    wf.initialize(profiles[userid])
Exemplo n.º 39
0
    def test_state_acl(self):
        node = StateACLWorkflowNode()
        wf = get_workflow(node.__class__, node.workflow_name)
        self.assertTrue(isinstance(wf, Workflow))

        self.assertEqual(node.workflow_name, u'dummy')
        self.assertTrue(IWorkflowState.providedBy(node))

        self.assertEqual(
            node.__acl__,
            [('Allow', 'role:manager', ['manage', 'edit', 'change_state']),
             ('Allow', 'system.Everyone', ['login']),
             ('Deny', 'system.Everyone', ALL_PERMISSIONS)])

        with self.layer.authenticated('manager'):
            request = self.layer.new_request()
            wf = get_workflow(node.__class__, node.workflow_name)
            wf.transition(node, request, u'initial_2_final')
            self.assertEqual(node.state, u'final')

        self.assertEqual(
            node.__acl__,
            [('Allow', 'role:manager', ['view', 'edit', 'change_state']),
             ('Deny', 'system.Everyone', ALL_PERMISSIONS)])
Exemplo n.º 40
0
    def handle_submit(self, converted):
        context = self.context
        community = self.community
        request = self.request
        users = find_users(context)
        profiles = self.profiles

        password = converted['password']
        password_confirm = converted['password_confirm']

        if password != password_confirm:
            msg = 'Mismatched password and confirm'
            raise ValidationError(password_confirm=msg, password=msg)

        username = converted['username']
        if username in profiles:
            raise ValidationError(username='******')

        community_href = resource_url(community, request)
        groups = [ community.members_group_name ]
        users.add(username, username, password, groups)
        plugin = request.environ['repoze.who.plugins']['auth_tkt']
        identity = {'repoze.who.userid':username}
        remember_headers = plugin.remember(request.environ, identity)
        profile = create_content(
            IProfile,
            firstname=converted['firstname'],
            lastname=converted['lastname'],
            email=context.email,
            phone=converted['phone'],
            extension=converted['extension'],
            department=converted['department'],
            position=converted['position'],
            organization=converted['organization'],
            location=converted['location'],
            country=converted['country'],
            websites=converted['websites'],
            date_format=converted['date_format'],
            languages=converted['languages']
            )
        profiles[username] = profile
        workflow = get_workflow(IProfile, 'security')
        if workflow is not None:
            workflow.initialize(profile)
        try:
            handle_photo_upload(profile, converted)
        except Invalid, e:
            raise ValidationError(**e.error_dict)
Exemplo n.º 41
0
Arquivo: blog.py Projeto: lslaz1/karl
def show_blogentry_view(context, request):
    post_url = resource_url(context, request, "comments", "add_comment.html")
    workflow = get_workflow(IBlogEntry, 'security', context)

    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, context, request)

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    client_json_data = dict(
        tagbox=get_tags_client_data(context, request))

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('edit', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api.is_taggable = True

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    blog = find_interface(context, IBlog)
    backto = {
        'href': resource_url(blog, request),
        'title': blog.title,
        }

    comments = get_comment_data(context, context['comments'], api, request)
    comment_form = get_comment_form(context, context['comments'], api, request)

    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(
            context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states=security_states,
        )
Exemplo n.º 42
0
def check_cr_for_estimation(mapper, connection, target):
    state = ''
    cr = DBSession().query(CustomerRequest).get(target.customer_request_id)

    if target in cr.estimations and len(cr.estimations) == 1 and cr.workflow_state != 'created': # removing last estimation
        state = 'created'
    elif len(cr.estimations)==0 and cr.workflow_state != 'estimated':
        state = 'estimated'

    request = get_current_request()
    if state and request:
        workflow = get_workflow(cr, 'CustomerRequest')
        try:
            workflow.transition_to_state(cr, request, state, skip_same=True)
        except WorkflowError:
            pass
Exemplo n.º 43
0
def show_blogentry_view(context, request):
    post_url = resource_url(context, request, "comments", "add_comment.html")
    workflow = get_workflow(IBlogEntry, 'security', context)

    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, context, request)

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    client_json_data = dict(tagbox=get_tags_client_data(context, request))

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('edit', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api.is_taggable = True

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    blog = find_interface(context, IBlog)
    backto = {
        'href': resource_url(blog, request),
        'title': blog.title,
    }

    comments = get_comment_data(context, context['comments'], api, request)
    comment_form = get_comment_form(context, context['comments'], api, request)

    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states=security_states,
    )
Exemplo n.º 44
0
Arquivo: members.py Projeto: zagy/karl
    def handle_submit(self, converted):
        context = self.context
        community = self.community
        request = self.request
        users = find_users(context)
        profiles = self.profiles

        password = converted['password']
        password_confirm = converted['password_confirm']

        if password != password_confirm:
            msg = 'Mismatched password and confirm'
            raise ValidationError(password_confirm=msg, password=msg)

        username = converted['username']
        if username in profiles:
            raise ValidationError(username='******')

        community_href = resource_url(community, request)
        groups = [community.members_group_name]
        users.add(username, username, password, groups)
        remember_headers = remember(request, username)
        profile = create_content(IProfile,
                                 firstname=converted['firstname'],
                                 lastname=converted['lastname'],
                                 email=context.email,
                                 phone=converted['phone'],
                                 extension=converted['extension'],
                                 department=converted['department'],
                                 position=converted['position'],
                                 organization=converted['organization'],
                                 location=converted['location'],
                                 country=converted['country'],
                                 websites=converted['websites'],
                                 date_format=converted['date_format'],
                                 biography=converted['biography'],
                                 languages=converted['languages'])
        profiles[username] = profile
        workflow = get_workflow(IProfile, 'security')
        if workflow is not None:
            workflow.initialize(profile)
        try:
            handle_photo_upload(profile, converted)
        except Invalid, e:
            raise ValidationError(**e.error_dict)
Exemplo n.º 45
0
def evolve(context):
    root = find_root(context)
    searcher = ICatalogSearch(root)
    total, docids, resolver = searcher(interfaces=[IForumTopic])
    count = 0
    workflow = get_workflow(IForumTopic, 'security')
    for docid in docids:
        topic = resolver(docid)
        if has_custom_acl(topic):
            continue  # don't mess with objects customized via edit_acl
        try:
            state, msg = workflow.reset(topic)
        except:
            print "ERROR while resetting topic workflow: %s" % resource_path(
                topic)
        else:
            print "Reset topic workflow: %s" % resource_path(topic)
            count += 1
    print "Updated %d forum topic workflows" % count
Exemplo n.º 46
0
    def test_workflow(self):
        # Dummy workflow is registered for ``WorkflowNode``
        wf = get_workflow(WorkflowNode, u'dummy')
        self.assertTrue(isinstance(wf, Workflow))

        node = WorkflowNode()
        self.assertTrue(IWorkflowState.providedBy(node))

        # Workflow name is set on node properties for lookup
        self.assertEqual(node.workflow_name, u'dummy')

        # Initial workflow state gets set at node creation time if not set yet
        self.assertEqual(node.state, u'initial')

        node.state = u'final'
        self.assertEqual(node.attrs['state'], u'final')
        self.assertTrue(node.attrs['state'] is node.state)

        initialize_workflow(node)
        self.assertEqual(node.state, u'final')
Exemplo n.º 47
0
    def relocate(match):
        matchdict = match.groupdict()
        tempid = matchdict['tempid']
        if tempid in relocated_images:
            # Already relocated this one
            url = relocated_images[tempid]
        else:
            # Move temp image to attachments folder
            image = tempfolder[tempid]
            del tempfolder[tempid]
            name = make_unique_name(attachments, image.filename)
            attachments[name] = image
            size = (int(matchdict['width']), int(matchdict['height']))
            url = thumb_url(image, request, size)
            relocated_images[tempid] = url
            workflow = get_workflow(ICommunityFile, 'security', image)
            if workflow is not None:
                workflow.initialize(image)

        return ''.join([matchdict['pre'], url, matchdict['post'],])
Exemplo n.º 48
0
    def handle_submit(self, converted):
        context = self.context
        request = self.request
        workflow =  get_workflow(IComment, 'security', context)

        objectEventNotify(ObjectWillBeModifiedEvent(context))
        if workflow is not None:
            if 'security_state' in converted:
                workflow.transition_to_state(context, request,
                                             converted['security_state'])
        context.text = converted['add_comment']
        context.description = extract_description(context.text)
        creator = authenticated_userid(request)
        if support_attachments(context):
            upload_attachments(converted['attachments'], context, creator,
                               request)
        context.modified_by = creator
        objectEventNotify(ObjectModifiedEvent(context))
        location = resource_url(context, request)
        self.filestore.clear()
        return HTTPFound(location=location)
Exemplo n.º 49
0
def reset_security_workflow(root, output=None):
    count = 0
    for node in postorder(root):
        if IContent.providedBy(node):
            if has_custom_acl(node):
                continue  # don't mess with objects customized via edit_acl
            content_type = get_content_type(node)
            workflow = get_workflow(content_type, 'security', node)
            if workflow is not None:
                try:
                    state, msg = workflow.reset(node)
                except:
                    if output is not None:
                        output('Error while resetting %s' %
                               resource_path(node))
                    raise
                if output is not None:
                    if msg:
                        output(msg)
                count += 1
    if output is not None:
        output('updated %d content objects' % count)
Exemplo n.º 50
0
def calc_user_totals(total, docids, resolver, staff_set, get_workflow):
    result = dict(
        staff=0,
        core_office=0,
        national_foundation=0,
        former=0,
        affiliate=0,
        active=0,
        total=total,
    )

    wf = get_workflow(IProfile, 'security')

    for docid in docids:
        profile = resolver(docid)
        if profile is not None:
            user_info = find_user_info(profile, staff_set, wf)
            for attribute, should_include in user_info.items():
                if should_include:
                    result[attribute] = result[attribute] + 1

    return result
Exemplo n.º 51
0
Arquivo: people.py Projeto: zagy/karl
def reactivate_profile_view(context, request,
                            reset_password=request_password_reset):
    name = context.__name__
    confirm = request.params.get('confirm')
    if confirm:
        users = find_users(context)
        temp_passwd = str(uuid.uuid4())
        users.add(name, name, temp_passwd, [])
        workflow = get_workflow(IProfile, 'security', context)
        workflow.transition_to_state(context, request, 'active')
        reset_password(users.get_by_id(name), context, request)
        query = {'status_message': 'Reactivated user account: %s' % name}
        location = resource_url(context, request, query=query)

        return HTTPFound(location=location)

    page_title = 'Reactivate user account for %s %s' % (context.firstname,
                                                        context.lastname)
    api = TemplateAPI(context, request, page_title)

    # Show confirmation page.
    return dict(api=api)
Exemplo n.º 52
0
    def test_verify_workflow(self):
        workflow = get_workflow(SiteRoot, SiteRoot.__name__)
        self.assertEqual(workflow, None)

        workflow = get_workflow(IMeeting, 'Meeting')
        self.assertEqual(workflow.name, u'Meeting Workflow')

        workflow = get_workflow(IAgendaItem, 'AgendaItem')
        self.assertEqual(workflow.name, u'Agenda Item Workflow')

        workflow = get_workflow(IProposal, 'Proposal')
        self.assertEqual(workflow.name, u'Proposal Workflow')

        workflow = get_workflow(IPoll, 'Poll')
        self.assertEqual(workflow.name, u'Poll Workflow')

        workflow = get_workflow(IInviteTicket, 'InviteTicket')
        self.failUnless(workflow)
Exemplo n.º 53
0
    def handle_submit(self, converted):
        context = self.context
        request = self.request
        users = find_users(context)
        profiles = self.profiles

        password = converted['password']
        password_confirm = converted['password_confirm']

        if password != password_confirm:
            msg = 'Mismatched password and confirm'
            raise ValidationError(password_confirm=msg, password=msg)

        username = converted['username']
        if username in profiles:
            raise ValidationError(username='******')

        groups = self.get_groups()
        users.add(username, username, password, groups)
        remember_headers = remember(request, username)

        data = dict(firstname=converted['firstname'],
                    lastname=converted['lastname'],
                    email=context.email)
        for field_name in get_setting(self.context, 'member_fields'):
            if field_name in self.fields:
                data[field_name] = converted[field_name]
        profile = create_content(IProfile, **data)

        profiles[username] = profile
        workflow = get_workflow(IProfile, 'security')
        if workflow is not None:
            workflow.initialize(profile)
        try:
            handle_photo_upload(profile, converted)
        except Invalid, e:
            raise ValidationError(**e.error_dict)
Exemplo n.º 54
0
    def test_agenda_item_states(self):
        obj = AgendaItem()
        request = testing.DummyRequest()

        workflow = get_workflow(AgendaItem, AgendaItem.__name__, obj)
        obj.workflow.initialize(obj)
        self.assertEqual(obj.get_workflow_state(), u'private')

        obj.make_workflow_transition(request, 'private_to_upcoming')
        self.assertEqual(obj.get_workflow_state(), u'upcoming')

        obj.make_workflow_transition(request, 'upcoming_to_ongoing')
        self.assertEqual(obj.get_workflow_state(), u'ongoing')

        obj.workflow.initialize(obj)
        obj.make_workflow_transition(request, 'private_to_upcoming')
        obj.make_workflow_transition(request, 'upcoming_to_closed')
        self.assertEqual(obj.get_workflow_state(), u'closed')

        obj.workflow.initialize(obj)
        obj.make_workflow_transition(request, 'private_to_upcoming')
        obj.make_workflow_transition(request, 'upcoming_to_ongoing')
        obj.make_workflow_transition(request, 'ongoing_to_upcoming')
        self.assertEqual(obj.get_workflow_state(), u'upcoming')

        obj.workflow.initialize(obj)
        obj.make_workflow_transition(request, 'private_to_upcoming')
        obj.make_workflow_transition(request, 'upcoming_to_ongoing')
        obj.make_workflow_transition(request, 'ongoing_to_closed')
        self.assertEqual(obj.get_workflow_state(), u'closed')

        obj.workflow.initialize(obj)
        obj.make_workflow_transition(request, 'private_to_upcoming')
        obj.make_workflow_transition(request, 'upcoming_to_closed')
        obj.make_workflow_transition(request, 'closed_to_ongoing')
        self.assertEqual(obj.get_workflow_state(), u'ongoing')
Exemplo n.º 55
0
    def handle_submit(self, converted):
        context = self.context
        request = self.request
        parent = context.__parent__
        creator = authenticated_userid(request)
        comment = create_content(
            IComment,
            'Re: %s' % parent.title,
            converted['add_comment'],
            extract_description(converted['add_comment']),
            creator,
            )
        next_id = parent['comments'].next_id
        parent['comments'][next_id] = comment
        workflow = get_workflow(IComment, 'security', context)
        if workflow is not None:
            workflow.initialize(comment)
            if 'security_state' in converted:
                workflow.transition_to_state(comment, request,
                                             converted['security_state'])

        if support_attachments(comment):
            upload_attachments(converted['attachments'], comment,
                               creator, request)
        relocate_temp_images(comment, request)

        blogentry = find_interface(context, IBlogEntry)
        if converted.get('sendalert'):
            alerts = queryUtility(IAlerts, default=Alerts())
            alerts.emit(comment, request)

        location = resource_url(parent, request)
        msg = 'Comment added'
        location = '%s?status_message=%s' % (location, urllib.quote(msg))
        self.filestore.clear()
        return HTTPFound(location=location)
Exemplo n.º 56
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.workflow = get_workflow(ICommunity, 'security', context)
     self.available_tools = get_available_tools(context, request)
     self.tools = [(x['name'], x['title']) for x in self.available_tools]
Exemplo n.º 57
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.workflow = get_workflow(IWikiPage, 'security', context)
     self.userid = authenticated_userid(self.request)
Exemplo n.º 58
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.workflow = get_workflow(IWikiPage, 'security', context)
Exemplo n.º 59
0
def show_blog_view(context, request):
    if 'year' in request.GET and 'month' in request.GET:
        year = int(request.GET['year'])
        month = int(request.GET['month'])

        def filter_func(name, item):
            created = item.created
            return created.year == year and created.month == month

        dt = datetime.date(year, month, 1).strftime('%B %Y')
        page_title = 'Blog: %s' % dt
    else:
        filter_func = None
        page_title = 'Blog'

    api = TemplateAPI(context, request, page_title)

    actions = []
    if has_permission('create', context, request):
        actions.append(('Add Blog Entry',
                        request.resource_url(context, 'add_blogentry.html')), )

    batch = get_container_batch(context,
                                request,
                                filter_func=filter_func,
                                interfaces=[IBlogEntry],
                                sort_index='creation_date',
                                reverse=True)

    # Unpack into data for the template
    entries = []
    profiles = find_profiles(context)
    karldates = getUtility(IKarlDates)
    fmt0 = '<a href="%s#addcomment">Add a Comment</a>'
    fmt1 = '<a href="%s#comments">1 Comment</a>'
    fmt2 = '<a href="%s#comments">%i Comments</a>'

    for entry in batch['entries']:
        profile = profiles[entry.creator]
        byline_info = getMultiAdapter((entry, request), IBylineInfo)
        entry_url = resource_url(entry, request)

        # Get information about comments on this entry to display in
        # the last line of the entry
        comment_count = len(entry['comments'])
        if comment_count == 0:
            comments_blurb = fmt0 % entry_url
        elif comment_count == 1:
            comments_blurb = fmt1 % entry_url
        else:
            comments_blurb = fmt2 % (entry_url, comment_count)
        info = {
            'title': entry.title,
            'href': resource_url(entry, request),
            'description': entry.description,
            'creator_title': profile.title,
            'creator_href': entry_url,
            'long_date': karldates(entry.created, 'longform'),
            'byline_info': byline_info,
            'comments_blurb': comments_blurb,
        }
        entries.append(info)

    feed_url = "%satom.xml" % resource_url(context, request)
    workflow = get_workflow(IBlogEntry, 'security', context)
    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, None, request)

    system_email_domain = get_setting(context, "system_email_domain")
    return dict(
        api=api,
        actions=actions,
        entries=entries,
        system_email_domain=system_email_domain,
        feed_url=feed_url,
        batch_info=batch,
        security_states=security_states,
    )