Beispiel #1
0
 def _rename_assets(self):
     records = api.content.find(context=self.context,
                                portal_type=[
                                    "Image",
                                ])
     asset_idx = 0
     for record in records:
         asset_obj = record.getObject()
         # Rename records
         try:
             asset = getattr(asset_obj, 'image', None)
             if asset:
                 asset_filename = getattr(asset, 'filename', record.Title)
                 asset_obj.setTitle(asset_filename)
                 modified(asset_obj)
                 asset_obj.reindexObject(idxs='modified')
                 asset_idx += 1
         except AttributeError:
             # Handle error
             logger.info(
                 " - Could not rename image {0} with identifier {1}".format(
                     record.getId, record.UID()))
     logger.info(
         "Renamed {0} assets to use the actual filename as title".format(
             asset_idx))
Beispiel #2
0
def plonegroup_contact_changed(organization, event):
    """
        Manage an organization change
    """
    # zope.lifecycleevent.ObjectRemovedEvent : delete
    # zope.lifecycleevent.ObjectModifiedEvent : edit, rename
    # is the container who's modified at creation ?
    # bypass if we are removing the Plone Site
    if IContainerModifiedEvent.providedBy(event) or \
       event.object.portal_type == 'Plone Site':
        return
    # invalidate vocabularies caches
    invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.CreatingGroupVocabulary')
    invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.ActiveCreatingGroupVocabulary')
    invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.TreatingGroupsWithDeactivatedVocabulary')
    invalidate_cachekey_volatile_for('imio.dms.mail.vocabularies.TreatingGroupsForFacetedFilterVocabulary')
    # is the current organization a part of own organization
    organization_path = '/'.join(organization.getPhysicalPath())
    if not organization_path.startswith(get_own_organization_path('unfound')):
        return
    portal = api.portal.getSite()
    pcat = portal.portal_catalog
    brains = pcat.unrestrictedSearchResults(portal_type='organization', path=organization_path)
    for brain in brains:
        obj = brain._unrestrictedGetObject()
        full_title = obj.get_full_title(separator=' - ', first_index=1)
        for base_folder in (portal['templates']['om'], portal.contacts['contact-lists-folder']):
            folder = base_folder.get(brain.UID)
            if folder and folder.title != full_title:
                folder.title = full_title
                folder.reindexObject(idxs=['Title', 'SearchableText', 'sortable_title'])
                modified(folder)
Beispiel #3
0
 def _create_panel(self):
     context = aq_inner(self.context)
     token = django_random.get_random_string(length=24)
     title = self.request.form.get('title')
     new_title = 'row'
     if title:
         new_title = title
     block = {
         'id': token,
         'title': new_title,
         'status': 'visible',
         'klass': 'pp-row-default',
         'panels': [
             {
                 'uuid': None,
                 'component': u"placeholder",
                 'grid-col': 12,
                 'klass': 'pp-column'
             }
         ]
     }
     items = getattr(context, 'panelPageLayout', None)
     if items is None:
         items = list()
     items.append(block)
     setattr(context, 'panelPageLayout', items)
     modified(context)
     context.reindexObject(idxs='modified')
     url = '{0}/@@panelpage-editor'.format(context.absolute_url())
     return url
Beispiel #4
0
def after_recover(sample):
    """Unassigns the sample from its storage container and "recover". It also
    transitions the sample to its previous state before it was stored
    """
    container = _api.get_storage_sample(api.get_uid(sample))
    if container:
        container.remove_object(sample)
    else:
        logger.warn("Container for Sample {} not found".format(sample.getId()))

    # Transition the sample to the state before it was stored
    previous_state = get_previous_state(sample) or "sample_due"
    changeWorkflowState(sample, "bika_ar_workflow", previous_state)

    # Notify the sample has ben modified
    modified(sample)

    # Reindex the sample
    sample.reindexObject()

    # If the sample is a partition, try to promote to the primary
    primary = sample.getParentAnalysisRequest()
    if not primary:
        return

    # Recover primary sample if all its partitions have been recovered
    parts = primary.getDescendants()

    # Partitions in some statuses won't be considered.
    skip = ['stored']
    parts = filter(lambda part: api.get_review_status(part) in skip, parts)
    if not parts:
        # There are no partitions left, transition the primary
        do_action_for(primary, "recover")
 def render(self):
     folder = IResponseContainer(self.context)
     form = self.request.form
     context = aq_inner(self.context)
     if not self.can_edit_response:
         msg = _(u'You are not allowed to edit responses.')
         api.portal.show_message(message=msg, request=self.request, type='error')
     else:
         response_id = form.get('response_id', None)
         if response_id is None:
             msg = _(u'No response selected for saving.')
             api.portal.show_message(message=msg, request=self.request, type='error')
         elif folder[response_id] is None:
             msg = _(u'Response does not exist anymore; perhaps it was removed by another user.')
             api.portal.show_message(message=msg, request=self.request, type='error')
         else:
             response = folder[response_id]
             response_text = form.get('response', u'')
             response.text = response_text
             msg = _(
                 u'Changes saved to response id ${response_id}.',
                 mapping=dict(response_id=response_id)
             )
             api.portal.show_message(message=msg, request=self.request)
             modified(response, context)
     self.request.response.redirect(context.absolute_url())
Beispiel #6
0
 def _create_report(self):
     context = aq_inner(self.context)
     date = datetime.datetime.now()
     token = django_random.get_random_string(length=24)
     item = api.content.create(
         type='xpose.seodash.report',
         id=token,
         title='Report {0} {1}'.format(date.strftime("%B"),
                                       date.strftime("%Y")),
         container=context,
         safe_id=True
     )
     uuid = api.content.get_uuid(obj=item)
     template_file = os.path.join(os.path.dirname(__file__),
                                  'report.json')
     template = Template(open(template_file).read())
     template_vars = {
         'id': uuid_tool.uuid4(),
         'uid': uuid,
         'timestamp': int(time.time()),
         'created': datetime.datetime.now(),
         'dashboard': api.content.get_uuid(obj=context),
     }
     report = template.substitute(template_vars)
     setattr(item, 'report', report)
     modified(item)
     item.reindexObject(idxs='modified')
     return uuid
