Example #1
0
    def test_portlet_visibility_settings(self):
        assignment = self.layer['right_portlets'].get('title2', False)
        settings = PersistentMapping({'visible': False})
        IPortletAssignmentSettings(assignment).data = settings

        # get the data
        adapter = getAdapter(self.layer['folder1'], IDataCollector,
                             name="portlet_data_adapter")

        data = adapter.getData()
        jsondata = json.dumps(utils.decode_for_json(data))
        data = utils.encode_after_json(json.loads(jsondata))

        self.assertEqual(
            settings,
            data['plone.rightcolumn']['title2']['settings'])

        # set the data
        adapter2 = getAdapter(self.layer['folder2'], IDataCollector,
                              name="portlet_data_adapter")
        adapter2.setData(data, metadata=None)

        new_assignment = self.layer['right_portlets'].get('title2', False)
        self.assertEqual(
            settings,
            IPortletAssignmentSettings(new_assignment).data)
Example #2
0
    def test_portlets_adapter_sync(self):
        #getter
        adapter = getAdapter(self.layer['folder1'], IDataCollector,
                             name="portlet_data_adapter")
        data = adapter.getData()

        #setter - on folder2
        adapter2 = getAdapter(self.layer['folder2'], IDataCollector,
                              name="portlet_data_adapter")
        adapter2.setData(data, metadata=None)

        # add another portlet to folder1
        self.layer['left_portlets']['title3'] = static.Assignment(
            header='Title3', text="some text", omit_border=False)

        # now get data again
        adapter3 = getAdapter(
            self.layer['folder1'], IDataCollector,
            name="portlet_data_adapter")
        data2 = adapter3.getData()

        #and sync
        adapter4 = getAdapter(self.layer['folder2'], IDataCollector,
                              name="portlet_data_adapter")
        adapter4.setData(data2, metadata=None)
Example #3
0
        def _gotSession(sess):
            log.msg(
                'bit.bot.http.socket: BotSocketProtocol.dataReceived._gotSession',
                sess)

            if sess:
                getUtility(ISockets).add('bot', sessionid, token, self)
            request = queryAdapter(self, ISocketRequest, name=data['request'])
            
            if data['request'] == 'message':
                message = data['message']
                if message.startswith('>'):
                    request = getAdapter(self, ISocketRequest, name="command")
                    message = message[1:]
                    data['command'] = message.strip().split(' ')[0]
                    data['args'] = ' '.join(message.strip().split(' ')[1:])
                elif message.startswith('~'):
                    request = getAdapter(
                        self, ISocketRequest, name="subscribe")
                    data['subscribe'] = message[1:]
                else:
                    request = getAdapter(
                        self, ISocketRequest, name="message")
            else:
                request = queryAdapter(
                    self, ISocketRequest, name=data['request'])

            if request:                
                request.load(sessionid, sess, data)

            else:
                print 'NO REQUEST ADAPTER FOR: %s' % data['request']
Example #4
0
    def create_queue(self, queue):
        # Check to see if the queue exists.
        try:
            self._checking = True
            yield getAdapter(self.chan, IAMQPChannelAdapter).declareQueue(queue, True)
            return
        except ChannelClosedError as e:
            log.debug(("Channel {0} doesn't exist, attempting to create it.").format(queue.name))
            self.chan = yield self.get_channel()
        finally:
            self._checking = False

        # Declare the queue
        try:
            yield getAdapter(self.chan, IAMQPChannelAdapter).declareQueue(queue, False)
        except ChannelClosedError as e:
            # Here we handle the case where we redeclare a queue 
            # with different properties. When this happens, Rabbit
            # both returns an error and closes the channel. We
            # need to detect this and reopen the channel, since
            # the existing queue will work fine (although it will
            # not use the modified config).
            if e.replyCode == 406:
                # PRECONDITION_FAILED -- properties changed
                # Remove the channel and allow it to be reopened
                log.warn(("Attempted to redeclare queue {0} with "
                        "different arguments. You will need to "
                        "delete the queue to pick up the new "
                        "configuration.").format(queue.name))
                log.debug(e)
                self.chan = yield self.get_channel()
            else:
                raise
 def test_many_groups(self):
     getAdapter(self.portal, IUserGroupsSettingsSchema).set_many_groups(True)
     self.assertEqual(
         getAdapter(
             self.portal, IUserGroupsSettingsSchema).get_many_groups(),
         True
     )
Example #6
0
def get_node_view(node, action='', name='', ext=''):
    if ext:
        view_interface = getUtility(IViewExtFactory, ext).interface
    else:
        view_interface = INodeView

    if isinstance(node, ViewResults):
        return getAdapter(node, view_interface)

    view = None
    if name:
        try:
            factory = getUtility(INodeFactory, name)
        except ComponentLookupError:
            # /node/action/name/ - dynamic action, static name
            view = getMultiAdapter((node, action), view_interface, name)
        else:
            # /node/action/factory/ - static action
            view = getMultiAdapter((node, factory), view_interface, action)
    else:
        try:
            # /node/action/ - static action
            view = getAdapter(node, view_interface, action)
        except ComponentLookupError:
            # /node/action/ - dynamic action
            view = getMultiAdapter((node, action), view_interface)

    return view
