def addProjectNavPortlet(obj, event): """Event handler triggered when adding a project folder. This will add the project navigator portlet automatically. """ parent = aq_parent(obj) if IProjectFolder.providedBy(parent): return # A portlet manager is a plugin to a column column = getUtility(IPortletManager, name=u"plone.leftcolumn") # We multi-adapt the object and the column to an assignment mapping, # which acts like a dict where we can put portlet assignments manager = getMultiAdapter(( obj, column, ), IPortletAssignmentMapping) # We then create the assignment and put it in the assignment manager, # using the default name-chooser to pick a suitable name for us. assignment = navigation.Assignment(name=u"项目导航", root_uid=obj.UID(), topLevel=0) chooser = INameChooser(manager) manager[chooser.chooseName(None, assignment)] = assignment
def addContentToContainer(container, object, checkConstraints=True): """Copy of plone.dexterity.util.addContentToContainer. Modified to check the existing Id on the object before paving over it. """ 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 ) chooser = INameChooser(container) if hasattr(object, 'id') and chooser.checkName(object.id, object): name = object.id else: name = INameChooser(container).chooseName(None, object) object.id = name newName = container._setObject(name, object) return container._getOb(newName)
def _create_project(cell, context): STATUS = {'17': 'active', '18': 'inactive', '19': 'archive'} chooser = INameChooser(context) project_id = chooser.chooseName(cell[2].decode('latin-1'), context) # Create project context.invokeFactory("Project", project_id) project = context[project_id] project.setExcludeFromNav(True) # Set project attributes project.setCode(cell[2].decode('latin-1')) project.setName_fr(cell[16].decode('latin-1')) project.setName_en(cell[4].decode('latin-1')) project.setName_nl(cell[3].decode('latin-1')) project.setContent_fr(cell[13].decode('latin-1')) project.setContent_en(cell[20].decode('latin-1')) project.setContent_nl(cell[7].decode('latin-1')) project.setComments(cell[11].decode('latin-1')) project.setUrl(cell[6].decode('latin-1')) project.setOrganisationtype(cell[5].decode('latin-1')) project.setStatus(STATUS.get(cell[18].decode('latin-1'), '')) project.setRelationtype(cell[19].decode('latin-1')) project.setStart(_get_datetime(cell[10].decode('latin-1'))) project.setEnd(_get_datetime(cell[15].decode('latin-1'))) return project
def _createObj(context, event): parent = context.aq_parent column = getUtility(IPortletManager, name=u'plone.leftcolumn', context=context) manager = getMultiAdapter((context, column,), IPortletAssignmentMapping) assignment = burgermenuportlet.Assignment() chooser = INameChooser(manager) assignment.path = '/'.join(context.getPhysicalPath()) manager[chooser.chooseName(None, assignment)] = assignment id = context.getId() object_Ids = [] catalog = getToolByName(context, 'portal_catalog') brains = catalog.unrestrictedSearchResults(object_provides = IPilgrimageApp.__identifier__) for brain in brains: object_Ids.append(brain.id) last_name = str(idnormalizer.normalize(context.title)) temp_new_id = last_name new_id = temp_new_id.replace("-","") test = '' if new_id in object_Ids: test = filter(lambda name: new_id in name, object_Ids) if '-' not in (max(test)): new_id = new_id + '-1' if '-' in (max(test)): new_id = new_id +'-' +str(int(max(test).split('-')[-1])+1) parent.manage_renameObject(id, new_id ) new_title = last_name context.setTitle(context.title) context.reindexObject() return
def handleSave(self, action): data, errors = self.extractData() if errors: return False types = api.portal.get_tool('portal_types') type_info = types.getTypeInfo('eea.meeting.email') name_chooser = INameChooser(self.context) content_id = name_chooser.chooseName(data['subject'], self.context) obj = type_info._constructInstance(self.context, content_id) obj.title = data['subject'] obj.sender = data['sender'] obj.receiver = data['receiver'] obj.cc = data['cc'] obj.subject = data['subject'] obj.body = data['body'] obj.reindexObject() notify(SendEmailAddEvent(self.context, data)) msg = _(u"Email successfully sent") IStatusMessage(self.request).addStatusMessage(msg, type='info') self.request.response.redirect( self.context.getParentNode().absolute_url())
def moveTo(self, target, new_name=None): """Move this object to the `target` given. Returns the new name within the `target` """ obj = self.context container = obj.__parent__ orig_name = obj.__name__ if new_name is None: new_name = orig_name checkObject(target, new_name, obj) if target is container and new_name == orig_name: # Nothing to do return chooser = INameChooser(target) new_name = chooser.chooseName(new_name, obj) if target is container and new_name == orig_name: # obstinate namechooser return target[new_name] = obj del container[orig_name] return new_name
def copy(source=None, target=None, id=None, safe_id=False): """Copy the object to the target container. :param source: [required] Object that we want to copy. :type source: Content object :param target: Target container to which the source object will be moved. If no target is specified, the source object's container will be used as a target. :type target: Folderish content object :param id: Id of the copied object on the target location. If no id is provided, the copied object will have the same id as the source object - however, if the new object's id conflicts with another object in the target container, a suffix will be added to the new object's id. :type id: string :returns: Content object that was created in the target location :param safe_id: When True, the given id will be enforced. If the id is conflicting with another object in the target container, raise a InvalidParameterError. When True, choose a new, non-conflicting id. :type safe_id: boolean :raises: KeyError, ValueError :Example: :ref:`content_copy_example` """ source_id = source.getId() target.manage_pasteObjects(source.manage_copyObjects(source_id)) if id: if not safe_id: new_id = id else: chooser = INameChooser(target) new_id = chooser.chooseName(id, source) target.manage_renameObject(source_id, new_id)
def rename(obj=None, new_id=None, safe_id=False): """Rename the object. :param obj: [required] Object that we want to rename. :type obj: Content object :param new_id: New id of the object. :type new_id: string :param safe_id: When False, the given id will be enforced. If the id is conflicting with another object in the container, raise a InvalidParameterError. When True, choose a new, non-conflicting id. :type safe_id: boolean :returns: Content object that was renamed :Example: :ref:`content_rename_example` """ obj_id = obj.getId() if safe_id: try: chooser = INameChooser(obj) except TypeError: chooser = INameChooser(obj.aq_parent) new_id = chooser.chooseName(new_id, obj) obj.aq_parent.manage_renameObject(obj_id, new_id) return obj.aq_parent[new_id]
def addContentToContainer(container, object, checkConstraints=True): """Copy of plone.dexterity.util.addContentToContainer. Modified to check the existing Id on the object before paving over it. """ 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 {0}'.format(object.portal_type)) if container_fti is not None and \ not container_fti.allowType(object.portal_type): raise ValueError('Disallowed subobject type: {0}'.format( object.portal_type)) chooser = INameChooser(container) if hasattr(object, 'id') and chooser.checkName(object.id, object): name = object.id else: name = INameChooser(container).chooseName(None, object) object.id = name newName = container._setObject(name, object) return container._getOb(newName)
def __call__(self, filename, title, description, content_type, data, portal_type): context = aq_inner(self.context) error = '' result = {} result['success'] = None newid = get_id_from_filename(filename, context) chooser = INameChooser(context) newid = chooser.chooseName(newid, context) # consolidation because it's different upon Plone versions if not title: # try to split filenames because we don't want # big titles without spaces title = filename.rsplit('.', 1)[0]\ .replace('_', ' ')\ .replace('-', ' ') if newid in context: # only here for flashupload method since a check_id is done # in standard uploader - see also XXX in quick_upload.py raise NameError, 'Object id %s already exists' % newid else: upload_lock.acquire() try: transaction.begin() try: from zope.publisher.browser import TestRequest request = TestRequest() dataobj = FileObj(data) dataobj.filename = filename request.form['doc'] = dataobj request.form['ajax'] = '1' from fhnw.office2plone.browser.docx_importer import DocxImporter docximport = DocxImporter(self.context, request) docximport.docx_import() except ImportError: error = '' except Unauthorized: error = u'serverErrorNoPermission' except ConflictError: # rare with xhr upload / happens sometimes with flashupload error = u'serverErrorZODBConflict' except ValueError: error = u'serverErrorDisallowedType' except Exception, e: error = u'serverError' logger.exception(e) if error: if error == u'serverError': logger.info( "An error happens with setId from filename, " "the file has been created with a bad id, " "can't find %s", newid) else: pass #@TODO : rollback if there has been an error transaction.commit() finally:
def new_user(principal, event): """Initialise the dashboard for a new user """ #import pdb; pdb.set_trace() defaults = IDefaultPersonalPortlet(principal, None) if defaults is None: return userid = principal.getId() portlets = defaults() for name in ('plone.rightcolumn', ): assignments = portlets.get(name) if assignments: column = queryUtility(IPortletManager, name=name) if column is not None: # Add the default portlets only, if this is our manager. # We must check this to avoid adding the default portlets # when the product is not installed into the portal # (but the event triggers even in this case) if IPersonalPortletManager in providedBy(column): category = column.get(USER_CATEGORY, None) if category is not None: manager = category.get(userid, None) if manager is None: manager = category[userid] = UserPortletAssignmentMapping(manager=name, category=USER_CATEGORY, name=userid) chooser = INameChooser(manager) for assignment in assignments: manager[chooser.chooseName(None, assignment)] = assignment
def __call__(self): # http://localhost:8080/Plone/ca/eetac/organ/session/changeTitle?pk=OLD_ID&name=&value=NEW_ID try: origin_path = '/'.join( self.context.getPhysicalPath()) + '/' + self.request.form['pk'] newvalue = self.request.form['value'] except: return None try: entry = api.content.find(path=origin_path, depth=0)[0] old_id = entry.id entryobj = entry.getObject() container = entryobj.aq_parent chooser = INameChooser(container) new_id = chooser.chooseName(newvalue, entryobj) change_str = entryobj.absolute_url( ) + ' - [' + entry.Title + ' → ' + newvalue + ']' with api.env.adopt_roles(['OG1-Secretari']): container.manage_renameObject(old_id, new_id) newObject = api.content.find(id=new_id, path='/'.join( origin_path.split('/')[:-1]))[0] newobj = newObject.getObject() newobj.title = newvalue newobj.reindexObject() # transaction ok, then write log addEntryLog(self.context, None, _(u"Changed Title"), change_str) # This line is only to bypass the CSRF WARNING # WARNING plone.protect error parsing dom, failure to add csrf token to response for url ... return "Changed Title" except: pass
def handleApply(self, action): data, errors = self.extractData() if errors: return title = data['title'] # Generate a name based on the title.. util = queryUtility(IIDNormalizer) id = util.normalize(title) # Context may not be a container, get one. context_state = getMultiAdapter((self.context, self.request), name="plone_context_state") container = context_state.folder() # Make sure our chosen id is unique, iterate until we get one that is. chooser = INameChooser(container) id = chooser._findUniqueName(id, None) # create the object type_name = data['type_name'] container.invokeFactory(type_name, id=id, title=title) if type_name in [u'Folder']: self.request.response.redirect("%s/@@cmsui-structure" % container[id].absolute_url()) else: self.request.response.redirect("%s/edit" % container[id].absolute_url())
def new_user(principal, event): """Initialise the dashboard for a new user """ defaults = IDefaultDashboard(principal, None) if defaults is None: return userid = principal.getId() portlets = defaults() for name in ('plone.dashboard1', 'plone.dashboard2', 'plone.dashboard3', 'plone.dashboard4'): assignments = portlets.get(name) if assignments: column = queryUtility(IPortletManager, name=name) if column is not None: category = column.get(USER_CATEGORY, None) if category is not None: manager = category.get(userid, None) if manager is None: manager = category[ userid] = UserPortletAssignmentMapping( manager=name, category=USER_CATEGORY, name=userid) chooser = INameChooser(manager) for assignment in assignments: manager[chooser.chooseName(None, assignment)] = assignment
def __call__(self, name, content_type, data): ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(name.lower(), '', '') or 'File' # XXX: quick fix for german umlauts name = name.decode("utf8") normalizer = getUtility(IFileNameNormalizer) chooser = INameChooser(self.context) # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() # this should fix #8 newid = chooser.chooseName(normalizer.normalize(name), self.context.aq_parent) try: transaction.begin() obj = ploneutils._createObjectByType(type_, self.context, newid) mutator = obj.getPrimaryField().getMutator(obj) mutator(data, content_type=content_type) obj.setTitle(name) obj.reindexObject() notify(ObjectInitializedEvent(obj)) notify(ObjectModifiedEvent(obj)) transaction.commit() finally: upload_lock.release() return obj
def addUtility(root_folder, utility_type, utility_factory, asObject=_marker, **kw): """ Add a Utility to the root folder's site manager. The utility is added to the default package and activated. """ if asObject is not _marker: warnings.warn("asObject argument is deprecated and will be " "removed in Zope 3.6", DeprecationWarning, 2) package = getSiteManagerDefault(root_folder) chooser = INameChooser(package) utility = utility_factory() name = chooser.chooseName(utility_type, utility) package[name] = utility # the utility might have been location-proxied; we need the name # information (__name__) so let's get it back again from the # container utility = package[name] # Set additional attributes on the utility for k, v in kw.iteritems(): setattr(utility, k, v) return utility
def new_user(principal, event): """Initialise the dashboard for a new user """ #import pdb; pdb.set_trace() defaults = IDefaultPersonalPortlet(principal, None) if defaults is None: return userid = principal.getId() portlets = defaults() for name in ('plone.rightcolumn', ): assignments = portlets.get(name) if assignments: column = queryUtility(IPortletManager, name=name) if column is not None: # Add the default portlets only, if this is our manager. # We must check this to avoid adding the default portlets # when the product is not installed into the portal # (but the event triggers even in this case) if IPersonalPortletManager in providedBy(column): category = column.get(USER_CATEGORY, None) if category is not None: manager = category.get(userid, None) if manager is None: manager = category[ userid] = UserPortletAssignmentMapping( manager=name, category=USER_CATEGORY, name=userid) chooser = INameChooser(manager) for assignment in assignments: manager[chooser.chooseName( None, assignment)] = assignment
def handleSave(self, action): data, errors = self.extractData() if errors: return False types = api.portal.get_tool('portal_types') type_info = types.getTypeInfo('eea.meeting.email') name_chooser = INameChooser(self.context) content_id = name_chooser.chooseName(data['subject'], self.context) obj = type_info._constructInstance(self.context, content_id) obj.title = data['subject'] obj.sender = data['sender'] obj.receiver = "\r\n".join(data['receiver']) data['receiver'] = obj.receiver obj.cc = data['cc'] obj.subject = data['subject'] obj.body = data['body'] obj.reindexObject() notify(SendEmailAddEvent(self.context, data)) msg = _(u"Email successfully sent") IStatusMessage(self.request).addStatusMessage(msg, type='info') self.request.response.redirect(self.context.getParentNode().absolute_url())
def add(self, schoolyear): """Add `schoolyear` to the container.""" chooser = INameChooser(self.context) name = chooser.chooseName(schoolyear.title, schoolyear) self.context[name] = schoolyear self.importData(schoolyear) return schoolyear
def __call__(self, name, content_type, data): ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(name.lower(), '', '') or 'File' # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() name = safe_unicode(name) chooser = INameChooser(self.context) newid = chooser.chooseName(name, self.context.aq_parent) try: transaction.begin() obj = ploneutils._createObjectByType(type_, self.context, newid) mutator = obj.getPrimaryField().getMutator(obj) mutator(data, content_type=content_type, filename=name) obj.setTitle(name) if hasattr(obj, 'setFilename'): # if chunk uploaded, needs override obj.setFilename(name) obj.reindexObject() notify(ObjectInitializedEvent(obj)) notify(ObjectModifiedEvent(obj)) transaction.commit() finally: upload_lock.release() return obj
def _create_file(self, item, files, title, description, rights): namechooser = INameChooser(self.context) content_type = item.headers.get('Content-Type') filename = safe_unicode(item.filename) data = item.read() id_name = '' title = title and title[0] or filename id_name = namechooser.chooseName(title, self.context) if content_type in IMAGE_MIMETYPES: portal_type = 'Image' wrapped_data = NamedBlobImage(data=data, filename=filename) else: portal_type = 'File' wrapped_data = NamedBlobFile(data=data, filename=filename) self.context.invokeFactory(portal_type, id=id_name, title=title, description=description[0], rights=rights[0]) newfile = self.context[id_name] if portal_type == 'File': if IATFile.providedBy(newfile): newfile.setFile(data, filename=filename) else: newfile.file = wrapped_data elif portal_type == 'Image': if IATImage.providedBy(newfile): newfile.setImage(data, filename=filename) else: newfile.image = wrapped_data newfile.reindexObject() notify(ObjectModifiedEvent(newfile)) return newfile
def drop(self, mail): """ drop a mail into this mail box. The mail is a string with the complete email content """ # code unicode to utf-8 if isinstance(mail,unicode): mail = mail.encode( 'utf-8' ) type = 'Email' format = 'text/plain' content_type='text/plain' #generate title mailobj = email.message_from_string(mail) # Subject for key in "Subject subject Betreff betreff".split(): subject = mailobj.get(key) if subject: subject = self.decodeheader(subject) break id = subject or DEFAULT_ID title = id # generate id normalizer = component.getUtility(IIDNormalizer) chooser = INameChooser(self.context) id = chooser.chooseName(normalizer.normalize(id), aq_base(self.context)) self.context.invokeFactory(type ,id=id , title=title, format=format, \ content_type=content_type, file=mail) getattr(self.context, id, None).setContentType(content_type) getattr(self.context, id, None).processForm() notify(MailDroppedEvent(getattr(self.context, id, None), self.context))
def createDXItem(self, fields, request, context): """Create dexterity item and call converters as necessary """ mappings = {} for m in self.mappings: src_field, v = m.split(' ') if ':' not in v: v += ':' target_field, field_type = v.split(':') mappings[target_field] = self.convert_field( field_type, fields[src_field], ) location = api.content.get(path=self.location.encode( 'ascii', 'ignore'), ) if 'id' in mappings and mappings['id']: title_or_id = mappings['id'] else: title_or_id = mappings['title'] chooser = INameChooser(location) item_id = chooser.chooseName(title_or_id, location) api.content.create( container=location, type=self.content_type, id=item_id, **mappings # noqa C815 )
def createNewDaviz(self): """ Create new visualization """ davizsettings = queryUtility(IDavizSettings) strFolder = davizsettings.settings.get("daviz.defaultfolder", "") if strFolder != "": portal = getSite() folder = portal.restrictedTraverse(strFolder) else: folder = self.context.aq_parent found = False while True: try: allowedContentTypes = folder.allowedContentTypes() except AttributeError: break for allowedContentType in allowedContentTypes: if allowedContentType.id == "DavizVisualization": found = True if found: break folder = folder.aq_parent if not found: return chooser = INameChooser(folder) newId = chooser.chooseName(self.context.title, folder) if newId in folder.objectIds(): raise NameError, 'Object id %s already exists' % newId else: folder.invokeFactory("DavizVisualization", newId) newObj = folder[newId] newObj.title = self.context.title newObj.setRelatedItems([self.context]) self.request.response.redirect(newObj.absolute_url()+"/daviz-edit.html")
def new_user(principal, event): """Initialise the dashboard for a new user """ defaults = IDefaultDashboard(principal, None) if defaults is None: return userid = principal.getId() portlets = defaults() for name in ('plone.dashboard1', 'plone.dashboard2', 'plone.dashboard3', 'plone.dashboard4'): assignments = portlets.get(name) if assignments: column = queryUtility(IPortletManager, name=name) if column is not None: category = column.get(USER_CATEGORY, None) if category is not None: manager = category.get(userid, None) if manager is None: manager = category[userid] = UserPortletAssignmentMapping(manager=name, category=USER_CATEGORY, name=userid) chooser = INameChooser(manager) for assignment in assignments: manager[chooser.chooseName(None, assignment)] = assignment
def handleApply(self, action): data, errors = self.extractData() if errors: return # Context may not be a container, get one. context_state = getMultiAdapter((self.context, self.request), name="plone_context_state") container = context_state.folder() title = data['file'].filename # Generate a name based on the title.. util = queryUtility(IIDNormalizer) id = util.normalize(title) # Make sure our chosen id is unique, iterate until we get one that is. chooser = INameChooser(container) id = chooser._findUniqueName(id, None) # Determine the Content Type ct_reg = getToolByName(self.context, 'content_type_registry') typeName = ct_reg.findTypeName(data['file'].filename, data['file'].contentType, data['file'].data) # Really, we want Image if it's an image, and File for everything else... typeName = 'Image' if typeName == 'Image' else 'File' # create the object container.invokeFactory(typeName, id=id, title=title, file=data['file'].data) # Redirect to the view page. self.request.response.redirect("%s/view" % container[id].absolute_url())
def setup_department_portlets(obj, event): # equaldepartments-portlet manager = getUtility(IPortletManager, name=u"plone.leftcolumn") mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) has_equaldepartments = False for value in mapping.values(): if value.__name__ == "label_equaldepartmentsportlet": has_equaldepartments = True if not has_equaldepartments: assignment_equaldepartments = equaldepartmentsportlet.EqualDepartmentsPortletAssignment( department_uid=obj.UID() ) chooser = INameChooser(mapping) equaldepartments_name = chooser.chooseName(None, assignment_equaldepartments) mapping[equaldepartments_name] = assignment_equaldepartments # departmentportlet manager = getUtility(IPortletManager, name=u"plone.rightcolumn") mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) has_department = False for value in mapping.values(): if value.__name__ == "label_departmentportlet": has_department = True if not has_department: assignment_department = departmentportlet.DepartmentPortletAssignment(department_uid=obj.UID()) chooser = INameChooser(mapping) department_name = chooser.chooseName(None, assignment_department) mapping[department_name] = assignment_department
def _createObject(context, event): column = getUtility(IPortletManager, name=u'plone.leftcolumn', context=context) manager = getMultiAdapter((context, column,), IPortletAssignmentMapping) assignment = mydocs_portlet.Assignment() chooser = INameChooser(manager) assignment.button_label = 'My Documents' manager[chooser.chooseName(None, assignment)] = assignment
def choose_name(self): if self._id is not None: return self._id title = self.arguments.get('title', self.portal_type) chooser = INameChooser(self.container) return chooser.chooseName(title, self.container)
def add(self, content): """See zope.browser.interfaces.IAdding """ container = self.context name = self.contentName chooser = INameChooser(container) # check precondition checkObject(container, name, content) if IContainerNamesContainer.providedBy(container): # The container picks its own names. # We need to ask it to pick one. name = chooser.chooseName(self.contentName or '', content) else: request = self.request name = request.get('add_input_name', name) if name is None: name = chooser.chooseName(self.contentName or '', content) elif name == '': name = chooser.chooseName('', content) else: # Invoke the name chooser even when we have a # name. It'll do useful things with it like converting # the incoming unicode to an ASCII string. name = chooser.chooseName(name, content) content.id = name container._setObject(name, content) self.contentName = name # Set the added object Name return container._getOb(name)
def add(container, obj, rename=True): """Add an object to a container.""" id_ = getattr(aq_base(obj), "id", None) # Archetypes objects are already created in a container thus we just fire # the notification events and rename the object if necessary. if base_hasattr(obj, "_at_rename_after_creation"): notify(ObjectAddedEvent(obj, container, id_)) notifyContainerModified(container) if obj._at_rename_after_creation and rename: obj._renameAfterCreation(check_auto_id=True) return obj else: if rename: chooser = INameChooser(container) # INameFromTitle adaptable objects should not get a name # suggestion. NameChooser would prefer the given name instead of # the one provided by the INameFromTitle adapter. suggestion = None name_from_title = INameFromTitle(obj, None) if name_from_title is None: suggestion = obj.Title() id_ = chooser.chooseName(suggestion, obj) obj.id = id_ new_id = container._setObject(id_, obj) # _setObject triggers ObjectAddedEvent which can end up triggering a # content rule to move the item to a different container. In this case # look up the object by UUID. try: return container._getOb(new_id) except AttributeError: uuid = IUUID(obj) return uuidToObject(uuid)
def convert_legacy_portlets(context): """Convert legacy portlets (left_slots, right_slots) in the given context to new-style portlets. """ portletsMapping = {'portlet_login': login.Assignment(), 'portlet_news': news.Assignment(count=5), 'portlet_navigation': navigation.Assignment(), 'portlet_review': review.Assignment(), 'portlet_recent': recent.Assignment(count=5), 'portlet_related': DONT_MIGRATE, 'portlet_languages': DONT_MIGRATE, 'portlet_calendar': DONT_MIGRATE, 'portlet_events': DONT_MIGRATE, } if HAS_PLONE_APP_EVENT: portletsMapping.update({ 'portlet_calendar': calendar.Assignment(), 'portlet_events': events.Assignment(count=5), }) # Convert left_slots and right_slots to portlets left = getUtility(IPortletManager, name='plone.leftcolumn') right = getUtility(IPortletManager, name='plone.rightcolumn') leftAssignable = getMultiAdapter((context, left), IPortletAssignmentMapping).__of__(context) rightAssignable = getMultiAdapter((context, right), IPortletAssignmentMapping).__of__(context) IPortletPermissionChecker(leftAssignable)() IPortletPermissionChecker(rightAssignable)() leftChooser = INameChooser(leftAssignable) rightChooser = INameChooser(rightAssignable) left_slots = getattr(aq_base(context), 'left_slots', []) right_slots = getattr(aq_base(context), 'right_slots', []) for item in left_slots: path = item.split('/') if len(path) == 4: newPortlet = portletsMapping.get(path[1], None) if newPortlet is None and path[0] in ('context', 'here') and path[2] == 'macros': newPortlet = classic.Assignment(path[1], path[3]) if newPortlet is not None and newPortlet is not DONT_MIGRATE: leftAssignable[leftChooser.chooseName(None, newPortlet)] = newPortlet for item in right_slots: path = item.split('/') if len(path) == 4: newPortlet = portletsMapping.get(path[1], None) if newPortlet is None and path[0] in ('context', 'here') and path[2] == 'macros': newPortlet = classic.Assignment(path[1], path[3]) if newPortlet is not None and newPortlet is not DONT_MIGRATE: rightAssignable[rightChooser.chooseName(None, newPortlet)] = newPortlet context.left_slots = [] context.right_slots = []
def create_document(container, document, zipfile): temp_id = 'document.temp.{}'.format(randint(0, 999999)) id_ = container.invokeFactory('opengever.document.document', temp_id) obj = container[id_] # Mandatory metadata metadata = { 'title': document.titles.title[0].value(), } # Optional metadata if document.openingDate is not None: metadata['document_date'] = document.openingDate if document.owner is not None: metadata['document_author'] = document.owner if document.ourRecordReference is not None: metadata['foreign_reference'] = document.ourRecordReference if document.classification is not None: metadata['classification'] = INV_CLASSIFICATION_MAPPING.get( document.classification) if document.hasPrivacyProtection is not None: metadata['privacy_layer'] = INV_PRIVACY_LAYER_MAPPING.get( document.hasPrivacyProtection) if document.openToThePublic is not None: metadata['public_trial'] = INV_PUBLIC_TRIAL_MAPPING.get( document.openToThePublic) if document.keywords: metadata['keywords'] = [k.value() for k in document.keywords.keyword] deserializer = queryMultiAdapter((obj, obj.REQUEST), IDeserializeFromJson) deserializer(validate_all=True, data=metadata) if document.files: file_ = document.files.file[0] try: zipinfo = zipfile.getinfo(file_.pathFileName) except KeyError: raise ValueError('Missing file {}'.format(file_.pathFileName)) file_field = IDocumentSchema['file'] filename = os.path.basename(file_.pathFileName) obj.file = file_field._type(data=zipfile.read(zipinfo), contentType=file_.mimeType, filename=filename) # Rename document chooser = INameChooser(container) name = chooser.chooseName(None, obj) transaction.savepoint(optimistic=True) container.manage_renameObject(obj.getId(), name) # work around possible event handler ordering issue set_digitally_available(obj, None) # fire final modified event after rename to make sure bumblebee trigger # storing views/handlers use correct document url notify(ObjectModifiedEvent(obj))
def generate_id(name, context): normalizer = component.getUtility(IIDNormalizer) chooser = INameChooser(context) normalized = normalizer.normalize(name) normalized = normalized.replace('_', '-').replace(' ', '-').lower() return chooser.chooseName(normalized, context)
def testNameChooser(self): mapping = PortletAssignmentMapping() chooser = INameChooser(mapping) c = classic.Assignment() mapping[chooser.chooseName(None, c)] = c self.failUnless(c.__name__) d = classic.Assignment() self.failIfEqual(chooser.chooseName(None, d), c.__name__)
def add(self, schedules): self._objects_added = [] for section, schedule in self._objects_created: schedules = IScheduleContainer(section) chooser = INameChooser(schedules) name = chooser.chooseName('', schedule) schedules[name] = schedule self._objects_added.append(schedule)
def add(self, course): chooser = INameChooser(self.context) name = chooser.chooseName(u'', course) self.context[name] = course self._course = course if self._level is not None: self._level.courses.add(course) return course
def addPortletToContext(context, portlet, columnName="plone.rightcolumn"): if not portlet: return column = getUtility(IPortletManager, columnName) manager = getMultiAdapter((context, column), IPortletAssignmentMapping) chooser = INameChooser(manager) manager[chooser.chooseName(None, portlet)] = portlet
def testNameChooser(self): mapping = PortletAssignmentMapping() chooser = INameChooser(mapping) c = classic.Assignment() mapping[chooser.chooseName(None, c)] = c self.assertTrue(c.__name__) d = classic.Assignment() self.assertFalse(chooser.chooseName(None, d) == c.__name__)
def upload(self, files, title='', description=''): loaded = [] namechooser = INameChooser(self.context) if not isinstance(files, list): files = [files] for item in files: if item.filename: content_type = item.headers.get('Content-Type') filename = safe_unicode(item.filename) data = item.read() id_name = '' title = title and title[0] or filename # Get a unique id here id_name = namechooser.chooseName(title, self.context) # Portal types allowed : File and Image # Since Plone 4.x both types use Blob if content_type in IMAGE_MIMETYPES: portal_type = 'ArquivoBiblioteca' wrapped_data = NamedBlobFile(data=data, filename=filename) else: portal_type = 'ArquivoBiblioteca' wrapped_data = NamedBlobFile(data=data, filename=filename) # Create content self.context.invokeFactory(portal_type, id=id_name, title=title, description=description[0]) newfile = self.context[id_name] if not newfile.Title(): newfile.setTitle(title) import transaction transaction.commit() if IBoaPratica.providedBy(self.context): newfile.setUid_pratica(self.context) # Set data if portal_type == 'ArquivoBiblioteca': if IATFile.providedBy(newfile): newfile.setFile(data, filename=filename) else: newfile.file = wrapped_data elif portal_type == 'ArquivoBiblioteca': if IATImage.providedBy(newfile): newfile.setImage(data, filename=filename) else: newfile.image = wrapped_data # Finalize content creation, reindex it newfile.reindexObject() notify(ObjectModifiedEvent(newfile)) loaded.append(newfile) if loaded: return loaded return False
def _createProject(self): """ Return newly created project, see _getProject. """ code = json.loads(self.payload)['code'] chooser = INameChooser(self.context) project_id = chooser.chooseName(code, self.context) self.context.invokeFactory("Project", project_id) project = self.context[project_id] project.setFromJSON(self.payload) self._index = project.getJSON()
def createAndAdd(self, data): resource = self._factory() resource.title = data.get('title') chooser = INameChooser(self.context) resource.__name__ = chooser.chooseName('', resource) form.applyChanges(self, resource, data) notify(ObjectCreatedEvent(resource)) self.context[resource.__name__] = resource return resource
def addTimeSlotTemplates(self, day_template_schedule, days): for key, title, time_slots in days: template = DayTemplate(title=title) day_template_schedule.templates[key] = template name_chooser = INameChooser(template) for tstart, duration in time_slots: timeslot = TimeSlot(tstart, duration, activity_type=None) key = name_chooser.chooseName('', timeslot) template[key] = timeslot
def add_portlet(self): """ Add a portlet assignment. Example data: { "portlet_manager": "plone.rightcolumn", "title": "my title", "class": "collective.portlet.links.portlet.Assignment", "portlet_data": { "links": [ {"url": "https://www.heise.de", "label": "Heise", "icon": "pdf"} ] } } """ intids = getUtility(IIntIds) data = json.loads(self.request.BODY) class_ = data["class"] portlet_manager = data["portlet_manager"] portlet_data = data["portlet_data"] mod_name, class_name = class_.rsplit(".", 1) # create assignment from something like 'collective.portlet.infolinks.portlet.Assignment' try: module = importlib.import_module(mod_name) except ModuleNotFoundError: self.request.response.setStatus( 501) # indicate 501 error in order to avoid retry on client return f"Module {class_} not found" assignment_class = getattr(module, class_name) argspec = inspect.getargspec(assignment_class.__init__) # extract parameters from `portlet_data` params = dict() for k, v in portlet_data.items(): if k in argspec.args: params[k] = v try: assignment = assignment_class(**params) except KeyError: # Assignment class may accept *args, **kw assignment = assignment_class(**portlet_data) column = getUtility(IPortletManager, portlet_manager) manager = getMultiAdapter((self.context, column), IPortletAssignmentMapping) chooser = INameChooser(manager) manager[chooser.chooseName(None, assignment)] = assignment self.request.response.setStatus(204)
def setup_institution_portlets(obj, event): ptool = getToolByName(obj, "portal_url") c_uid = obj.UID() c_root = "/" + "/".join(ptool.getRelativeContentPath(obj)) # left portlets manager = getUtility(IPortletManager, name=u"plone.leftcolumn") mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) has_navigation = False has_equal_institutions = False for value in mapping.values(): if value.__name__ == "navigation": has_navigation = True elif value.__name__ == "label_equalinstitutionsportlet": has_equal_institutions = True if not has_navigation: assignment_navigation = navigation.Assignment( name=obj.Title(), root=c_root, currentFolderOnly=False, includeTop=False, topLevel=0, bottomLevel=2 ) if not has_equal_institutions: assignment_equalinstitutions = equalinstitutionsportlet.EqualInstitutionsPortletAssignment( institution_uid=c_uid ) chooser = INameChooser(mapping) if not has_navigation: mapping[chooser.chooseName(None, assignment_navigation)] = assignment_navigation if not has_equal_institutions: mapping[chooser.chooseName(None, assignment_equalinstitutions)] = assignment_equalinstitutions # dont aquire portlets at left column assignable = queryMultiAdapter((obj, manager), ILocalPortletAssignmentManager) assignable.setBlacklistStatus("context", True) # right portlets manager = getUtility(IPortletManager, name=u"plone.rightcolumn") mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) has_institution = False for value in mapping.values(): if value.__name__ == "label_institutionportlet": has_institution = True if not has_institution: assignment_institutionportlet = institutionportlet.InstitutionPortletAssignment(institution_uid=c_uid) chooser = INameChooser(mapping) mapping[chooser.chooseName(None, assignment_institutionportlet)] = assignment_institutionportlet # dont aquire portlets at right column assignable = queryMultiAdapter((obj, manager), ILocalPortletAssignmentManager) assignable.setBlacklistStatus("context", True)
def createAndAdd(self, data): name = data['name'] description = data.get('description') namechooser = INameChooser(self.context) app = SampleApplication() name = namechooser.chooseName(name, app) app.name = name app.description = description self.context[name] = app self.request.response.redirect(name)
def add(self, content): """Add the rule to the context """ context = aq_inner(self.context) manager = aq_base(context) IPortletPermissionChecker(context)() chooser = INameChooser(manager) manager[chooser.chooseName(None, content)] = content
def __call__(self, name, content_type, data): ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(name.lower(), content_type, data) or 'File' name = name.decode('utf8') chooser = INameChooser(self.context) # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() newid = chooser.chooseName(name, self.context.aq_parent) try: transaction.begin() # Try to determine which kind of NamedBlob we need # This will suffice for standard p.a.contenttypes File/Image # and any other custom type that would have 'File' or 'Image' in # its type name # XXX heuristics are harmful behavior, here a better implemenation # is needed filename = ploneutils.safe_unicode(name) if 'Image' in type_: image = NamedBlobImage( data=data, filename=filename, contentType=content_type ) obj = createContentInContainer( self.context, type_, id=newid, image=image ) else: file = NamedBlobFile( data=data, filename=filename, contentType=content_type ) obj = createContentInContainer( self.context, type_, id=newid, file=file ) obj.title = name obj.reindexObject() transaction.commit() finally: upload_lock.release() return obj
def addPortlet(context, columnName='plone.leftcolumn', portlet=None): """ code borrowed from https://github.com/collective/wm.sampledata/blob/3146f22bf82f60924766997b5106cf03b8cd27c8/wm/sampledata/utils.py """ if not portlet: return column = getUtility(IPortletManager, columnName) manager = getMultiAdapter((context, column), IPortletAssignmentMapping) chooser = INameChooser(manager) manager[chooser.chooseName(None, portlet)] = portlet