Beispiel #7
0
 def create_content(self, ctype, parent=None, **kwargs):
     """Create instance of dexterity content type"""
     if parent is None:
         parent = self.portal
     content = createContentInContainer(parent, ctype, checkConstraints=False, **kwargs)
     modified(content)
     return content
Beispiel #8
0
    def dumpOutput(self, data):
        batch_list = data.get('batch_list', [])
        add_count = 0

        generator = getUtility(IUUIDGenerator)
        gid = generator()

        today = datetime.datetime.today()
        year, month, day = today.year, today.month, today.day
        container = make_folder(self.aq_parent, (year, month, day))

        for entry in batch_list:
            obj = createContentInContainer(container,
                                           portal_type='Tumour',
                                           gid=gid)
            if obj:
                add_count += 1
                fields = dict((field[0], field[1])
                              for field in getFieldsInOrder(self._list_schema))
                for name, value in entry.items():
                    if name in fields and fields[name].readonly is False:
                        setattr(obj, name, value)
                obj.steps = 'step1'
                if 'sample_no' in entry:
                    obj.title = entry['sample_no']
                modified(obj)

        api.portal.show_message(
            _(u'${count} Item created', mapping={'count': add_count}),
            self.request, 'info')
        logger.info(
            '{count} item(s) added successfully.'.format(count=add_count))

        return add_count