def submitSysNumbersSearch(wfStateInfo):
    logger.info("submitSysNumberSearch")
    print "submit sysnumber search"
    originalfile = wfStateInfo.object
    # epublication = aq_parent(aq_inner(originalfile))
    with api.env.adopt_user(username="******"):
        getAdapter(originalfile, IAMQPSender, name="sysnumber-aleph-search").send()
Example #8
0
    def _bind(self):
        queueConfig = self._queueSchema.getQueue(self._queueName)

        try:
            getAdapter(self.channel, IAMQPChannelAdapter).declareQueue(queueConfig)
        except ChannelClosedError as e:
            # Here we handle the case where we redeclare a queue
            # with different properties. When this happens, Rabbit
            # both returns an error and closes the channel. We
            # need to detect this and reopen the channel, since
            # the existing queue will work fine (although it will
            # not use the modified config).
            if e.replyCode == 406:
                # PRECONDITION_FAILED -- properties changed
                # Remove the channel and allow it to be reopened
                log.warn(("Attempted to redeclare queue {0} with "
                        "different arguments. You will need to "
                        "delete the queue to pick up the new "
                        "configuration.").format(queueConfig.name))
                log.debug(e)
                self._channel = None
            else:
                raise

        for outboundExchange in self._exchanges:
            exchangeConfig = self._queueSchema.getExchange(outboundExchange)
            getAdapter(self.channel, IAMQPChannelAdapter).declareExchange(exchangeConfig)
 def _addSortUi(self, header, column):
     columnName = column.name
     resource_path = component.getAdapter(self.request, name='zc.table')()
     if (interfaces.IColumnSortedItems.providedBy(self.items) and
         self.items.sort_on):
         sortColumnName, sortReversed = self.items.sort_on[0]
     else:
         sortColumnName = sortReversed = None
     if columnName == sortColumnName:
         path = component.getAdapter(self.request, name='zc.table')()
         if sortReversed:
             dirIndicator = ('<img src="%s/sort_arrows_up.gif" '
                             'style="vertical-align: top; '
                             'margin-top: 0px" '
                             'alt="(ascending)"/>' % resource_path)
         else:
             dirIndicator = ('<img src="%s/sort_arrows_down.gif" '
                             'style="vertical-align: top; '
                             'margin-top: 0px" '
                             'alt="(descending)"/>' % resource_path)
     else:
         dirIndicator = ('<img src="%s/sort_arrows.gif" '
                         'style="vertical-align: top; '
                         'margin-top: 0px" '
                         'alt="(sortable)"/>' % resource_path)
     sort_on_name = getSortOnName(self.prefix)
     script_name = self.script_name
     return self._header_template(locals())
def submitThumbnailGenerating(wfStateInfo):
    logger.info("submitThumbnailGenerating")
    print "submit thumbnail generating"
    originalfile = wfStateInfo.object
    epublication = aq_parent(aq_inner(originalfile))
    with api.env.adopt_user(username="******"):
        getAdapter(originalfile, IAMQPSender, name="generate-thumbnail").send()
def renewAlephRecords(wfStateInfo):
    logger.info("renewAlephRecords")
    print "renew Aleph Records"
    context = wfStateInfo.object
    with api.env.adopt_user(username="******"):
        getAdapter(context, IAMQPSender, name="load-aleph-records-by-title").send()
        getAdapter(context, IAMQPSender, name="renew-aleph-records-by-icz-sysnumber").send()
    def test_properties_adapter_setter(self):
        adapter1 = getAdapter(self.layer['testdoc1'], IDataCollector,
                              name="properties_data_adapter")
        data = adapter1.getData()
        # setter
        adapter2 = getAdapter(self.layer['testdoc2'], IDataCollector,
                              name="properties_data_adapter")
        adapter2.setData(data, metadata=None)

        # test boolean
        self.assertEquals(getattr(self.layer['testdoc2'], 'bool'), True)
        # test date
        self.assertEquals(getattr(self.layer['testdoc2'], 'date'),
                          DateTime('2000/01/01'))
        # test float
        self.assertEquals(getattr(self.layer['testdoc2'], 'float'),
                          2.1000000000000001)
        # test int
        self.assertEquals(getattr(self.layer['testdoc2'], 'int'), 2)
        # test lines
        self.assertEquals(getattr(self.layer['testdoc2'], 'lines')[0], 'row1')
        self.assertEquals(getattr(self.layer['testdoc2'], 'lines')[1], 'row2')
        # test string
        self.assertEquals(getattr(self.layer['testdoc2'], 'string'),
                          'Hello World!')
