def __contains__(self, value): if isinstance(value, basestring): uid = value else: uid = IUUID(value) if uid[0] == '/': # it is a path query site = getSite() site_path = '/'.join(site.getPhysicalPath()) path = os.path.join(site_path, uid.lstrip('/')) if self.search_catalog({'path': {'query': path, 'depth': 0}}): return True else: if self.search_catalog({'UID': uid}): return True
def short_uuid(obj): uuid = IUUID(obj, None) if uuid is not None: portal_catalog = getToolByName(obj, 'portal_catalog') short_uuids = portal_catalog.uniqueValuesFor('short_uuid') uuid = uuid.replace('-', '') for i in xrange(0, 32): short_uuid_ = uuid[:i] if short_uuid_ in short_uuids: same_short = portal_catalog.searchResults( short_uuid=short_uuid_ ) if len(same_short) > 0 and same_short[0]['UID'] == uuid: return short_uuid_ else: return short_uuid_ return uuid
def __contains__(self, value): """used during validation to make sure the selected item is found with the specified query. value can be either a string (hex value of uuid or path) or a plone content object. """ if not isinstance(value, basestring): # here we have a content and fetch the uuid as hex value value = IUUID(value) # else we have uuid hex value or path if value.startswith('/'): # it is a path query site = getSite() site_path = '/'.join(site.getPhysicalPath()) path = os.path.join(site_path, value.lstrip('/')) query = {'path': {'query': path, 'depth': 0}} else: # its a uuid query = {'UID': value} return bool(self.search_catalog(query))
def test_surgery_drop_duplicate_from_acquisition_from_catalog_for_missing_uuid( self): grandchild = create( Builder('folder').within(self.child).titled(u'nastygrandchild')) old_grandchild_path = '/'.join(grandchild.getPhysicalPath()) # move object into parent's parent self.parent.manage_pasteObjects( self.child.manage_cutObjects(grandchild.getId()), ) # re-register old grandchild path with different rid rid = self.choose_next_rid() self.catalog.uids[old_grandchild_path] = rid self.catalog.paths[rid] = old_grandchild_path self.catalog.indexes['UID']._unindex[rid] = IUUID(grandchild) self.catalog.data[rid] = {} self.catalog._length.change(1) result = self.run_healthcheck() self.assertFalse(result.is_healthy()) self.assertEqual(1, len(result.get_unhealthy_rids())) unhealthy_rid = result.get_unhealthy_rids()[0] self.assertEqual(( 'in_catalog_not_in_uuid_index', 'in_uuid_unindex_not_in_uuid_index', ), result.get_symptoms(unhealthy_rid.rid)) doctor = CatalogDoctor(self.catalog, unhealthy_rid) self.assertIs(RemoveRidOrReindexObject, doctor.get_surgery()) self.perform_surgeries(result) self.assert_no_unhealthy_rids() self.assertNotIn(old_grandchild_path, self.catalog.uids) self.assertNotIn(rid, self.catalog.paths) self.assertNotIn(rid, self.catalog.indexes['UID']._unindex) self.assertNotIn(rid, self.catalog.data)
def afterTraversal(event): """ check it should be blocked by lockout """ request = event.request if not ICastleLayer.providedBy(request): return robot_view = shield.protect(request) resp = request.response if robot_view: resp.setBody(robot_view, lock=True) resp.setHeader('X-Robots-Tag', 'noindex') context = get_context_from_request(request) # make sure content in private folders remains private if api.user.is_anonymous(): if hasattr(context, 'UID'): brain = api.portal.get_tool('portal_catalog')(UID=context.UID())[0] if getattr(brain, 'has_private_parents', False): raise NotFound cache_tags = set([ getattr(context, 'portal_type', '').lower().replace(' ', '-'), getattr(context, 'meta_type', '').lower().replace(' ', '-'), IUUID(context, ''), urlparse(request.URL).netloc.lower().replace('.', '').replace(':', '') ]) resp.setHeader('Cache-Tag', ','.join(t for t in cache_tags if t)) # Prevent IE and Chrome from incorrectly detecting non-scripts as scripts resp.setHeader('X-Content-Type-Options', 'nosniff') # prevent some XSS from browser resp.setHeader('X-XSS-Protection', '1; mode=block')
def test_add_to_folder(self): browser = Browser(self.layer['app']) browser.handleErrors = False # Login browser.open(self.portal.absolute_url() + '/login') browser.getControl(name='__ac_name').value = TEST_USER_NAME browser.getControl(name='__ac_password').value = TEST_USER_PASSWORD browser.getControl('Log in').click() # Enter the add screen for a temporary portal_factory-managed object browser.open(self.folder.absolute_url() + '/++add++MyDocument') # We should now have cookies with the drafts information cookies = browser.cookies.forURL(browser.url) self.assertEqual( '"{0}"'.format(self.folder.absolute_url_path()), cookies['plone.app.drafts.path'] ) self.assertEqual( # noqa '"{}"'.format(IUUID(self.folder)), cookies['plone.app.drafts.targetKey'], ) self.assertNotIn( 'plone.app.drafts.draftName', browser.cookies.forURL(browser.url), ) # We can now cancel the edit. The cookies should expire. browser.getControl(name='form.buttons.cancel').click() self.assertNotIn( 'plone.app.drafts.targetKey', browser.cookies.forURL(browser.url), ) self.assertNotIn( 'plone.app.drafts.path', browser.cookies.forURL(browser.url), )
def test_existing_content_tile_show_comments(self): """ """ # Allow discussion registry = queryUtility(IRegistry) settings = registry.forInterface(IDiscussionSettings) settings.globally_enabled = True page_id = self.portal.invokeFactory('Document', 'a-commented-page', title=u'A commented page', description=u'A description', text=u'Hello World!') page = self.portal[page_id] page_uuid = IUUID(page) transaction.commit() self.unprivileged_browser.open( self.portalURL + '/@@plone.app.standardtiles.existingcontent/unique?content_uid=' + page_uuid + '&show_comments=True') self.assertIn(u'0', self.unprivileged_browser.contents) conversation = IConversation(page) comment1 = createObject('plone.Comment') comment1.title = 'Comment 1' comment1.text = 'Comment text' comment1.creator = 'jim' comment1.author_username = '******' comment1.creation_date = datetime(2006, 9, 17, 14, 18, 12) comment1.modification_date = datetime(2006, 9, 17, 14, 18, 12) conversation.addComment(comment1) transaction.commit() self.unprivileged_browser.open( self.portalURL + '/@@plone.app.standardtiles.existingcontent/unique?content_uid=' + page_uuid + '&show_comments=True') self.assertIn(u'1', self.unprivileged_browser.contents)
def create_translation(self, *args, **kwargs): """Create translation for an object with uid in the given target_language and return its UID Usage:: Create translation /plone/en/foo ca title=Translated """ # Parse arguments: uid_or_path = args[0] target_language = args[1] # BBB: Support keywords arguments with robotframework < 2.8.3 kwargs.update(dict([arg.split('=', 1) for arg in args[2:]])) # Look up translatable content pc = getToolByName(self, "portal_catalog") uid_results = pc.unrestrictedSearchResults(UID=uid_or_path) path_results = pc.unrestrictedSearchResults( path={'query': uid_or_path.rstrip('/'), 'depth': 0}) obj = (uid_results or path_results)[0]._unrestrictedGetObject() # Translate manager = ITranslationManager(obj) manager.add_translation(target_language) translation = manager.get_translation(target_language) # Update fields data = constructMessageFromSchemata(obj, iterSchemata(obj)) for key, value in kwargs.items(): del data[key] data[key] = Header(value, 'utf-8') del data['language'] initializeObjectFromSchemata(translation, iterSchemata(obj), data) notify(ObjectModifiedEvent(translation)) # Return uid for the translation return IUUID(translation)
def test_handlers(self): logger = IModificationLogger(self.portal) # guarantee that everything is initially empty by pruning days=0 logger.prune(None, days=0) for name in ('modifications', 'moves', 'deletions', 'additions'): facility = getattr(logger, name) self.assertFalse(len(facility)) self.assertFalse(len(facility.keys())) # Add some content we can modify, and throw away content = api.content.create( type='Document', title='Throw away', container=self.portal, ) uid = IUUID(content) # api will have notified ObjectAddedEvent by effect, let's verify: self.assertTrue(len(logger.additions) == 1) self.assertTrue(logger.additions.values()[0].get('uid') == uid) # api create will have also renamed the item, logging a move: self.assertTrue(len(logger.moves.keys()) == 1) # modification logging: self.assertFalse(len(logger.modifications.keys())) notify(ObjectModifiedEvent(content)) self.assertTrue(len(logger.modifications.keys())) self.assertTrue(logger.modifications.values()[0].get('uid') == uid) # move/rename logging: self.assertTrue(len(logger.moves.keys()) == 1) notify( ObjectMovedEvent(content, self.portal, content.getId(), self.portal, 'haha')) self.assertTrue(len(logger.moves.keys()) == 2) # finally removal: self.assertFalse(len(logger.deletions.keys())) notify(ObjectRemovedEvent(content)) self.assertTrue(len(logger.deletions.keys())) self.assertTrue(logger.deletions.values()[0].get('uid') == uid) # clean up after testing: logger.prune(None, days=0)
def test_warning_on_publish_when_page_content_has_reference_to_content_on_other_page( self, browser): target_page = create(Builder('sl content page').titled(u'Target')) target_textblock = create( Builder('sl textblock').within(target_page).titled( u'Target Block')) source_page = create(Builder('sl content page').titled(u'Source')) source_textblock = create( Builder('sl textblock').titled(u'Source Block').having( text=RichTextValue('<a href="resolveuid/%s">link</a>' % IUUID(target_textblock))).within( source_page)) notify(ObjectModifiedEvent(source_textblock)) transaction.commit() browser.login().visit(source_page) Workflow().do_transition('publish') statusmessages.assert_message( 'The referenced object <a href="{}">Target</a> is not yet published.' .format(target_page.absolute_url()))
def test_revising_creates_history_entry(self, browser): self.login(self.meeting_user, browser) deciding_url = self.meeting.model.get_url(view='agenda_items/2/decide') generate_excerpt_url = self.meeting.model.get_url(view='agenda_items/2/generate_excerpt?excerpt_title=bla') return_excerpt_url = self.meeting.model.get_url(view='agenda_items/2/return_excerpt?document={}') reopening_url = self.meeting.model.get_url(view='agenda_items/2/reopen') revising_url = self.meeting.model.get_url(view='agenda_items/2/revise') with self.login(self.committee_responsible, browser): self.schedule_proposal(self.meeting, self.submitted_proposal) browser.open(deciding_url, data={'_authenticator': createToken()}) browser.open(generate_excerpt_url, data={'_authenticator': createToken()}) agenda_item = self.meeting.model.agenda_items[0] excerpt_document = agenda_item.get_excerpt_documents()[0] browser.open(return_excerpt_url.format(IUUID(excerpt_document)), data={'_authenticator': createToken()}) browser.open(reopening_url, data={'_authenticator': createToken()}) browser.open(revising_url, data={'_authenticator': createToken()}) self.assert_proposal_history_records( u'Proposal revised by M\xfcller Fr\xe4nzi (franzi.muller)', self.proposal, browser, with_submitted=True, )
def test_view_requests_bridge(self): context = self.layer['folder'] request = self.layer['request'] referer_url = 'http://nohost/plone/some-folder' request.environ['HTTP_REFERER'] = referer_url feed_path = '@@watcher-feed?uid=%s' % IUUID(context) bridge_path = 'http://bridge/proxy/dashboard/@@add-watcher-portlet' self._expect_request(url=bridge_path, data={ 'path': feed_path }).result(self._create_response(raw='OK')) self.replay() view = getMultiAdapter((context, request), name='watch') view() self.assertEqual(request.response.headers.get('location'), referer_url) messages = IStatusMessage(request).show() self.assertEqual(len(messages), 1) self.assertEqual(messages[0].message, u'A dashboard portlet was created.')
def deleteTranscodedVideos(obj, event): if is_transcode_installed(obj) is False: return if not IUUID(obj, None): return try: registry = getUtility(IRegistry) types = registry[SETTING_TYPES] newTypes = [t.split(':')[0] for t in types] if unicode(obj.portal_type) not in newTypes: return fieldNames = [ str(t.split(':')[1]) for t in types if ('%s:' % unicode(obj.portal_type)) in t ] tt = getUtility(ITranscodeTool) request = getattr(obj, 'REQUEST', None) if 'form.submitted' in request.form: tt.delete(obj, fieldNames) #delete video only after confirmation for delete is clicked except Exception, e: log.error("Could not delete resource %s\n Exception: %s" % (obj.absolute_url(), e))
def setUp(self): self.portal = self.layer['portal'] login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.portal.invokeFactory('Document', id="page", title="page") self.portal.page.reindexObject() self.request = TestRequest(environ={ 'HTTP_ACCEPT_LANGUAGE': 'en', 'REQUEST_METHOD': 'POST' }, form={ 'selection': '["' + IUUID(self.portal.page) + '"]', '_authenticator': createToken(), 'folder': '/' }) self.request.REQUEST_METHOD = 'POST' alsoProvides(self.request, IAttributeAnnotatable) self.userList = 'one,two'
def test_warning_on_retract_when_ftw_simplelayout_block_has_published_references( self, browser): page = create(Builder('sl content page')) other_page = create( Builder('sl content page').titled(u'Other Page').in_state( EXAMPLE_WF_PUBLISHED)) other_page_uuid = IUUID(other_page) textblock = create( Builder('sl textblock').having( text=RichTextValue('<a href="resolveuid/%s">link</a>' % other_page_uuid)).within(page)) notify(ObjectModifiedEvent(textblock)) transaction.commit() browser.login().visit(page) # cannot add text block when published Workflow().do_transition('publish') Workflow().do_transition('retract') statusmessages.assert_message( 'The referenced object <a href="http://nohost/plone' '/other-page">Other Page</a> is still published.')
def dump_object_data(obj, duplicate=False): try: state = api.content.get_state(obj=obj) except WorkflowException: state = 'published' base_url = obj.absolute_url() registry = getUtility(IRegistry) if obj.portal_type in registry.get('plone.types_use_view_action_in_listings', []): url = base_url + '/view' else: url = base_url return json.dumps({ 'success': True, 'base_url': base_url, 'url': url, 'edit_url': base_url + '/@@edit', 'portal_type': obj.portal_type, 'uid': IUUID(obj), 'workflow_state': state, 'title': obj.Title(), 'valid': True, 'duplicate': duplicate })
def create(self, data): fti = getUtility(IDexterityFTI, name=self.portal_type) context = aq_inner(self.context) submission = createObject(fti.factory).__of__(context) IMutableUUID(submission).set(uuid4()) submission.title = IUUID(submission) # noqa: P001 # extract attachments to be saved into separate objects submission._v_attachments = tuple(extract_attachments(data, context)) # save form data (bypass data manager for speed # and to avoid needing to reload the form schema) save_form(self, data, submission, default_values=True, force=True) # save schema to allow submission to adapt its schema interface submission.schema = remove_attachments(self.context.schema) submission.schema_digest = hashlib.md5(submission.schema).hexdigest() # we cannot acquire from parent FlowFolder, because behaviors # are resolved without acquisition chain submission.submission_behaviors = self.submission_behaviors return aq_base(submission)
def test_existing_content_tile(self): """The existing content tile takes the uuid of a content object in the site and displays the result of calling its default view's content-core macro """ page_id = self.portal.invokeFactory('Document', 'an-another-page', title=u'An another page', description=u'A description', text=u'Hello World!') self.portal[page_id].text = RichTextValue(u'Hello World!') page_uuid = IUUID(self.portal[page_id]) transaction.commit() self.unprivileged_browser.open( self.portalURL + '/@@plone.app.standardtiles.existingcontent/unique?content_uid=' + page_uuid + '&show_text=True') self.assertIn(u'Hello World!', self.unprivileged_browser.contents)
def _uidFor(self, obj): # We should really check for the interface but I have an idea # about simple annotated objects I want to play out if not isinstance(obj, basestring): uobject = aq_base(obj) if not self.isReferenceable(uobject): raise ReferenceException, "%r not referenceable" % uobject uuid = IUUID(uobject, None) if uuid is None: uuid = self._getUUIDFor(uobject) else: uuid = obj obj = None #and we look up the object uid_catalog = getToolByName(self, UID_CATALOG) brains = uid_catalog(dict(UID=uuid)) for brain in brains: res = brain.getObject() if res is not None: obj = res return uuid, obj
def _set_subjects(self, value): value = tuple([safe_unicode(x) for x in value]) self.context.subject = value graph = getUtility(INetworkTool) user = api.user.get_current() try: uuid = IUUID(self.context) except TypeError: # new factory document, not registered yet # we'll come back to this with an event listener return if value: graph.tag('content', uuid, user.id, *value) # else value==() -> cleaned up below try: current_tags = graph.get_tags('content', uuid, user.id) except KeyError: # no tags set yet return else: stale = [tag for tag in current_tags if tag not in value] if stale: graph.untag('content', uuid, user.id, *stale)
def manage_afterClone(self, item): # Get a new UID (effectivly dropping reference) # (Called when the object is cloned.) uc = getToolByName(self, config.UID_CATALOG) isCopy = getattr(item, '_v_is_cp', None) if isCopy: # if isCopy is True, manage_afterAdd should have assigned a # UID already. Don't mess with UID anymore. return # TODO Should we ever get here after the isCopy flag addition?? # If the object has no UID or the UID already exists, then # we should get a new one uuid = IUUID(self, None) if (uuid is None or len(uc(UID=uuid))): setattr(self, config.UUID_ATTR, None) self._register() self._updateCatalog(self)
def get_related_documents(self): """ Return the related documents from a task We get objects but we need brains. So we lookup them """ brains = [] for item in self.config.context.relatedItems: obj = item.to_object if obj.portal_type in [ 'opengever.document.document', 'ftw.mail.mail']: brain = uuidToCatalogBrain(IUUID(obj)) if not brain: # the document is trashed # or not enough permission are preset to get the brain continue # We need a BrainWrapper object to declare the item as # a related document for the tabbedview helper. brains.append(BrainWrapper(brain)) return brains
def insert(self, content, user, extra): record_storage, keys = self.prep_insert() key = self.generate_key() uid = IUUID(content) user = self._user(user) record = { 'uid': uid, 'path': '/'.join(content.getPhysicalPath()), 'user': user, 'when': datetime.now() } if extra: record['extra'] = dict(extra) record_storage[key] = record # TODO: need to consider whether there are potential # conflict resolution issues with using a # PersistentList without subclassing and # using _p_resolveConflict on the insertion; # fear is that some expensive transaction takes # a long time to retry whole request over # simple race condition on the insertion order # in the PersistentList used here? keys.insert(0, key)
def create_proposal_document(self, source_blob=None, **kwargs): """Creates a proposal document within this proposal or submitted proposal. Only one proposal document can be created. """ if self.get_proposal_document(): raise ValueError('There is already a proposal document.') if source_blob: kwargs.setdefault('filename', source_blob.filename) kwargs.setdefault('data', source_blob.open().read()) kwargs.setdefault('content_type', source_blob.contentType) kwargs['context'] = self kwargs.setdefault('preserved_as_paper', False) kwargs.setdefault('title', safe_unicode(self.Title())) with elevated_privileges(): obj = CreateDocumentCommand(**kwargs).execute() self._proposal_document_uuid = IUUID(obj) return obj
def populate_with_object(self, obj): try: image = obj.restrictedTraverse('chart_1.png') except: image = None if not image: return self.set_limit() uuid = IUUID(obj, None) data_mgr = ITileDataManager(self) old_data = data_mgr.get() if data_mgr.get()['uuids']: uuids = data_mgr.get()['uuids'] if type(uuids) != list: uuids = [uuid] elif uuid not in uuids: uuids.append(uuid) old_data['uuids'] = uuids[:self.limit] else: old_data['uuids'] = [uuid] data_mgr.set(old_data)
def addContentToContainer(container, object, checkConstraints=True): """Add an object to a container. The portal_type must already be set correctly. If checkConstraints is False no check for addable content types is done. The new object, wrapped in its new acquisition context, is returned. """ if not hasattr(aq_base(object), "portal_type"): raise ValueError("object must have its portal_type set") container = aq_inner(container) if checkConstraints: container_fti = container.getTypeInfo() fti = getUtility(IDexterityFTI, name=object.portal_type) if not fti.isConstructionAllowed(container): raise Unauthorized("Cannot create %s" % object.portal_type) if container_fti is not None and not container_fti.allowType( object.portal_type): raise ValueError("Disallowed subobject type: %s" % object.portal_type) name = INameChooser(container).chooseName(None, object) object.id = name newName = container._setObject(name, object) try: return container._getOb(newName) except AttributeError: if HAS_UUID: # work around edge case where a content rule may have moved the item uuid = IUUID(object) return uuidToObject(uuid) else: # no way to know where it is raise
def update_apply(self, *args, **kwargs): req = self.request do_bind = bool(req.get('bind-stylebook', False)) _get = lambda name: self.context.get(name, None) stylebook = _get(req.get('selected-stylebook')) if stylebook is None: self.status.addStatusMessage('Unknonwn style book', type='info') return targets = [_get(name) for name in req.get('selected-charts', [])] if not targets: self.status.addStatusMessage( 'No target charts selected to apply stylebook to.', type='info' ) return for target in targets: clone_chart_styles(stylebook, target) # copy styles now if do_bind: bookuid = IUUID(stylebook, None) target.stylebook = bookuid _listcharts = lambda s: ', '.join(['"%s"' % o.Title() for o in s]) msg = 'Copied styles from' if not do_bind else 'Bound' self.status.addStatusMessage( '%s stylebook "%s" to %s charts: %s' % ( msg, stylebook.Title(), len(targets), _listcharts(targets), ), type='info', ) if do_bind: self.status.addStatusMessage( 'IMPORTANT: subsequent changes to style book and line ' 'styles will propogate to the charts listed as bound ' 'to a style book. To remove a binding, visit the Edit ' 'tab of a chart that has been bound to a style book this ' 'way.', type='info', )
def test_breaking_header_links(self): page = self._create_page(_id='test1', text=''' <h1>Foobar 1</h1> <p>foobar 1</p> <h1>Foobar 2</h1> <p>foobar 2</p> <h2>Foobar 3</h2> <p>foobar 3</p> <h1>Foobar 4</h1> <p>foobar 4</p> ''') page2 = self._create_page(_id='test2', text=''' <div data-type="snippet_tag" data-snippet-id="{}" data-header="Foobar 2"></div>'''.format(IUUID(page))) links = getOutgoingLinks(page2) # should add link self.assertEqual([l for l in links][0].to_object.getId(), 'test1') links = getIncomingLinks(page) # should add link self.assertEqual([l for l in links][0].from_object.getId(), 'test2') # now, remove the header... page.text = RichTextValue(''' <h1>Foobar 1</h1> <p>foobar 1</p> <h2>Foobar 3</h2> <p>foobar 3</p> <h1>Foobar 4</h1> <p>foobar 4</p> ''', 'text/html', 'text/html') status_annotations = IAnnotations(self.request) self.assertFalse(bool(status_annotations.get(STATUSMESSAGEKEY))) checkSnippetReferences(page) self.assertTrue(bool(status_annotations.get(STATUSMESSAGEKEY)))
def get_options(self): site = get_top_site_from_url(self.context, self.request) base_url = site.absolute_url() base_vocabulary = '%s/@@getVocabulary?name=' % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() columns = self.get_columns() options = { 'vocabularyUrl': '%splone.app.vocabularies.Catalog' % ( base_vocabulary), 'urlStructure': { 'base': base_url, 'appended': '/folder_contents' }, 'moveUrl': '%s{path}/fc-itemOrder' % base_url, 'indexOptionsUrl': '%s/@@qsOptions' % base_url, 'contextInfoUrl': '%s{path}/@@fc-contextInfo' % base_url, 'setDefaultPageUrl': '%s{path}/@@fc-setDefaultPage' % base_url, 'defaultPageTypes': self.default_page_types(), 'searchParam': 'Title', 'availableColumns': columns, 'attributes': ['Title', 'path', 'getURL', 'getIcon', 'getMimeIcon', 'portal_type'] + list(columns.keys()), # noqa 'buttons': self.get_actions(), 'rearrange': { 'properties': self.get_indexes(), 'url': '%s{path}/@@fc-rearrange' % base_url }, 'basePath': '/' + '/'.join(context_path[len(site_path):]), 'upload': { 'relativePath': 'fileUpload', 'baseUrl': base_url, 'initialFolder': IUUID(self.context, None), 'useTus': TUS_ENABLED }, 'thumb_scale': self.get_thumb_scale(), } return options
def fix_links_in_static_portlet(context): """Fix links in "atalhos" portlet. To make this independent of portal site name we need to fix the links adding the portal URL. This is called after import of portlets.xml. """ marker_file = '{0}.txt'.format(PROJECTNAME) if context.readDataFile(marker_file) is None: return from plone.portlets.interfaces import IPortletAssignmentMapping from plone.portlets.interfaces import IPortletManager from zope.component import getMultiAdapter from zope.component import getUtility portal = api.portal.get() obj = portal['intranet']['pagina-inicial-da-intranet'] manager = getUtility(IPortletManager, name='plone.leftcolumn', context=obj) mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) assert 'atalhos' in mapping portlet = mapping['atalhos'] intranet_url = portal.absolute_url() + '/intranet/' portlet.text = portlet.text.replace('intranet/', intranet_url) logger.debug(u'Links substituidos no portlet de atalhos') manager = getUtility(IPortletManager, name='plone.rightcolumn', context=obj) mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) assert 'voting-portlet' in mapping portlet = mapping['voting-portlet'] intranet = portal['intranet'] poll = intranet['ponto-de-encontro']['enquete']['gostou-da-nova-intranet'] portlet.poll = IUUID(poll) logger.debug(u'Portlet de enquete atualizado')
def populate_with_object(self, obj): super(CarouselTile, self).populate_with_object(obj) # check permission try: scale = obj.restrictedTraverse('@@images').scale('image') except: scale = None if not scale: return self.set_limit() uuid = IUUID(obj, None) data_mgr = ITileDataManager(self) old_data = data_mgr.get() if data_mgr.get()['uuids']: uuids = data_mgr.get()['uuids'] if type(uuids) != list: uuids = [uuid] elif uuid not in uuids: uuids.append(uuid) old_data['uuids'] = uuids[:self.limit] else: old_data['uuids'] = [uuid] data_mgr.set(old_data)
def test_delete_tile_persistent_data(self): permissions = getMultiAdapter( (self.tile.context, self.request, self.tile), ITilesPermissions) permissions.set_allowed_edit('masters_of_the_universe') annotations = IAnnotations(self.tile.context) self.assertIn('plone.tiles.permission.test', annotations) uuid = IUUID(self.pfg, None) configuration = getMultiAdapter( (self.tile.context, self.request, self.tile), ITilesConfigurationScreen) configuration.set_configuration({ 'uuid': uuid, 'title': self.pfg.Title(), 'description': self.pfg.Description(), }) self.assertIn('plone.tiles.configuration.test', annotations) # Call the delete method self.tile.delete() # Now we should not see the stored data anymore self.assertNotIn('plone.tiles.permission.test', annotations) self.assertNotIn('plone.tiles.configuration.test', annotations)
def getVCal(self): """get vCal data """ context = self.context out = StringIO() map = { 'dtstamp': rfc2445dt(DateTime()), 'created': rfc2445dt(DateTime(context.CreationDate())), 'uid': IUUID(context), 'modified': rfc2445dt(DateTime(context.ModificationDate())), 'summary': vformat(context.Title()), 'startdate': rfc2445dt(context.start_date), 'enddate': rfc2445dt(context.end_date), } out.write(VCS_EVENT_START % map) description = context.Description() if description: out.write(foldLine('DESCRIPTION:%s\n' % vformat(description))) location = context.location if location: location = location.encode('utf-8') out.write('LOCATION:%s\n' % vformat(location)) out.write(VCS_EVENT_END) return out.getvalue()
def test_provides(self): import uuid from plone.uuid.interfaces import IUUIDObject, IUUID self.assertTrue(IUUIDObject.providedBy(uuid.uuid4())) self.assertFalse(IUUID.providedBy(uuid.uuid4()))