Beispiel #9
0
def _create_content(item_dict, container, force=False):
    if not force and container.get(item_dict['id'], None) is not None:
        return

    layout = item_dict.pop('layout', None)
    default_page = item_dict.pop('default_page', None)
    allowed_types = item_dict.pop('allowed_types', None)
    local_roles = item_dict.pop('local_roles', [])
    children = item_dict.pop('children', [])
    state = item_dict.pop('state', None)

    new = api.content.create(container=container, safe_id=True, **item_dict)
    logger.info('Created {0} at {1}'.format(new.portal_type,
                                            new.absolute_url()))

    if layout is not None:
        new.setLayout(layout)
    if default_page is not None:
        new.setDefaultPage(default_page)
    if allowed_types is not None:
        _constrain(new, allowed_types)
    for local_role in local_roles:
        api.group.grant_roles(groupname=local_role['group'],
                              roles=local_role['roles'],
                              obj=new)
    if state is not None:
        api.content.transition(new, to_state=state)

    modified(new)
    for subitem in children:
        _create_content(subitem, new)
    def handleOK(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return
        try:
            valid = is_valid_isbn(data['isbn'])
        except:
            print sys.exc_info()
            raise ActionExecutionError(Invalid(u"Objevila se nějaká chyby při volání Aleph služby! (%s)" % (str(sys.exc_info()),)))

        if not valid:
            raise ActionExecutionError(Invalid(u"ISBN není validní!"))

        try:
            appearedAtAleph = getISBNCount(data['isbn'])
        except:
            print sys.exc_info()
            raise ActionExecutionError(Invalid(u"Objevila se nějaká chyby při volání Aleph služby! (%s)" % (str(sys.exc_info()),)))

        if appearedAtAleph:
            raise ActionExecutionError(Invalid(u"ISBN už v Alephu existuje!"))

        wft = api.portal.get_tool('portal_workflow')
        self.context.isbn = data['isbn']
        modified(self.context)
        wft.doActionFor(self.context, 'submitISBNGeneration')
        self.status = u"Hotovo!"
def add_order_container(event):
    context = event.context
    if not IShoppingSite(context).order_container():
        container = createContentInContainer(
            context, 'collective.cart.core.OrderContainer',
            id="order-container", title="Order Container", checkConstraints=False)
        modified(container)
 def update(self):
     context = aq_inner(self.context)
     self.errors = {}
     if 'form.button.Delete' in self.request:
         authenticator = getMultiAdapter((context, self.request),
                                         name=u"authenticator")
         if not authenticator.verify():
             raise Unauthorized
         form = self.request.form
         current_layout = context.layout_order
         try:
             headlines = json.loads(context.headlines)
         except TypeError:
             headlines = {}
         uuid = form.get('headline.uid', None)
         del headlines[uuid]
         new_headlines = json.dumps(headlines)
         setattr(context, 'headlines', new_headlines)
         current_layout.remove(uuid)
         setattr(context, 'layout_order', current_layout)
         modified(context)
         context.reindexObject(idxs='modified')
         api.portal.show_message(
             message=_(u"Headline successfully removed."),
             request=self.request)
         next_url = context.absolute_url() + '/@@edit-layout'
         return self.request.response.redirect(next_url)
 def __setitem__(self, key, value):
     if not isinstance(key, str):
         raise ValueError('Only plain ascii keys are accepted')
     if not isinstance(value, str):
         raise ValueError('Only plain ascii values are accepted')
     self._dict[key] = value
     modified(self, key)
 def update(self):
     context = aq_inner(self.context)
     self.errors = {}
     if 'form.button.Submit' in self.request:
         authenticator = getMultiAdapter((context, self.request),
                                         name=u"authenticator")
         if not authenticator.verify():
             raise Unauthorized
         form = self.request.form
         current_layout = context.layout_order
         try:
             headlines = json.loads(context.headlines)
         except TypeError:
             headlines = {}
         new_item = {}
         new_uuid = base64.b64encode(os.urandom(24))
         new_item['title_de'] = form['headline-de']
         new_item['title_en'] = form['headline-en']
         headlines[new_uuid] = new_item
         new_headlines = json.dumps(headlines)
         setattr(context, 'headlines', new_headlines)
         if self.has_open_session():
             session = self.open_session()
             if session is not None:
                 session.append(new_uuid)
         current_layout.append(new_uuid)
         setattr(context, 'layout_order', current_layout)
         modified(context)
         context.reindexObject(idxs='modified')
         api.portal.show_message(
             message=_(u"Item successfully added."), request=self.request)
         next_url = context.absolute_url() + '/@@edit-layout'
         return self.request.response.redirect(next_url)
 def test_articles(self):
     from Products.CMFCore.utils import getToolByName
     from collective.cart.core.interfaces import IShoppingSiteRoot
     from plone.uuid.interfaces import IUUID
     from zope.interface import alsoProvides
     from zope.lifecycleevent import modified
     alsoProvides(self.portal, IShoppingSiteRoot)
     workflow = getToolByName(self.portal, 'portal_workflow')
     context = self.create_content('collective.cart.core.Article')
     article1 = self.create_content('collective.cart.core.Article', money=self.money('10.00'), title='Ärticle1')
     workflow.doActionFor(article1, 'publish')
     uuid1 = IUUID(article1)
     modified(article1)
     article2 = self.create_content('collective.cart.core.Article', money=self.money('20.00'), title='Ärticle2')
     workflow.doActionFor(article2, 'publish')
     uuid2 = IUUID(article2)
     modified(article2)
     context.related_articles = [uuid1, uuid2]
     instance = self.create_viewlet(RelatedArticlesViewlet, context)
     self.assertEqual(instance.articles(), [{
         'gross': self.money('10.00'),
         'image_url': 'http://nohost/plone/fallback.png',
         'title': 'Ärticle1',
         'url': 'http://nohost/plone/article1'
     }, {
         'gross': self.money('20.00'),
         'image_url': 'http://nohost/plone/fallback.png',
         'title': 'Ärticle2',
         'url': 'http://nohost/plone/article2'
     }])
Beispiel #16
0
 def postprocess_ac_record(self):
     context = aq_inner(self.context)
     report = self.report()
     ac_data = getattr(context, 'report_ac')
     ac_report = json.loads(ac_data)
     metric = report[1]
     table = metric['dataTable']
     rows = table['rows']
     for entry in ac_report[:50]:
         time_rec = entry['record_date']['mysql']
         time_comps = time_rec.split('-')
         entry_date = '{0}.{1}.{2}'.format(time_comps[2],
                                           time_comps[1],
                                           time_comps[0])
         new_row = {
             'xd:trackingDate': entry_date,
             'xd:trackingUserId': entry['user']['display_name'],
             'xd:trackingSummary': entry['summary'],
             'xd:trackingValue': entry['value']
         }
         rows.append(new_row)
     table['rows'] = rows
     metric['dataTable'] = table
     stored = getattr(context, 'report')
     data = json.loads(stored)
     items = data['items']
     items[1] = metric
     setattr(context, 'report', json.dumps(data))
     modified(context)
     context.reindexObject(idxs='modified')
     msg = _(u"Built links data table was successfully updated")
     api.portal.show_message(msg, self.request)
     return msg
Beispiel #17
0
 def create_content(self, ctype, parent=None, **kwargs):
     """Create instance of dexterity content type"""
     if parent is None:
         parent = self.portal
     content = createContentInContainer(parent, ctype, checkConstraints=False, **kwargs)
     modified(content)
     return content
Beispiel #18
0
 def create_folder(self):
     from plone.dexterity.utils import createContentInContainer
     folder = createContentInContainer(
         self.portal, 'collective.behavior.sku.Folder', id='folder',
         checkConstraints=False, title='Földer', description='Description of Földer.')
     modified(folder)
     return folder
Beispiel #19
0
def ObjectModifiedEventHandler(instance, event):
    """Actions to be taken when AnalysisRequest object is modified
    """
    # If Internal Use value has been modified, apply suitable permissions
    internal_use = instance.getInternalUse()
    if internal_use != IInternalUse.providedBy(instance):

        # Update permissions for current sample
        update_internal_use_permissions(instance)

        # Mark/Unmark all analyses with IInternalUse to control their
        # visibility in results reports
        for analysis in instance.objectValues("Analysis"):
            if internal_use:
                alsoProvides(analysis, IInternalUse)
            else:
                noLongerProvides(analysis, IInternalUse)

            # Reindex analysis security in catalogs
            analysis.reindexObjectSecurity()

        # If internal use is True, cascade same setting to partitions
        if internal_use:
            for partition in instance.getDescendants():
                partition.setInternalUse(internal_use)
                # Notify the partition has been modified
                modified(partition)
Beispiel #20
0
 def __setitem__(self, key, value):
     if not isinstance(key, str):
         raise ValueError('Only plain ascii keys are accepted')
     if not isinstance(value, str):
         raise ValueError('Only plain ascii values are accepted')
     self._dict[key] = value
     modified(self, key)
Beispiel #21
0
 def clean_ac_record(self):
     context = aq_inner(self.context)
     data = getattr(context, 'report_ac')
     as_json = json.dumps(data)
     setattr(context, 'report_ac', as_json)
     modified(context)
     return as_json
Beispiel #22
0
 def _update_report_data(self, data):
     context = aq_inner(self.context)
     metric = self.report()
     new_row = {
         'xd:linkDate': data['lb-date'],
         'xd:linkSourceURI': data['lb-source'],
         'xd:linkTargetURI': data['lb-target'],
         'xd:linkText': data['lb-text']
     }
     table = metric['dataTable']
     rows = table['rows']
     rows.append(new_row)
     table['rows'] = rows
     metric['dataTable'] = table
     stored = getattr(context, 'report')
     data = json.loads(stored)
     items = data['items']
     items[0] = metric
     setattr(context, 'report', json.dumps(data))
     modified(context)
     context.reindexObject(idxs='modified')
     msg = _(u"Built links data table was successfully updated")
     api.portal.show_message(msg, self.request)
     portal_url = api.portal.get().absolute_url()
     url = '{0}/adm/'.format(portal_url)
     return self.request.response.redirect(url)
Beispiel #23
0
 def _refresh_configuration(self, data):
     context = aq_inner(self.context)
     xovi_tool = getUtility(IXoviTool)
     project_list = xovi_tool.get(
         service=u'project',
         method=u'getProjects',
         limit=50
     )
     projects = json.dumps(project_list)
     setattr(context, 'projects_xovi', projects)
     daily_domains = xovi_tool.get(
         service=u'seo',
         method=u'getDailyDomains',
         limit=50
     )
     domains = json.dumps(daily_domains)
     setattr(context, 'domains_xovi', domains)
     modified(context)
     context.reindexObject(idxs='modified')
     IStatusMessage(self.request).addStatusMessage(
         _(u"The Xovi configuration has sucessfully been refreshed"),
         type='info')
     portal_url = api.portal.get().absolute_url()
     param = '/adm/@@setup-xovi'
     url = portal_url + param
     return self.request.response.redirect(url)
def setUp(self):
    layer = self.globs['layer']
    browser = Browser(layer['app'])
    portal = layer['portal']
    self.globs.update({
        'TEST_USER_NAME': TEST_USER_NAME,
        'TEST_USER_PASSWORD': TEST_USER_PASSWORD,
        'browser': browser,
        'portal': portal,
    })
    browser.setBaseUrl(portal.absolute_url())
    browser.handleErrors = True
    portal.error_log._ignored_exceptions = ()

    setRoles(portal, TEST_USER_ID, ['Manager'])

    alsoProvides(portal, IShoppingSiteRoot)
    portal.reindexObject()

    container = createContentInContainer(
        portal, 'collective.cart.core.OrderContainer', checkConstraints=False, id='order-container', title='Örder Cöntäiner')
    modified(container)

    order1 = createContentInContainer(container, 'collective.cart.core.Order', checkConstraints=False, id='1')
    modified(order1)

    transaction.commit()
Beispiel #25
0
 def __call__(self):
     form = self.request.form
     context = aq_inner(self.context)
     status = IStatusMessage(self.request)
     if not self.can_edit_response:
         msg = _(u"You are not allowed to edit responses.")
         msg = translate(msg, 'Poi', context=self.request)
         status.addStatusMessage(msg, type='error')
     else:
         response_id = form.get('response_id', None)
         if response_id is None:
             msg = _(u"No response selected for saving.")
             msg = translate(msg, 'Poi', context=self.request)
             status.addStatusMessage(msg, type='error')
         else:
             response = self.folder[response_id]
             response_text = form.get('response', u'')
             response.text = response_text
             # Remove cached rendered response.
             response.rendered_text = None
             msg = _(u"Changes saved to response id ${response_id}.",
                     mapping=dict(response_id=response_id))
             msg = translate(msg, 'Poi', context=self.request)
             status.addStatusMessage(msg, type='info')
             # Fire event.  We put the context in the descriptions
             # so event handlers can use this fully acquisition
             # wrapped object to do their thing.  Feels like
             # cheating, but it gets the job done.  Arguably we
             # could turn the two arguments around and signal that
             # the issue has changed, with the response in the
             # event descriptions.
             modified(response, context)
     self.request.response.redirect(context.absolute_url())
Beispiel #26
0
 def _update_panel_asignment(self, data):
     context = aq_inner(self.context)
     item = uuidToObject(self.uuid)
     current = getattr(item, 'panels', list())
     idx = int(self.slot)
     panel = data['panel']
     if not current:
         updated = list()
         updated.append(panel)
     else:
         list_idx = len(current) - 1
         updated = current
         if panel:
             if idx > list_idx:
                 updated.append(panel)
             else:
                 del updated[idx]
                 updated.insert(idx, panel)
     setattr(item, 'panels', updated)
     modified(context)
     context.reindexObject(idxs='modified')
     base_url = context.absolute_url()
     params = '/@@panel-asignment?uuid={0}'.format(self.uuid)
     next_url = base_url + params
     return self.request.response.redirect(next_url)
Beispiel #27
0
 def _apply(self, **data):
     if ((data.get('removed_values', None)
          and data['action_choice'] in ('remove', 'replace'))
             or (data.get('added_values', None))
             and data['action_choice'] in ('add', 'replace', 'overwrite')):
         intids = getUtility(IIntIds)
         for brain in self.brains:
             obj = brain.getObject()
             if data['action_choice'] in ('overwrite'):
                 items = set(data['added_values'])
             else:
                 # we get the linked objects
                 items = set([
                     intids.getObject(rel.to_id)
                     for rel in (getattr(obj, self.attribute) or [])
                     if not rel.isBroken()
                 ])
                 if data['action_choice'] in ('remove', 'replace'):
                     items = items.difference(data['removed_values'])
                 if data['action_choice'] in ('add', 'replace'):
                     items = items.union(data['added_values'])
             # transform to relations
             rels = [RelationValue(intids.getId(ob)) for ob in items]
             setattr(obj, self.attribute, rels)
             modified(obj)
    def create_order(self, order_id=None):
        """Create order into order container from cart in session

        :param order_id: Order ID
        :type order_id: str

        :rtype: collective.cart.core.Order
        """
        container = self.order_container()
        articles = self.cart_articles()
        if container and articles:
            if order_id is None:
                order_id = str(container.next_order_id)
            order = createContentInContainer(
                container, "collective.cart.core.Order", id=order_id, checkConstraints=False
            )
            modified(order)
            self.update_next_order_id()
            for uuid in articles:
                article = createContentInContainer(
                    order, "collective.cart.core.OrderArticle", checkConstraints=False, **articles[uuid]
                )
                modified(article)

            return order
Beispiel #29
0
 def handle_submit(self, REQUEST=None):
     logger.info("senaite.databox::handle_submit")
     form_data = self.get_form_data()
     for key, value in form_data.items():
         logger.info("Set field '{}' -> {}".format(key, value))
         setattr(self.databox, key, value)
     modified(self.context)
    def setUpContent(self):
        pat.login(self.portal, testing.SITE_ADMIN)

        self.challenge = helpers.create_challenge(
            self.challenges, "a-real-challenge")

        for i in range(0, 20):
            wsId = "workspace_" + str(i)
            wsName = u"Workspace " + str(i)
            ws = ws_helpers.create_workspace(self.workspaces,
                wsId, title=wsName,
                challenges=[relatify(self.challenge)])
            modified(ws)

        for i in range(0, 5):
            projectId = 'project_' + str(i)
            projectName = u"Prøjėçt " + str(i)
            project = helpers.create_project(
                self.workspaces, projectId,
                title=projectName,
                challenges=[relatify(self.challenge)],
                description=u"A lengthy but interesting description",
                goals=u"Lorem ipsum. Add goals here.")
            ws_helpers.do_action_for(project, 'publish')

            for j in range(0,3):
                wsId = "project_workspace_" + str(i) + "_" + str(j)
                wsName = u"Project-Workspace " + str(i) + " " + str(j)
                ws = ws_helpers.create_workspace(self.workspaces,
                    wsId, title=wsName)
                project.add_workspace(ws)

        pat.logout()
 def test_renaming_workspace_updates_group_titles(self):
     self.workspace.setTitle('new title')
     from zope.lifecycleevent import modified
     modified(self.workspace)
     group = self.portal.portal_groups.getGroupById(
         'Admins:' + self.workspace.UID())
     self.assertEqual(group.getProperty('title'), 'Admins: new title')
 def setUp(self):
     self.portal = self.layer['portal']
     self.request = self.layer['request']
     self.portal_url = self.portal.absolute_url()
     setRoles(self.portal, TEST_USER_ID, ['Manager'])
     self.doc1 = api.content.create(
         container=self.portal,
         type='Document',
         title=u'Some Document',
     )
     self.doc1.text = RichTextValue(u'One two', 'text/plain', 'text/html')
     self.browser = Browser(self.layer['app'])
     self.browser.handleErrors = False
     modified(self.doc1)
     self.statscache = getUtility(IHistoryStatsCache)
     self.statscache.refresh()
     import transaction
     transaction.commit()
     # Set up browser
     self.browser = Browser(self.layer['app'])
     self.browser.handleErrors = False
     self.browser.addHeader(
         'Authorization',
         'Basic {}:{}'.format(SITE_OWNER_NAME, SITE_OWNER_PASSWORD,)  # noqa: P101
     )
Beispiel #33
0
 def importOrderableItems(self, data):
     context = aq_inner(self.context)
     logger = getLogger('ShopContentImport')
     io = StringIO.StringIO(data)
     reader = csv.reader(io, delimiter=';', dialect="excel", quotechar='"')
     header = reader.next()
     processed_records = 0
     transaction_threshold = 50
     for row in reader:
         code = self.getSpecificRecord(header, row, name=u'productCode')
         title = self.getSpecificRecord(header, row, name=u'title_de')
         title_en = self.getSpecificRecord(header, row, name=u'title_en')
         data = {
             'title': title,
             'title_de': title,
             'title_en': title_en,
             'productCode': code}
         if not code:
             logger.info('Product code missing for record %s' % title)
         else:
             logger.info('Processing file: %s' % title)
             item = createContentInContainer(
                 context,
                 'chromsystems.shopcontent.orderableitem',
                 checkConstraints=True, **data)
             modified(item)
         processed_records += 1
         if processed_records % transaction_threshold == 0:
             transaction.commit()
     return processed_records
Beispiel #34
0
 def __call__(self):
     form = self.request.form
     context = aq_inner(self.context)
     status = IStatusMessage(self.request)
     if not self.can_edit_response:
         msg = _(u"You are not allowed to edit responses.")
         msg = translate(msg, 'Poi', context=self.request)
         status.addStatusMessage(msg, type='error')
     else:
         response_id = form.get('response_id', None)
         if response_id is None:
             msg = _(u"No response selected for saving.")
             msg = translate(msg, 'Poi', context=self.request)
             status.addStatusMessage(msg, type='error')
         else:
             response = self.folder[response_id]
             response_text = form.get('response', u'')
             response.text = response_text
             # Remove cached rendered response.
             response.rendered_text = None
             msg = _(u"Changes saved to response id ${response_id}.",
                     mapping=dict(response_id=response_id))
             msg = translate(msg, 'Poi', context=self.request)
             status.addStatusMessage(msg, type='info')
             # Fire event.  We put the context in the descriptions
             # so event handlers can use this fully acquisition
             # wrapped object to do their thing.  Feels like
             # cheating, but it gets the job done.  Arguably we
             # could turn the two arguments around and signal that
             # the issue has changed, with the response in the
             # event descriptions.
             modified(response, context)
     self.request.response.redirect(context.absolute_url())
def return_stock_to_original_article(context, event):
    if event.action == 'canceled':
        adapter = IOrderAdapter(context)
        for article in adapter.articles():
            orig_article = adapter.get_object(IArticle, path=adapter.portal_path(), UID=article['id'])
            if orig_article:
                IStock(orig_article).add_stock(article['quantity'])
                modified(orig_article)
Beispiel #36
0
 def render(self):
     item = self.report()
     setattr(item, 'approved', True)
     modified(item)
     item.reindexObject(idxs='modified')
     portal_url = api.portal.get().absolute_url()
     url = '{0}/adm/@@review-queue'.format(portal_url)
     return self.request.response.redirect(url)
Beispiel #37
0
 def _set_text(self, obj, text):
     if IDexterityContent.providedBy(obj):
         # Dexterity
         obj.text = RichTextValue(text, 'text/html', 'text/x-html-safe')
     else:
         # Archetypes
         obj.setText(text, mimetype='text/html')
     modified(obj)
Beispiel #38
0
 def _apply(self, **data):
     if data['assigned_user']:
         if data['assigned_user'] == '__none__':
             data['assigned_user'] = None
         for brain in self.brains:
             obj = brain.getObject()
             obj.assigned_user = data['assigned_user']
             modified(obj, Attributes(ITask, 'ITask.assigned_user'))
 def reduce_stocks(self):
     """Reduce stocks from articles"""
     for item in self.cart_article_listing():
         uuid = item['id']
         quantity = item['quantity']
         obj = self.get_object(UID=uuid)
         IStock(obj).sub_stock(quantity)
         modified(obj)
 def create_stock(self, folder, oid, stock):
     from plone.dexterity.utils import createContentInContainer
     from zope.lifecycleevent import modified
     obj = createContentInContainer(
         folder, 'collective.cart.stock.Stock', id=oid, stock=stock)
     modified(obj)
     obj.reindexObject()
     return obj
Beispiel #41
0
 def test_reindex_suborganization(self):
     before = self.portal.portal_catalog(UID=self.brigadelh.UID())[0].get_full_title
     self.assertEqual(before, u'Arm\xe9e de terre / Corps A / Division Alpha / R\xe9giment H / Brigade LH')
     self.armeedeterre.title = u"Armée de l'air"
     from zope.lifecycleevent import modified
     modified(self.armeedeterre)
     after = self.portal.portal_catalog(UID=self.brigadelh.UID())[0].get_full_title
     self.assertEqual(after, u"Arm\xe9e de l'air / Corps A / Division Alpha / R\xe9giment H / Brigade LH")
 def _apply(self, **data):
     if data['assigned_user']:
         if data['assigned_user'] == '__none__':
             data['assigned_user'] = None
         for brain in self.brains:
             obj = brain.getObject()
             obj.assigned_user = data['assigned_user']
             modified(obj, Attributes(ITask, 'ITask.assigned_user'))
Beispiel #43
0
 def _set_text(self, obj, text):
     if IDexterityContent.providedBy(obj):
         # Dexterity
         obj.text = RichTextValue(text)
     else:
         # Archetypes
         obj.setText(text, mimetype='text/html')
     modified(obj)
Beispiel #44
0
    def test_remove_cleans_ref_catalog(self):
        doc1 = self.portal['doc1']
        doc1.text = RichTextValue('<a href="doc1">doc1</a>')
        modified(doc1)
        ref_catalog = self.portal.reference_catalog
        self.assertEquals(1, len(ref_catalog()))

        self.portal.manage_delObjects(['doc1'])
        self.assertEquals(0, len(ref_catalog()))
Beispiel #45
0
    def handleRepair(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        query = Indexed('chimpfeeds')
        brains = self.context.portal_catalog.evalAdvancedQuery(query)

        context = self.getContent()
        vocabulary = feeds_factory(context)
        all_feeds = set(term.value for term in vocabulary)

        count = 0
        bad = set()

        changed = []
        for i, brain in enumerate(brains):
            try:
                feeds = set(brain.chimpfeeds)
            except TypeError:
                continue

            missing = feeds - all_feeds
            bad |= missing

            if missing:
                count += 1
                obj = brain.getObject()
                try:
                    field = obj.getField('feeds')
                except AttributeError:
                    feeds = obj.feeds
                    field = None
                else:
                    feeds = set(field.get(obj))

                fixed = feeds - missing

                if field is None:
                    obj.feeds = fixed
                else:
                    field.set(obj, fixed)

                changed.append(obj)

        for obj in changed:
            modified(obj)
            obj.reindexObject()

        logger.info("Repair complete; %d items updated." % count)
        if bad:
            logger.info("Feeds removed: %s." %
                        (", ".join(bad).encode('utf-8')))

        IStatusMessage(self.request).addStatusMessage(
            _(u"Repaired ${count} items.", mapping={'count': count}), "info")
Beispiel #46
0
 def cleanupFTI(self):
     """Cleanup the FTIs"""
     generated_name = self.getGeneratedName()
     for (name, fti) in self.sm.getUtilitiesFor(IDexterityFTI):
         if generated_name in fti.behaviors:
             fti.behaviors = [behavior for behavior in
                              fti.behaviors
                              if behavior != generated_name]
         modified(fti, DexterityFTIModificationDescription("behaviors", ''))
Beispiel #47
0
 def delete(self, uuid, key=None):
     stored = self.read(uuid)
     if key is not None:
         stored[key] = dict()
         updated = json.dumps(stored)
         item = api.content.get(UID=uuid)
         setattr(item, 'assets', updated)
         modified(item)
         item.reindexObject(idxs='modified')
     return uuid
Beispiel #48
0
 def migrate_tasks(self):
     for brain in self.catalog(portal_type='task'):
         obj = brain.getObject()
         # replace userid by organization
         if not obj.enquirer or obj.enquirer not in self.registry[ORGANIZATIONS_REGISTRY]:
             if base_hasattr(obj.aq_parent, 'treating_groups') and obj.aq_parent.treating_groups:
                 obj.enquirer = obj.aq_parent.treating_groups
             elif base_hasattr(obj.aq_parent, 'assigned_group') and obj.aq_parent.assigned_group:
                 obj.enquirer = obj.aq_parent.assigned_group
             modified(obj)
Beispiel #49
0
    def push_data(self):
        data = self.request.get('json', '[]')
        data_list = json.loads(data)
        names = getFieldNamesInOrder(IAnalysisResults)
        names.remove('uuid')
        names.remove('sample_no')
        success_count = 0

        for entry in data_list:
            return_obj = ReturnData()
            [setattr(return_obj, key, entry[key]) for key in entry]
            errors = schema.getValidationErrors(IAnalysisResults, return_obj)

            if errors:
                msg = []
                for error in errors:
                    error_type = error[1].__class__.__name__
                    field_value = unicode(error[1])
                    err = u'{0}: {1}; '.format(error_type, field_value)
                    msg.append(err)
                msg = ''.join(msg)
                entry.update(dict(_back_success=False, _back_message=msg))
                logger.warn(msg)
                continue
            else:
                uuid = entry['uuid']
                obj = api.content.uuidToObject(uuid)
                if obj:
                    [setattr(obj, k, entry[k]) for k in entry if k in names]
                    old_steps = obj.steps
                    new_steps = u'step5'
                    obj.steps = new_steps
                    notify(StepsChangedEvent(obj, old_steps, new_steps))
                    modified(obj)
                    try:
                        api.content.transition(obj=obj, transition='submit')
                    except (MissingParameterError,
                            InvalidParameterError) as error:
                        msg = 'Warning, {0}'.format(str(error))
                        logger.warn(error)
                    else:
                        msg = 'Success.'
                    success_count += 1
                    entry.update(dict(_back_success=True, _back_message=msg))
                else:
                    msg = u'Warning, ' \
                          u'uuid "{0}" not found, skipping.'.format(uuid)
                    entry.update(dict(_back_success=False, _back_message=msg))
                    logger.warn(msg)

        failed_count = len(data_list) - success_count
        msg = u'Analysis of Results: {0} Item Succeeded, ' \
              u'{1} Item Failed.'.format(success_count, failed_count)
        logger.info(msg)
        return json.dumps(data_list)
Beispiel #50
0
def setUp(self):
    layer = self.globs['layer']
    browser = Browser(layer['app'])
    portal = layer['portal']
    # Update global variables within the tests.
    self.globs.update({
        'TEST_USER_NAME': TEST_USER_NAME,
        'TEST_USER_PASSWORD': TEST_USER_PASSWORD,
        'portal': portal,
        'browser': browser,
    })
    ztc.utils.setupCoreSessions(layer['app'])
    browser.setBaseUrl(portal.absolute_url())

    browser.handleErrors = True
    portal.error_log._ignored_exceptions = ()

    setRoles(portal, TEST_USER_ID, ['Manager'])

    # Set the site back in English mode to make testing easier.
    portal.portal_languages.manage_setLanguageSettings('en', ['en', 'fi'])

    workflow = getToolByName(portal, 'portal_workflow')

    # Add two shipping method
    shipping_method_container = portal['toimitustavat']
    shipping_method1 = shipping_method_container[shipping_method_container.invokeFactory('ShippingMethod', 'shippingmethod1',
        title='ShippingMethöd1', vat=24.0)]
    modified(shipping_method1)
    workflow.doActionFor(shipping_method1, 'publish')
    shipping_method2 = shipping_method_container[shipping_method_container.invokeFactory('ShippingMethod', 'shippingmethod2',
        title='ShippingMethöd2', vat=24.0)]
    modified(shipping_method2)
    workflow.doActionFor(shipping_method2, 'publish')

    regtool = getToolByName(portal, 'portal_registration')
    regtool.addMember('member1', 'member1')
    setRoles(portal, 'member1', ['Member'])

    # ## Setup MockMailHost
    from Products.CMFPlone.tests.utils import MockMailHost
    from Products.MailHost.interfaces import IMailHost
    from zope.component import getSiteManager
    portal._original_MailHost = portal.MailHost
    portal.MailHost = mailhost = MockMailHost('MailHost')
    sm = getSiteManager(context=portal)
    sm.unregisterUtility(provided=IMailHost)
    sm.registerUtility(mailhost, provided=IMailHost)
    self.globs.update({
        'mailhost': portal.MailHost,
        # 'prink': prink,
    })

    transaction.commit()
Beispiel #51
0
 def create(self, uuid, data=None):
     item = api.content.get(UID=uuid)
     start = time.time()
     initial_data = self._create_record(uuid, item, data)
     end = time.time()
     initial_data.update(dict(_runtime=end - start))
     json_data = json.dumps(initial_data)
     setattr(item, 'assets', json_data)
     modified(item)
     item.reindexObject(idxs='modified')
     return json_data
def objectRemovedEvent(context, event):
    """Handle event that content was removed.

    We need to remove the translation from its translation graph (if
    applicable).
    """

    container = event.oldParent
    wrapped = context.__of__(container)
    obj = ITranslationGraph(wrapped).detach()
    if obj is not None:
        modified(obj)
Beispiel #53
0
 def _process_image_asset(self, field_key, field_value):
     portal = api.portal.get()
     asset_repository = portal['asset-repository']
     widget_file = api.content.create(container=asset_repository,
                                      type="Image",
                                      title="Widget Asset {0}".format(
                                          self.generate_hash_from_filename(
                                              field_value.filename), ),
                                      image=field_value)
     modified(widget_file)
     widget_file.reindexObject(idxs='modified')
     return widget_file.UID()
Beispiel #54
0
def add_shipping_info_to_address_book_for_the_first_time(event):
    member = IMember(event.context)
    if member.area and not member.default_shipping_info:
        data = IShoppingSite(event.context).get_address('shipping')
        oid = u'{}1'.format('shipping')
        info = createContentInContainer(
            member.area, 'collective.cart.shopping.CustomerInfo', id=oid, checkConstraints=False, **data)

        if not IShoppingSite(event.context).billing_same_as_shipping:
            info.info_type = u'shipping'

        modified(info)
    def test_relations_export(self):
        image = api.content.create(self.portal, 'Image', 'image1',
                                   u'❤︎ly Pløne Image')
        image.description = "This is my image."
        image.image = dummy_image()
        file1 = api.content.create(self.portal, 'File', 'file1',
                                   u'❤︎ly Pløne File')
        file1.description = "This is my file."
        file1.file = dummy_image()
        file_without_blob = api.content.create(self.portal, 'File',
                                               'file-without-blob',
                                               u'Pløne File without a blob')
        # Add relations
        doc = self.portal['doc1']
        intids = getUtility(IIntIds)
        doc.relatedItems = PersistentList()
        doc.relatedItems.append(RelationValue(intids.getId(image)))
        doc.relatedItems.append(RelationValue(intids.getId(file1)))
        doc.relatedItems.append(RelationValue(intids.getId(file_without_blob)))
        modified(doc)
        view = api.content.get_view('collective_contentexport_view',
                                    self.portal, self.request)
        view(export_type='related', portal_type='Document')
        self.assertEqual(view.request.response.headers['content-disposition'],
                         'attachment; filename="related.zip"')
        size = int(view.request.response.headers['content-length'])
        self.assertTrue(2750 < size < 2800)

        view = api.content.get_view('collective_contentexport_view',
                                    self.portal, self.request)
        results = view(export_type='json', portal_type='Document')
        results = json.loads(results)
        related = results[0]['relatedItems']
        self.assertEquals(len(related.split(',')), 3)
        self.assertIn('http://nohost/plone/image1/@@download/image', related)
        self.assertIn('http://nohost/plone/file1/@@download/file', related)
        # TODO: Fix this
        self.assertIn('http://nohost/plone/file-without-blob/@@download/file',
                      related)

        # make sure blacklist and whitelist work for related
        results = view(export_type='related',
                       portal_type='Document',
                       blacklist=['relatedItems'])
        self.assertEqual('No related found', results)
        results = view(export_type='related',
                       portal_type='Document',
                       whitelist=['relatedItems'])
        self.assertIsNone(results)
        self.assertEqual(view.request.response.headers['content-disposition'],
                         'attachment; filename="related.zip"')
        size = int(view.request.response.headers['content-length'])
        self.assertTrue(2750 < size < 2800)
    def handleUse(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = _("Please correct errors.")
            return

        obj = data['target']
        lt = getToolByName(self.context, 'portal_languages')

        default_lang = lt.getDefaultLanguage()

        language = aq_base(self.context).language or default_lang
        obj_lang = aq_base(obj).language or default_lang

        if language == obj_lang:
            lang_name = self.request.locale.displayNames.languages.get(
                obj_lang, _(u"n/a"))

            self.status = _(
                u"The referenced content item is set to the "
                u"same language: ${lang}.",
                mapping={'lang': lang_name})

            return

        # Check if an existing translation in the current language
        # already exists.
        translations = ITranslationGraph(obj).getTranslations()
        for lang_id, item in translations:
            if lang_id or default_lang != language:
                continue

            parent = ITranslationGraph(item).detach()
            if parent is not None:
                title = item.Title().decode('utf-8')
                IStatusMessage(self.request).addStatusMessage(
                    _(
                        u"The existing reference to \"${title}\" has "
                        u"been replaced.",
                        mapping={'title': title}), "info")

                modified(parent)

        # Register new translation.
        ITranslationGraph(self.context).registerTranslation(obj)
        modified(obj)

        IStatusMessage(self.request).addStatusMessage(
            _(u"Translation registered."), "info")

        next_url = self.context.absolute_url()
        self.request.response.redirect(next_url)
Beispiel #57
0
    def test_referal_to_private_files(self):
        # This tests the behaviour of the link integrity code when a to
        # be deleted item is referred to by some page the current user
        # has no permission to view. In this case the privacy of the
        # linking user should be protected, so neither the name or url
        # of the linking page should be shown. First we need to create
        # the link in question and set up the permissions accordingly.
        doc = self.portal.doc1
        img = self.portal.image1
        self._set_text(doc, '<a href="image1">Image 1</a>')

        roles = ('Member', )
        self.portal.manage_permission('List folder contents', roles=roles)
        self.portal.manage_permission('Delete objects', roles=roles)
        doc.manage_permission('View', roles=('Manager', ), acquire=0)
        doc.manage_permission('Access contents information',
                              roles=('Manager', ),
                              acquire=0)

        logout()
        login(self.portal, 'member')
        checkPermission = self.portal.portal_membership.checkPermission
        self.assertFalse(checkPermission('View', doc))
        self.assertFalse(checkPermission('Access contents information', doc))
        self.assertTrue(checkPermission('View', img))
        self.assertTrue(checkPermission('Access contents information', img))

        # The warning is shown.
        self.assertTrue(hasOutgoingLinks(doc))
        view = img.restrictedTraverse('delete_confirmation')
        results = view()
        self.assertIn('Potential link breakage', results)
        self.assertIn('The item is not accessible.', results)

        # delete linked item and check if the source still has the relation

        # TODO: There is a permission-problem. Deleting the relation
        # When deleting the linked obj the relation is deleted by
        # z3c.relationfield.event.breakRelations. That also fires
        # ObjectModifiedEvent on the linked obj even though the user might not
        # have the permission to edit that obj.
        # Here plone.app.versioningbehavior.subscribers.create_version_on_save
        # for the linked object is triggerted and results in
        # Unauthorized: You are not allowed to access 'save' in this context

        # self.portal.manage_delObjects(img.id)
        self.portal._delObject(img.id, suppress_events=True)

        logout()
        login(self.portal, TEST_USER_NAME)
        modified(doc)
        self.assertFalse(hasOutgoingLinks(doc))
Beispiel #58
0
 def render(self):
     context = aq_inner(self.context)
     tool = getUtility(IWigoTool)
     hostname = getattr(context, 'server', '')
     if hostname is not None:
         data = tool.get(hostname=hostname)
         setattr(context, 'serverdetails', json.dumps(data))
         modified(context)
         context.reindexObject(idxs='modified')
         IStatusMessage(self.request).addStatusMessage(
             _(u"The panel has successfully been updated"), type='info')
         next_url = context.absolute_url()
         return self.request.response.redirect(next_url)