Example #13
0
 def url(view):
     helper = getAdapter(context, IExposureSourceAdapter)
     exposure, workspace, path = helper.source()
     note = getAdapter(context, name=view)
     filename = note.filename or path
     return 'opencor://openFile/%s/rawfile/%s/%s' % (
         workspace.absolute_url(), exposure.commit_id, filename)
 def __init__(self, context, request):
     super(ModerationView, self).__init__(context, request)
     self.mem_list = IWriteMembershipList(context)
     annot = IAnnotations(self.context)
     self.listen_annot = annot.setdefault(PROJECTNAME, OOBTree())
     self.mod_post_pending_list = getAdapter(context, IPostPendingList, 'pending_mod_post')
     self.pmod_post_pending_list = getAdapter(context, IPostPendingList, 'pending_pmod_post')
     self.sub_pending_list = getAdapter(context, IMembershipPendingList, 'pending_sub_mod_email')
    def __call__(self):
        sub_action = self.request.get('subscribe_member', None)
        unsub_action = self.request.get('unsubscribe_member', None)
        email_action = self.request.get('subscribe_email', None)
        self.request.set('enable_border', True)
        self.errors = errors = {}

        logged_in_mem = self._get_logged_in_user()
        self.user_logged_in = False
        if logged_in_mem:
            self.user_email = lookup_email(logged_in_mem.getId(), self.context)
            self.user_logged_in = True
        else:
            #XXX what should this be?
            self.user_email = ''

        self.mem_list = IWriteMembershipList(self.context)

        # the appropriate sub_policy needs to be instantiated
        # depending on list type
        self.sub_policy = getAdapter(self.context, IUserTTWMembershipPolicy)

        if sub_action:
            self.subscribe()
        elif unsub_action:
            self.unsubscribe()
        elif email_action:
            address = self.request.get('email_address', None)
            if not address:
                errors['email_address'] = _('An email address is required')
            elif EMAIL_RE.match(address) is None:
                errors['email_address'] = _('This email address is invalid')
            elif self.mem_list.is_subscribed(address):
                errors['email_address'] = \
                                 _('This email address is already subscribed')
            else:
                # everything is OK, send a request mail the
                # appropriate sub_policy needs to be instantiated
                # depending on list type
                sub_policy_for_email = getAdapter(self.context, IUserEmailMembershipPolicy)

                ret = sub_policy_for_email.enforce({'email':address,
                                                    'subject':'subscribe'})
                if ret == MEMBERSHIP_ALLOWED:
                    # make user a subscriber
                    self.mem_list.subscribe(address)
                    self.request.set('portal_status_message', 'Email subscribed')
                elif ret == MEMBERSHIP_DEFERRED:
                    self.request.set('portal_status_message',
                                     'Subscription request sent')
                else:
                    self.request.set('portal_status_message', 'Bad email address')
                    
                # Blank the email field to avoid the postback
                self.request.set('email_address', '')
                self.request.set('subscribe_email', '')

        return self.index()
Example #16
0
    def test_reference_number_works_for_objects_marked_as_BaseDocument(self):
        d1 = createContentInContainer(self.portal, 'opengever.document.document')
        b1 = createContentInContainer(self.portal, 'SimpleDocument')
        d2 = createContentInContainer(self.portal, 'opengever.document.document')

        self.assertEquals(['Client1 / 1', 'Client1 / 2', 'Client1 / 3'],
                          [getAdapter(d1, IReferenceNumber).get_number(),
                           getAdapter(b1, IReferenceNumber).get_number(),
                           getAdapter(d2, IReferenceNumber).get_number()])
Example #17
0
    def test_find_dossier_works_for_tasks_and_subtask(self):
        dossier = create(Builder('dossier'))
        task = create(Builder('task').within(dossier))
        subtask = create(Builder('task').within(task))

        finder = getAdapter(task, name='parent-dossier-finder')
        self.assertEquals(dossier, finder.find_dossier())
        finder = getAdapter(subtask, name='parent-dossier-finder')
        self.assertEquals(dossier, finder.find_dossier())
 def test_get_filter_on_workflow(self):
     self.assertEqual(
         getAdapter(self.portal, INavigationSchema).filter_on_workflow,
         False
     )
     self.navigation_settings.filter_on_workflow = True
     self.assertEquals(
         getAdapter(self.portal, INavigationSchema).filter_on_workflow,
         True
     )
 def test_get_available_languages(self):
     self.assertEqual(
         getAdapter(self.portal, ILanguageSchema).available_languages,
         ['en']
     )
     self.settings.available_languages = ['en', 'de']
     self.assertEquals(
         getAdapter(self.portal, ILanguageSchema).available_languages,
         ['en', 'de']
     )
 def test_get_generate_tabs(self):
     self.assertEqual(
         getAdapter(self.portal, INavigationSchema).generate_tabs,
         True
     )
     self.navigation_settings.generate_tabs = False
     self.assertEquals(
         getAdapter(self.portal, INavigationSchema).generate_tabs,
         False
     )
Example #21
0
File: vc.py Project: eugeneai/ZCA
    def book_return(self, book_barcode):
        book = Book()
        book.number = book_barcode
        bookdboperation = getAdapter(book, IDbOperation)
        book = bookdboperation.get()[0]

        circulation = Circulation()
        circulation.book = book
        circulationdboperation = getAdapter(circulation, IDbOperation)
        circulationdboperation.delete()
 def test_get_show_excluded_items(self):
     self.assertEqual(
         getAdapter(self.portal, INavigationSchema).show_excluded_items,
         True
     )
     self.navigation_settings.show_excluded_items = False
     self.assertEqual(
         getAdapter(self.portal, INavigationSchema).show_excluded_items,
         False
     )
 def test_get_default_editor_setting(self):
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).default_editor,
         u'TinyMCE'
     )
     self.settings.default_editor = u'None'
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).default_editor,
         u'None'
     )
 def test_get_default_language(self):
     self.assertEqual(
         getAdapter(self.portal, ILanguageSchema).default_language,
         'en'
     )
     self.settings.default_language = 'de'
     self.assertEquals(
         getAdapter(self.portal, ILanguageSchema).default_language,
         'de'
     )
 def test_get_lock_on_ttw_edit_setting(self):
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).lock_on_ttw_edit,
         True
     )
     self.settings.lock_on_ttw_edit = False
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).lock_on_ttw_edit,
         False
     )
 def test_get_enable_link_integrity_checks_setting(self):
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).enable_link_integrity_checks,  # noqa
         True
     )
     self.settings.enable_link_integrity_checks = False
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).enable_link_integrity_checks,  # noqa
         False
     )
 def test_get_ext_editor_setting(self):
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).ext_editor,
         False
     )
     self.settings.ext_editor = True
     self.assertEqual(
         getAdapter(self.portal, IEditingSchema).ext_editor,
         True
     )
 def test_get_smtp_userid(self):
     self.assertEqual(
         getAdapter(self.portal, IMailSchema).smtp_userid,
         None
     )
     self.mail_settings.smtp_userid = u'*****@*****.**'
     self.assertEqual(
         getAdapter(self.portal, IMailSchema).smtp_userid,
         u'*****@*****.**'
     )
 def test_get_smtp_pass(self):
     self.assertEqual(
         getAdapter(self.portal, IMailSchema).smtp_pass,
         None
     )
     self.mail_settings.smtp_pass = u'secret'
     self.assertEqual(
         getAdapter(self.portal, IMailSchema).smtp_pass,
         u'secret'
     )
 def test_get_nonfolderish_tabs(self):
     self.assertEqual(
         getAdapter(self.portal, INavigationSchema).nonfolderish_tabs,
         True
     )
     self.navigation_settings.nonfolderish_tabs = False
     self.assertEquals(
         getAdapter(self.portal, INavigationSchema).nonfolderish_tabs,
         False
     )
Example #31
0
    def reply(self):
        # Disable CSRF protection
        if "IDisableCSRFProtection" in dir(plone.protect.interfaces):
            alsoProvides(self.request,
                         plone.protect.interfaces.IDisableCSRFProtection)

        portal = getSite()

        # validate important data
        data = json_body(self.request)
        self.errors = []
        self.validate_input_data(portal, data)
        security = getAdapter(self.context, ISecuritySchema)
        registration = getToolByName(self.context, "portal_registration")

        general_usage_error = (
            "Either post to @users to create a user or use "
            "@users/<username>/reset-password to update the password.")
        if len(self.params) not in [0, 2]:
            raise Exception(general_usage_error)

        if len(self.params) == 2:
            if self.params[1] == "reset-password":
                return self.update_password(data)
            raise Exception("Unknown Endpoint @users/%s/%s" % self.params)

        # Add a portal member
        if not self.can_add_member:
            return self._error(403, "Forbidden",
                               "You need AddPortalMember permission.")

        if self.errors:
            self.request.response.setStatus(400)
            return dict(error=dict(
                type="WrongParameterError",
                message="Error in fields. {}".format(self.errors_to_string()),
                errors=self.errors,
            ))

        username = data.pop("username", None)
        email = data.pop("email", None)
        password = data.pop("password", None)
        roles = data.pop("roles", ["Member"])
        send_password_reset = data.pop("sendPasswordReset", None)
        properties = data

        if PLONE5:
            # We are improving the way the userid/login_name is generated using
            # Plone's plone.app.users utilities directly. Plone 4 lacks of the
            # login_name one, so we leave it as it is, improving the Plone 5
            # story
            user_id_login_name_data = {
                "username": username,
                "email": email,
                "fullname": data.get("fullname", ""),
            }

            register_view = getMultiAdapter((self.context, self.request),
                                            name="register")

            register_view.generate_user_id(user_id_login_name_data)
            register_view.generate_login_name(user_id_login_name_data)

            user_id = user_id_login_name_data.get("user_id",
                                                  data.get("username"))
            login_name = user_id_login_name_data.get("login_name",
                                                     data.get("username"))

            username = user_id
            properties["username"] = user_id
        else:
            # set username based on the login settings (username or email)
            if security.use_email_as_login:
                username = email
                properties["username"] = email
            else:
                properties["username"] = username

        properties["email"] = email

        if not self.can_manage_users and not security.enable_user_pwd_choice:
            send_password_reset = True
        if send_password_reset:
            password = registration.generatePassword()
        # Create user
        try:
            registration = getToolByName(portal, "portal_registration")
            user = registration.addMember(username,
                                          password,
                                          roles,
                                          properties=properties)
        except ValueError as e:
            self.request.response.setStatus(400)
            return dict(
                error=dict(type="MissingParameterError", message=str(e)))

        if PLONE5:
            # After user creation, we have to fix the login_name if it differs.
            # That happens when the email login is enabled and we are using
            # UUID as user ID security settings.
            if user_id != login_name:
                # The user id differs from the login name.  Set the login
                # name correctly.
                pas = getToolByName(self.context, "acl_users")
                pas.updateLoginName(user_id, login_name)

        if send_password_reset:
            registration.registeredNotify(username)
        self.request.response.setStatus(201)
        self.request.response.setHeader(
            "Location",
            portal.absolute_url() + "/@users/" + username)
        serializer = queryMultiAdapter((user, self.request), ISerializeToJson)
        return serializer()
def became_subscriber(event):
    """
    This function should ensure that all other pending membership
    lists that the other policy adapters depend on are in sync.

    set up the phony mailing list and policies
    >>> from Products.listen.content.tests import DummyAnnotableList
    >>> from Products.listen.content.tests import DummyMembershipTool
    >>> from Products.listen.extras.tests import TestMailingList
    >>> from Products.listen.content.tests import DummyMember
    >>> from Products.listen.config import POST_DEFERRED, MEMBERSHIP_DEFERRED
    >>> ml = TestMailingList()
    >>> from zope.interface import alsoProvides
    >>> from Products.listen.interfaces import IPublicList
    >>> alsoProvides(ml, IPublicList)
    >>> mails_to_list = []
    >>> def listMail(post):
    ...     mails_to_list.append(post)
    >>> ml.listMail = listMail
    >>> from Products.listen.interfaces import IMailingList
    >>> dtool = DummyMembershipTool('foo')
    >>> dtool.result = None
    >>> ml.portal_membership = dtool
    >>> from Products.listen.content import WriteMembershipList
    >>> mlist = WriteMembershipList(ml)
    >>> from zope.component import getAdapter
    >>> from zope.component import provideAdapter
    >>> from Products.listen.interfaces import IEmailPostPolicy
    >>> from Products.listen.interfaces import IManagerTTWMembershipPolicy
    >>> postpolicy = getAdapter(ml, IEmailPostPolicy)
    >>> mempolicy = getAdapter(ml, IManagerTTWMembershipPolicy)

    test the case when an allowed sender is sent a subscription request
    by a manager and the allowed sender subscribes independently, ttw
    make sure the subscription request is no longer pending
    >>> mlist.add_allowed_sender('*****@*****.**')
    >>> mempolicy.enforce({'action':'subscribe', 'email':'*****@*****.**'}) == MEMBERSHIP_DEFERRED
    True

    make sure he's on the pending_sub_email list
    >>> from zope.annotation.interfaces import IAnnotations
    >>> annot = IAnnotations(ml)
    >>> listen_annot = annot['listen']
    >>> pend_list = listen_annot['pending_sub_email']
    >>> '*****@*****.**' in pend_list
    True

    after subscribing, he should no longer be on the pending list
    >>> mlist.subscribe('*****@*****.**')
    >>> '*****@*****.**' in pend_list
    False


    """
    
    email = event.email
    context = event.context

    # clean up pending subscription
    pend_list = getAdapter(context, IMembershipPendingList, 'pending_sub_email')
    pend_list.remove(email)
def became_allowed_sender(event):
    """
    This function should ensure that all other pending allowed sender
    lists that the other policy adapters depend on are in sync.

    set up the phony mailing list and policies
    >>> from Products.listen.content.tests import DummyAnnotableList
    >>> from Products.listen.content.tests import DummyMembershipTool
    >>> from Products.listen.extras.tests import TestMailingList
    >>> from Products.listen.content.tests import DummyMember
    >>> from Products.listen.config import POST_DEFERRED, MEMBERSHIP_DEFERRED
    >>> ml = TestMailingList()
    >>> from zope.interface import alsoProvides
    >>> from Products.listen.interfaces import IPublicList
    >>> alsoProvides(ml, IPublicList)
    >>> mails_to_list = []
    >>> def listMail(post):
    ...     mails_to_list.append(post)
    >>> ml.listMail = listMail
    >>> from Products.listen.interfaces import IMailingList
    >>> dtool = DummyMembershipTool('foo')
    >>> dtool.result = None
    >>> ml.portal_membership = dtool
    >>> from Products.listen.content import WriteMembershipList
    >>> mlist = WriteMembershipList(ml)
    >>> from zope.component import getAdapter
    >>> from zope.component import provideAdapter
    >>> from Products.listen.interfaces import IEmailPostPolicy
    >>> from Products.listen.interfaces import IUserEmailMembershipPolicy
    >>> from Products.listen.content import PublicEmailPostPolicy
    >>> from Products.listen.content import UserMembershipPolicy
    >>> postpolicy = getAdapter(ml, IEmailPostPolicy)
    >>> mempolicy = getAdapter(ml, IUserEmailMembershipPolicy)

    send a subscribe email to get on the pending list
    >>> request = dict(email='*****@*****.**',
    ...                subject='subscribe')
    >>> mempolicy.enforce(request) == MEMBERSHIP_DEFERRED
    True

    now submit a post to get on that pending list
    >>> request = dict(email='*****@*****.**',
    ...                post=dict(header={}, body='there is only zul!'))
    >>> postpolicy.enforce(request) == POST_DEFERRED
    True

    now add the email as an allowed sender
    >>> mlist.add_allowed_sender('*****@*****.**')

    make sure he's not on the allowed sender pending list
    >>> from zope.annotation.interfaces import IAnnotations
    >>> annot = IAnnotations(ml)
    >>> listen_annot = annot['listen']
    >>> a_s_list = listen_annot['a_s_pending_sub_email']
    >>> '*****@*****.**' in a_s_list
    False

    verify that the post is no longer pending and has been sent out
    >>> post_list = listen_annot['pending_mod_post']
    >>> '*****@*****.**' in post_list
    False
    >>> 'there is only zul!' in mails_to_list[0]['Mail']
    True

    try with a mem-moderated list policy
    >>> from zope.interface import directlyProvides
    >>> from Products.listen.interfaces import IMembershipModeratedList
    >>> directlyProvides(ml, IMembershipModeratedList)
    >>> postpolicy = getAdapter(ml, IEmailPostPolicy)
    >>> request = dict(email='*****@*****.**',
    ...                post=dict(header={}, body='there is only zui!'))
    >>> postpolicy.enforce(request) == POST_DEFERRED
    True
    >>> mlist.add_allowed_sender('*****@*****.**')
    >>> '*****@*****.**' in post_list
    False
    >>> 'there is only zui!' in mails_to_list[1]['Mail']
    True

    make someone who is pending subscription moderation an allowed sender
    and make sure they get automatically subscribed
    >>> from Products.listen.interfaces import IMembershipPendingList
    >>> sub_mod_pending_list = getAdapter(ml, IMembershipPendingList, 'pending_sub_mod_email')
    >>> sub_mod_pending_list.add('*****@*****.**')
    >>> mlist.add_allowed_sender('*****@*****.**')
    >>> mlist.is_subscribed('*****@*****.**')
    True

    now try subscribing a member who is pending subscription moderation
    >>> sub_mod_pending_list.add('*****@*****.**')
    >>> mlist.subscribe('*****@*****.**')
    >>> mlist.is_subscribed('*****@*****.**')
    True

    """
    
    email = event.email
    context = event.context

    # clean up pending subscription
    pend_list = getAdapter(context, IPostPendingList, 'a_s_pending_sub_email')
    pend_list.remove(email)

    # if member is waiting for moderation to become a subscriber
    # then subscribe member
    sub_pending_list = getAdapter(context, IMembershipPendingList, 'pending_sub_mod_email')
    if sub_pending_list.is_pending(email):
        mlist = IWriteMembershipList(context)
        mail_sender = ISendMail(context)
        sub_pending_list.remove(email)
        mlist.subscribe(email)
        mail_sender.user_welcome(email, email)

    # clean up pending posts
    post_mod_list = getAdapter(context, IPostPendingList, 'pending_mod_post')
    # XXX currently expecting one post,
    # this is not the case for Post Moderated Lists
    # send the post for the user to the list
    posts = post_mod_list.get_posts(email)
    # uniquify posts
    post_dict = {}
    for p in posts:
        post_dict[p['body']] = p['header']
    posts = [dict(header=v, body=k) for k,v in post_dict.iteritems()]
    send_pending_posts(context, posts)
    post_mod_list.remove(email)
Example #34
0
 def values(self):
     return getAdapter(self.i18n_context, interface=IRSSValues).values
Example #35
0
 def test_set_generate_tabs(self):
     self.assertEquals(self.navigation_settings.generate_tabs, True)
     getAdapter(self.portal, INavigationSchema).generate_tabs = False
     self.assertEquals(self.navigation_settings.generate_tabs, False)
Example #36
0
 def test_set_workflow_states_to_show(self):
     self.assertEqual(self.navigation_settings.workflow_states_to_show, ())
     getAdapter(self.portal,
                INavigationSchema).workflow_states_to_show = ('private', )
     self.assertEqual(self.navigation_settings.workflow_states_to_show,
                      ('private', ))
Example #37
0
def check_tender_status_on_active_qualification_stand_still(request):

    tender = request.validated['tender']
    config = getAdapter(tender, IContentConfigurator)
    now = get_now()
    active_lots = [lot.id for lot in tender.lots
                   if lot.status == 'active'] if tender.lots else [None]
    if not (tender.awardPeriod and tender.awardPeriod.endDate <= now
            and not any([
                i.status in tender.block_complaint_status
                for a in tender.awards
                for i in a.complaints if a.lotID in active_lots
            ])):
        return
    statuses = set()
    if tender.lots:
        for lot in tender.lots:
            if lot.status != 'active':
                statuses.add(lot.status)
                continue
            active_lot_awards = [
                i for i in tender.awards
                if i.lotID == lot.id and i.status == 'active'
            ]
            if len(active_lot_awards) < config.min_bids_number:
                LOGGER.info('Switched lot {} of tender {} to {}'.format(
                    lot.id, tender.id, 'unsuccessful'),
                            extra=context_unpack(
                                request,
                                {'MESSAGE_ID': 'switched_lot_unsuccessful'},
                                {'LOT_ID': lot.id}))
                lot.status = 'unsuccessful'
                statuses.add(lot.status)
                continue
            statuses.add(lot.status)
    else:
        active_awards = [i for i in tender.awards if i.status == 'active']
        if len(active_awards) <= config.min_bids_count:
            statuses.add('unsuccessful')
        else:
            statuses.add('active.awarded')

    if statuses == set(['cancelled']):
        LOGGER.info('Switched tender {} to {}'.format(tender.id, 'cancelled'),
                    extra=context_unpack(
                        request, {'MESSAGE_ID': 'switched_tender_cancelled'}))
        tender.status = 'cancelled'
    elif not statuses.difference(set(['unsuccessful', 'cancelled'])):
        LOGGER.info('Switched tender {} to {}'.format(tender.id,
                                                      'unsuccessful'),
                    extra=context_unpack(
                        request,
                        {'MESSAGE_ID': 'switched_tender_unsuccessful'}))
        tender.status = 'unsuccessful'
    else:
        LOGGER.info('Switched tender {} to {}'.format(tender.id,
                                                      'active.awarded'),
                    extra=context_unpack(
                        request,
                        {'MESSAGE_ID': 'switched_tender_active_awarded'}))
        tender.status = 'active.awarded'
        tender.contractPeriod = {'startDate': now}
        tender.contractPeriod['clarificationsUntil'] = calculate_business_date(
            now, config.clarifications_until_period, tender, False)
        lots = [l for l in tender.get('lots', []) if l.status == 'active']
        if lots:
            for lot in lots:
                agreement_data = generate_agreement_data(request, tender, lot)
                agreement = type(tender).agreements.model_class(agreement_data)
                agreement.__parent__ = tender
                tender.agreements.append(agreement)
        else:
            agreement_data = generate_agreement_data(request, tender)
            agreement = type(tender).agreements.model_class(agreement_data)
            agreement.__parent__ = tender
            tender.agreements.append(agreement)
Example #38
0
 def test_set_set_cookie_always(self):
     self.assertEqual(self.settings.set_cookie_always, False)
     getAdapter(self.portal, ILanguageSchema).set_cookie_always = True
     self.assertEqual(self.settings.set_cookie_always, True)
Example #39
0
 def test_adapter_lookup(self):
     self.assertTrue(getAdapter(self.portal, ILanguageSchema))
Example #40
0
 def test_set_authenticated_users_only(self):
     self.assertEqual(self.settings.authenticated_users_only, False)
     getAdapter(self.portal,
                ILanguageSchema).authenticated_users_only = True
     self.assertEqual(self.settings.authenticated_users_only, True)
Example #41
0
 def audio_type(self):
     mime_type = self.context.get_content_type()
     accessor = component.getAdapter(self.context,
                                     interfaces.IAudioDataAccessor,
                                     unicode(mime_type))
     return accessor.audio_type
Example #42
0
 def test_set_show_excluded_items(self):
     self.assertEqual(self.navigation_settings.show_excluded_items, True)
     getAdapter(self.portal, INavigationSchema).show_excluded_items = False
     self.assertEqual(self.navigation_settings.show_excluded_items, False)
Example #43
0
 def email_as_username(self):
     return getAdapter(aq_inner(self.context),
                       ISecuritySchema).get_use_email_as_login()
Example #44
0
 def many_groups(self):
     return getAdapter(aq_inner(self.context),
                       IUserGroupsSettingsSchema).many_groups
Example #45
0
    def value(self):
        # create a GeoPoint Class
        SpatialThing = self.session.get_class(surf.ns.GEO.SpatialThing)

        geo = getAdapter(self.context, IGeoTags)

        output = []
        i = 0

        cty_names = {
            u'Macedonia': u'North Macedonia',
            u'Czech Republic': u'Czechia',
            u'Kosovo': u'Kosovo (UNSCR 1244/99)'
        }
        cty_names_keys = cty_names.keys()

        country_groups = COUNTRY_GROUPS
        country_groups_keys = country_groups.keys()
        country_groups_keys_index = [ki[0] for ki in country_groups_keys]
        for feature in geo.getFeatures():
            rdfp = self.session.get_resource("#geotag%s" % i, SpatialThing)

            label = feature['properties']['title']
            # do not add current countries_group locations as they
            # will be added on rdf export when adding all of the country groups
            if label in country_groups_keys_index:
                continue
            description = feature['properties']['description']
            if label in cty_names_keys:
                label = cty_names[label]
                description = label
            rdfp[surf.ns.RDFS['comment']] = description

            if label == description or not description:
                friendly_name = label
            else:
                friendly_name = label + ' (' + description + ')'
            rdfp[surf.ns.DCTERMS['title']] = friendly_name
            rdfp[surf.ns.RDFS['label']] = friendly_name

            tags = feature['properties']['tags']
            rdfp[surf.ns.DCTERMS['type']] = tags

            latitude = feature['properties']['center'][0]
            rdfp[surf.ns.GEO['lat']] = float(latitude)

            longitude = feature['properties']['center'][1]
            rdfp[surf.ns.GEO['long']] = float(longitude)

            other = feature['properties'].get('other', {})
            if other.has_key('geonameId'):
                geonamesURI = 'http://sws.geonames.org/%s/' % (str(
                    feature['properties']['other']['geonameId']))
                rdfp[surf.ns.OWL['sameAs']] = rdflib.URIRef(geonamesURI)
            rdfp.update()
            output.append(rdfp)
            i += 1

        # 85617 add country groups to rdf output
        found_groups = []
        location = self.get_location()
        correct_country_names = cty_names.values()
        for k, v in country_groups.items():
            differences = set(v).difference(location)
            if differences:
                for country_name in correct_country_names:
                    if country_name in differences:
                        differences.remove(country_name)
                if not differences:
                    found_groups.append(k)
            else:
                found_groups.append(k)
        for group in found_groups:
            label = group[0]
            if label in location:
                continue
            rdfp = self.session.get_resource("#geotag%s" % i, SpatialThing)
            title = group[1]
            full_title = label + ' (' + title + ')'
            rdfp[surf.ns.DCTERMS['title']] = full_title
            rdfp[surf.ns.RDFS['label']] = full_title
            rdfp[surf.ns.RDFS['comment']] = title + ': ' + \
                                            ', '.join(
                                                country_groups[(label, title)])
            rdfp[surf.ns.DCTERMS['type']] = 'countries_group'
            rdfp[surf.ns.SKOS['notation']] = label
            uri = 'http://rdfdata.eionet.europa.eu/eea/countries/%s' % label
            rdfp[surf.ns.OWL['sameAs']] = rdflib.URIRef(uri)
            rdfp.update()
            output.append(rdfp)
            i += 1

        return output
Example #46
0
 def get_config(self):
     return getAdapter(self.layer['request'],
                       interfaces.IWorkflowConfiguration,
                       name=self.workflow_id)
Example #47
0
 def test_set_default_language(self):
     self.assertEqual(self.settings.default_language, 'en')
     getAdapter(self.portal, ILanguageSchema).default_language = 'de'
     self.assertEqual(self.settings.default_language, 'de')
Example #48
0
 def getSuppliers(self):
     adapter = getAdapter(self.aq_parent, name='getSuppliers')
     return adapter()
Example #49
0
 def test_adapter_lookup(self):
     self.assertTrue(getAdapter(self.portal, IEditingSchema))
Example #50
0
 def test_set_displayed_types(self):
     getAdapter(self.portal,
                INavigationSchema).displayed_types = ('Folder', )
     self.assertEqual(self.navigation_settings.displayed_types,
                      ('Folder', ))
Example #51
0
 def getContacts(self):
     adapter = getAdapter(self.context.aq_parent, name='getContacts')
     return adapter()
Example #52
0
 def test_set_filter_on_workflow(self):
     self.assertEqual(self.navigation_settings.filter_on_workflow, False)
     getAdapter(self.portal, INavigationSchema).filter_on_workflow = True
     self.assertEqual(self.navigation_settings.filter_on_workflow, True)
Example #53
0
 def test_set_available_languages(self):
     self.assertEqual(self.settings.available_languages, ['en'])
     getAdapter(self.portal,
                ILanguageSchema).available_languages = ['de', 'en']
     self.assertEqual(self.settings.available_languages, ['de', 'en'])
Example #54
0
 def test_set_nonfolderish_tabs(self):
     self.assertEquals(self.navigation_settings.nonfolderish_tabs, True)
     getAdapter(self.portal, INavigationSchema).nonfolderish_tabs = False
     self.assertEquals(self.navigation_settings.nonfolderish_tabs, False)
Example #55
0
 def test_xml_adapter(self):
     serializer = getAdapter(self.content,
                             uvcsite.content.interfaces.ISerializer,
                             name="application/xml")
     with self.assertRaises(NotImplementedError):
         serializer()
Example #56
0
 def test_set_use_combined_language_codes(self):
     self.assertEqual(self.settings.use_combined_language_codes, True)
     getAdapter(self.portal,
                ILanguageSchema).use_combined_language_codes = False
     self.assertEqual(self.settings.use_combined_language_codes, False)
Example #57
0
 def test_set_display_flags(self):
     self.assertEqual(self.settings.display_flags, False)
     getAdapter(self.portal, ILanguageSchema).display_flags = True
     self.assertEqual(self.settings.display_flags, True)
Example #58
0
 def test_set_use_content_negotiation(self):
     self.assertEqual(self.settings.use_content_negotiation, False)
     getAdapter(self.portal, ILanguageSchema).use_content_negotiation = True
     self.assertEqual(self.settings.use_content_negotiation, True)
Example #59
0
 def render(self):
     renderer = getAdapter(self,
                           IPortletContainerRenderer,
                           name=self.data.container_view)
     return renderer()
Example #60
0
 def test_adapter_lookup(self):
     self.assertTrue(getAdapter(self.portal, INavigationSchema))