def initCriteria(self): """ initialize the dictionary of import criteria for each bibliography type """ # this is a migration 0.8 -> 0.9 fix: if not shasattr(self, '_criteria'): self._criteria = PersistentMapping() bib_tool = getToolByName(self, 'portal_bibliography') has = self._criteria_names.has_key for bib_type in bib_tool.getBibliographyContentTypes(): bibname = bib_type['name'] self._criteria[bibname] = [criteria for criteria in self._nonmeta_criteria] #adds all meta_data as criteria for each bibliography type for field in bib_type['schema'].fields(): field_name = field.getName() if field_name in self._ignored_criteria: continue if not shasattr(field, 'is_duplicates_criterion'): continue if not field.is_duplicates_criterion: continue if has(field_name): self._criteria[bibname].append(self._criteria_names[field_name]) else : self._criteria[bibname].append(field_name) self._criteria[bibname].sort() self._criteria[bibname] = tuple(self._criteria[bibname])
def _getFieldObjects(self, objTypes=None, includeFSMarkers=False): """ return list of enclosed fields """ # This function currently checks to see if # an object is a form field by looking to see # if it has an fgField attribute. # Make sure we look through fieldsets if objTypes is not None: objTypes = list(objTypes)[:] objTypes.append('FieldsetFolder') myObjs = [] for obj in self.objectValues(objTypes): # use shasattr to make sure we're not aquiring # fgField by acquisition # TODO: If I stick with this scheme for enable overrides, # I'm probably going to want to find a way to cache the result # in the request. _getFieldObjects potentially gets called # several times in a request. # first, see if the field enable override is set if shasattr(obj, 'fgTEnabled') and obj.getRawFgTEnabled(): # process the override enabled TALES expression # create a context for expression evaluation context = getExprContext(self, obj) # call the tales expression, passing our custom context enabled = obj.getFgTEnabled(expression_context=context) else: enabled = True if enabled: if shasattr(obj, 'fgField'): myObjs.append(obj) if shasattr(obj, 'fieldsetFields'): if queryAdapter(obj, interface=ISchemaExtender, name=config.PROJECT_NAME + FieldsetFolderExtender.__name__): # Product is not installed --> nothing to patch obj.setTitle(obj.Title()) obj.setDescription(obj.Description()) myObjs += obj.fieldsetFields(objTypes, includeFSMarkers) for field in myObjs: if not queryAdapter(field, interface=ISchemaExtender, name=config.PROJECT_NAME + BaseFormFieldExtender.__name__): # Product is not installed --> nothing to patch continue field.setTitle(field.Title()) field.setDescription(field.Description()) if hasattr(field,'setFgDefault'): field.setFgDefault(field.getFgDefault()) if isinstance(field.fgField, (StringVocabularyField, LinesVocabularyField,)): field.fgVocabulary = field.getFgVocabulary() if isinstance(field.fgField, LikertField): field.setLikertAnswers(field.getLikertAnswers()) field.setLikertQuestions(field.getLikertQuestions()) return myObjs
def processForm(self, data=1, metadata=0, REQUEST=None, values=None): """Process the schema looking for data in the form.""" is_new_object = self.checkCreationFlag() BaseObject.processForm(self, data, metadata, REQUEST, values) if config.AUTO_NOTIFY_CANONICAL_UPDATE: if self.isCanonical(): self.invalidateTranslations() if self._at_rename_after_creation and is_new_object: new_id = self._renameAfterCreation(check_auto_id=not not self.REQUEST.form.get('id')) else: new_id = None if shasattr(self, '_lp_default_page'): delattr(self, '_lp_default_page') language = self.getLanguage() canonical = self.getCanonical() parent = aq_parent(aq_inner(self)) if ITranslatable.providedBy(parent): if not parent.hasTranslation(language): parent.addTranslation(language) translation_parent = parent.getTranslation(language) translation_parent.processForm( values=dict(title=self.Title())) translation_parent.setDescription(self.Description()) parent = translation_parent if ISelectableBrowserDefault.providedBy(parent) and new_id: parent.setDefaultPage(new_id) if shasattr(self, '_lp_outdated'): delattr(self, '_lp_outdated')
def allCriteria(self, bib_type=None): # migrate CMFBAT v0.8 duplicates engine, mending a linguistic fault-pas if shasattr(self, '_criterias'): print 'CMFBibliographyAT: performing duplicates engine property update - v0.8 -> v0.9 (allCriteria of %s)' % '/'.join(self.getId()) self._criteria = PersistentMapping() self.initCriteria() try: delattr(self, '_criterias') except: pass # this should have been performed by __init__ but after some product migrations we might want to check it here again if not shasattr(self, '_criteria'): self._criteria = PersistentMapping() if not shasattr(self, 'duplicates_criteria'): self.duplicates_criteria = PersistentMapping() # first call? initialize self._criteria (available duplicates criteria per reference type) if not self._criteria: self.initCriteria() # always init criteria, during development, schema changes, etc. self.initCriteria() if bib_type: try: self._criteria[bib_type] except KeyError: return False return self._criteria[bib_type] else: critKeys = self._criteria.keys() critKeys.sort() return [(key, self._criteria[key]) for key in critKeys]
def get_value_for_choice(obj, field): catalog = api.portal.get_tool('portal_catalog') if shasattr(field, 'vocabulary') and field.vocabulary: vocabulary = field.vocabulary elif shasattr(field, 'vocabularyName') and field.vocabularyName: factory = component.getUtility( interfaces.IVocabularyFactory, field.vocabularyName) vocabulary = factory(obj) else: return if interfaces.IContextSourceBinder.providedBy(vocabulary): criteria = vocabulary.selectable_filter.criteria results = catalog(**criteria) if not len(results): return value = results[random.randint(0, len(results) - 1)].getObject() else: if interfaces.ITreeVocabulary.providedBy(vocabulary) or \ not len(vocabulary): # Can't yet deal with tree vocabs return index = random.randint(0, len(vocabulary) - 1) value = vocabulary._terms[index].token return value
def handle_object_cloned(obj, event): """ Handler for object cloned event """ #print "Event: ", id(event) if not shasattr(obj, 'workflow_history'): return if not shasattr(obj, '_v_original'): #this is the event triggered for a clone operation return if not obj.portal_type == obj._v_original.portal_type: #the event is being dispatched to sublocations return old_history = obj._v_original.workflow_history history = obj.workflow_history #this is a persistent mapping for name in history: history[name] = old_history.get(name, ()) + history.get(name, ()) for name, wf_entries in history.items(): wf_entries = list(wf_entries) wf_entries[-1]['action'] = COPIED wf_entries[-1]['comments'] = "Copied from (uid:%s)" % \ obj._v_original.UID() history[name] = tuple(wf_entries)
def invalidateTranslationCache(self): if config.CACHE_TRANSLATIONS: if shasattr(self, '_v_canonical'): delattr(self, '_v_canonical') if shasattr(self, '_v_translations'): delattr(self, '_v_translations') if not self.isCanonical(): self.getCanonical().invalidateTranslationCache()
def getFoldersForCurrentUser(self, user=None, queryBuilderClass=None, strategy=None): """ example = {'getURL': 'http://localhost:8081/Plone/basics', 'Title': 'Basics', 'creation_date': '2012-06-28T16:31:29+02:00', 'item_icon': None, 'id': 'basics', 'no_display': False, 'show_children': True, 'UID': '00a874166069411189bbc0c86c9caab7', 'normalized_review_state': 'published', 'depth': 1, 'children': [], 'currentItem': False, 'review_state': 'published', 'getRemoteUrl': None, 'portal_type': 'Folder', 'path': '/Plone/basics', 'Description': '', 'useRemoteUrl': False, 'normalized_id': 'basics', 'normalized_portal_type': 'folder', 'Creator': 'admin', 'absolute_url': 'http://localhost:8081/Plone/basics', 'item': None, 'currentParent': False, 'link_remote': None} """ if not user: if api.user.is_anonymous(): return None user = api.user.get_current() res = [] if not shasattr(self, "content", True): return res rres = [] # FIXME: this code knows about a specific application if self.isReceiver(): if hasattr(self.content, "Transfers"): t = self.content.Transfers tpath = "/".join(t.getPhysicalPath()) rres = [ _folderTree(self, "%s" % (tpath), queryBuilderClass=queryBuilderClass, strategy=strategy)] rres[0]['item_class'] = 'personal transfer' groups = getGroupsForCurrentUser(self, user) if not groups: # User is reader only return rres # strangely, member folders for users with '-' in their username # are created with double dashes user_name = user.getUserName() user_name = user_name.replace("-", "--") m = self.content.Members g = self.content.Groups mpath = "/".join(m.getPhysicalPath()) gpath = "/".join(g.getPhysicalPath()) hasGroup = False gres = [] for group in groups: if group['etypes']: # Group is ELAN group which can produce documents hasGroup = True # print group, "isELAN" if shasattr(g, group['id']): # only when the folder really exists # print "exists" gft = _folderTree(self, "%s/%s" % (gpath, group['id']), queryBuilderClass=queryBuilderClass, strategy=strategy) # print gft if gft.has_key("show_children"): gft['item_class'] = "personal" gres.append(gft) res.extend(gres) mfolder = [ _folderTree(self, "%s/%s" % (mpath,user_name), queryBuilderClass=queryBuilderClass, strategy=strategy) ] if mfolder and not mfolder[0].has_key("show_children"): # A folder for the user has not been found, e.g. in archive # print "has no user folder" mfolder = [] else: mfolder[0]['item_class'] = "personal" res.extend(mfolder) res.extend(rres) res.reverse() if gres: # Has groups, so return all the folders return res elif hasGroup: # If the groups are not navigable (i.e. in archive): only member folder return mfolder return rres # otherwise this will be empty for a reading user, or the Transfers for a receiver
def get_dummy_dexterity_value(obj, widget, data): value = None field = widget.field catalog = getToolByName(obj, 'portal_catalog') if interfaces.IChoice.providedBy(field): if shasattr(field, 'vocabulary') and field.vocabulary: vocabulary = field.vocabulary elif shasattr(field, 'vocabularyName') and field.vocabularyName: factory = component.getUtility( interfaces.IVocabularyFactory, field.vocabularyName) vocabulary = factory(obj) else: return if interfaces.IContextSourceBinder.providedBy(vocabulary): criteria = vocabulary.selectable_filter.criteria results = catalog(**criteria) if not len(results): return value = results[random.randint(0, len(results)-1)].getObject() else: if interfaces.ITreeVocabulary.providedBy(vocabulary) or \ not len(vocabulary): # Can't yet deal with tree vocabs return index = random.randint(0, len(vocabulary)-1) value = vocabulary._terms[index].value elif interfaces.IBool.providedBy(field): value = random.randint(0, 1) and True or False elif interfaces.ITextLine.providedBy(field): if HAS_USERANDGROUPSELECTIONWIDGET and \ IUserAndGroupSelectionWidget.providedBy(widget): mtool = getToolByName(obj, 'portal_membership') mids = mtool.listMemberIds() value = mids[random.randint(0, len(mids)-1 or 1)] else: length = getattr(field, 'max_length', None) value = unicode(get_text_line()[:length]) elif interfaces.IText.providedBy(field): if IWysiwygWidget.providedBy(widget): value = unicode(get_rich_text(data)) else: value = unicode(get_text_paragraph()) elif interfaces.IDatetime.providedBy(field): days = random.random()*10 * (random.randint(-1, 1) or 1) value = datetime.datetime.now() + datetime.timedelta(days, 0) elif interfaces.IDate.providedBy(field): days = random.random()*10 * (random.randint(-1, 1) or 1) value = datetime.datetime.now() + datetime.timedelta(days, 0) return value
def setDefaults(self, instance): """Only call during object initialization, this function sets fields to schema defaults. It's adapted from the original to support IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter does not find a suitable field, or that field's value is Falseish, this function will not continue with the normal default machinery. """ for field in self.values(): # ## bika addition: we fire adapters for IAcquireFieldDefaults. # If IAcquireFieldDefaults returns None, this signifies "ignore" return. # First adapter found with non-None result, wins. value = None if shasattr(field, 'acquire'): adapters = {} for adapter in getAdapters((instance,), IAcquireFieldDefaults): sort_val = getattr(adapter[1], 'sort', 1000) if sort_val not in adapters: adapters[sort_val] = [] adapters[sort_val].append(adapter) if adapters: keys = sorted(adapters.keys()) keys.reverse() adapter = adapters[keys[0]] _value = adapter[0][1](field) if _value is not None: value = _value if field.getName().lower() == 'id': continue # If our adapter reflects a value for a reference field, it will # be permitted. if field.type == "reference" and not value: continue default = value if value else field.getDefault(instance) # always set defaults on writable fields mutator = field.getMutator(instance) if mutator is None: continue args = (default,) kw = {'field': field.__name__, '_initializing_': True} if shasattr(field, 'default_content_type'): # specify a mimetype if the mutator takes a mimetype argument if # the schema supplies a default, we honour that, otherwise we use # the site property default_content_type = field.default_content_type if default_content_type is None: default_content_type = getDefaultContentType(instance) kw['mimetype'] = default_content_type mapply(mutator, *args, **kw)
def updateFields(self): super(PopulateForm, self).updateFields() self.fields['formatting'].widgetFactory = CheckBoxFieldWidget context = aq_inner(self.context) if shasattr(context, 'getLocallyAllowedTypes'): self.fields['portal_type'].field.default = \ list(context.getLocallyAllowedTypes()) elif shasattr(context, 'allowedContentTypes'): self.fields['portal_type'].field.default = \ [t.id for t in context.allowedContentTypes()]
def create_subobjects(root, context, data, total=0): amount = int(data.get('amount', 3)) types = data.get('portal_type') if types is None: base = aq_base(context) if IBaseContent.providedBy(base): types = [] if hasattr(base, 'constrainTypesMode') and base.constrainTypesMode: types = context.locallyAllowedTypes elif IDexterityContent.providedBy(base): fti = component.getUtility(IDexterityFTI, name=context.portal_type) types = fti.filter_content_types and fti.allowed_content_types if not types: msg = _('Either restrict the addable types in this folder or ' \ 'provide a type argument.') addStatusMessage(context.request, msg) return total else: msg = _("The context doesn't provide IBaseContent or " "IDexterityContent. It might be a Plone Site object, " "but either way, I haven't gotten around to dealing with " "it. Why don't you jump in and help?") addStatusMessage(context.request, msg) return total recurse = False if data.get('recurse', None) not in [None, '0', 'False', False]: depth = 0 node = context while IUUID(node) != IUUID(root): depth += 1 node = node.aq_parent if depth < data.get('recursion_depth'): recurse = True for portal_type in types: for n in range(0, amount): obj = create_object(context, portal_type, data) total += 1 if not IObjectManager.providedBy(obj): continue if recurse: if shasattr(obj, 'getLocallyAllowedTypes'): data['portal_type'] = \ list(obj.getLocallyAllowedTypes()) elif shasattr(obj, 'allowedContentTypes'): data['portal_type'] = \ [t.id for t in obj.allowedContentTypes()] total = create_subobjects(root, obj, data, total) return total
def lastFieldIdFromForm(self, **kw): """ Retrieve the last field id in the current form""" lastField = '' myFields = [] for field in self.objectValues(): if shasattr(field, 'fgField') or shasattr(field, 'fieldsetFields'): myFields.append(field) if myFields: lastField = myFields[-1].id return lastField
def install_product(portal, product): qi = portal.portal_quickinstaller if not qi.isProductInstalled(product): qi.installProduct(product) # Refresh skins if shasattr(portal, '_v_skindata'): portal._v_skindata = None if shasattr(portal, 'setupCurrentSkin'): portal.setupCurrentSkin() print ' Installed %s' % product else: print ' %s already installed' % product
def _objImplementsInterface(self, obj, interfaceClass): """ Return boolean indicating if obj implements the given interface. """ if shasattr(interfaceClass, 'providedBy') and \ interfaceClass.providedBy(obj): return True if not shasattr(obj, '__implements__'): return False if interfaceClass in self._tupleTreeToList(obj.__implements__): return True
def prebuildPreview(self): print "Build and store preview" if getattr(self.context, 'isPreviewable', "always") == "never": return False transforms = queryUtility(ITransformEngine) field = self.context.getPrimaryField() fileobj = self.context.getFile() if not fileobj.data: print "No file data!" return False if self.context.isBinary(field.getName()): if shasattr(fileobj, 'getIterator'): data = fileobj.getIterator() elif isinstance(fileobj.data, (str, unicode)): data=text2gen(fileobj.data) else: data=chunk2gen(fileobj.data) else: if shasattr(fileobj, 'getIterator'): data = unicodegen(fileobj.getIterator()) elif isinstance(fileobj.data, (str, unicode)): data = chunk2ugen(fileobj.data, 'utf-8') else: data = text2ugen(fileobj.data, 'utf-8') result = transforms.transform(data, field.getContentType(self.context),'text/html') if result is None: self.setPreview(u"") print "No preview!" return False #get the html code #XXX load all the html in memory.... We should have an iterator here, if possible html_converted = u''.join(result.data) #update internal links #remove bad character '\xef\x81\xac' from HTMLPreview html_converted = re.sub('\xef\x81\xac', "", html_converted) # patch image sources since html base is that of our parent subobjs = result.subobjects for subobj in subobjs.keys(): # transorm iterators to strings for subobjects # we should return the iterator, but it's not possible in sub-objects right now... self.setSubObject(subobj, ''.join(subobjs[subobj])) html_converted = self._re_imgsrc.sub(self._replacer(subobjs.keys(), self.context), html_converted) #store the html in the HTMLPreview field for preview self.setPreview(html_converted) self.annotations[self.key]['lastPreviewUpdate'] = time.time() return True
def Identifier(self): """@return agls identifier or UUID""" context = aq_inner(self.context) # AGLS Identifier if shasattr(context, 'agls_id_override') and \ context.agls_id_override: value = u'urn:uuid:' + safe_unicode(context.agls_id) elif shasattr(context, 'UID'): value = u'urn:uuid:' + safe_unicode(context.UID()) else: value = safe_unicode(context.absolute_url()) return value
def populate_dexterity_type(self, obj): request = self.request view = getMultiAdapter((obj, request), name="edit") view.update() view.form_instance.render() fields = view.form_instance.fields._data_values for i in range(0, len(fields)): field = fields[i].field name = field.__name__ if name == 'title': continue if interfaces.IChoice.providedBy(field): if shasattr(field, 'vocabulary') and field.vocabulary: vocabulary = field.vocabulary elif shasattr(field, 'vocabularyName') and field.vocabularyName: factory = getUtility( interfaces.IVocabularyFactory, field.vocabularyName) vocabulary = factory(obj) else: continue index = random.randint(0, len(vocabulary)-1) value = vocabulary._terms[index].value elif interfaces.ITextLine.providedBy(field): value = self.get_text_line() elif interfaces.IText.providedBy(field): widget = view.form_instance.widgets._data_values[i] if IWysiwygWidget.providedBy(widget): value = self.get_rich_text() else: value = self.get_text_paragraph() elif interfaces.IDatetime.providedBy(field): days = random.random()*10 * (random.randint(-1,1) or 1) value = datetime.datetime.now() + datetime.timedelta(days,0) elif interfaces.IDate.providedBy(field): days = random.random()*10 * (random.randint(-1,1) or 1) value = datetime.datetime.now() + datetime.timedelta(days,0) else: continue field.set(obj, value)
def setDefaults(self, instance): """Only call during object initialization. Sets fields to schema defaults """ # TODO think about layout/vs dyn defaults for field in self.values(): if field.getName().lower() == 'id': continue if field.type == "reference": continue # always set defaults on writable fields mutator = field.getMutator(instance) if mutator is None: continue default = field.getDefault(instance) args = (default,) kw = {'field': field.__name__, '_initializing_': True} if shasattr(field, 'default_content_type'): # specify a mimetype if the mutator takes a # mimetype argument # if the schema supplies a default, we honour that, # otherwise we use the site property default_content_type = field.default_content_type if default_content_type is None: default_content_type = getDefaultContentType(instance) kw['mimetype'] = default_content_type mapply(mutator, *args, **kw)
def cpListe(context=None): """ This method unfortunately needs a side effect: The current set of common doc types needs to be reflected in the database. """ class DTRenderer(FieldRenderer): def render_readonly(self, **kwargs): """render html for read only mode""" # print self._value # print self.dts if self._value and self.dts.has_key(self._value): return u"%s (%s)" % (safe_unicode(self.dts[self._value]), safe_unicode(self._value)) else: return self._value obj = context.getContextObj() # print obj if shasattr(obj, "myDocumentTypes", True): # print "ja" dts = obj.myDocumentTypes() DTRenderer.dts = {} for dt in dts: DTRenderer.dts[safe_unicode(dt[0])] = dt[1] # Here me make sure that all current matching document types are in the database. obj.ensureMatchingDocumentTypesInDatabase() else: DTRenderer.dts = {} g = Grid(ChannelPermissions, session=__session__) g.configure(include=[g.id.with_renderer(HiddenFieldRenderer), g.doc_type.label(_(u"Doc. type (short)")).readonly().with_renderer(DTRenderer),g.perm.label(_("Permission")).dropdown(perm_options)]) return {'form': g, 'importRestricted':True, 'sortNames' : ["doc_type", "perm"]}
def __setattr__(self, key, value): # Patch this method to get the original uid of source object if key == UUID_ATTR and value is None: if not shasattr(self, '_v_src_uid'): self._v_src_uid = getattr(self, UUID_ATTR, None) BaseContentMixin.__setattr__(self, key, value)
def isTemporary(self): """Checks to see if we are created as temporary object by portal factory. """ parent = aq_parent(aq_inner(self)) return shasattr(parent, 'meta_type') and \ parent.meta_type == 'TempFolder'
def create_object(context, portal_type, data): """ """ title = get_text_line() unique_id = generate_unique_id(context, title, portal_type) args = dict(id=unique_id) if portal_type in ['Image', 'File']: myfile = StringIO(decodestring('R0lGODlhAQABAPAAAPj8+AAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==')) ext = portal_type == 'Image' and 'gif' or 'dat' myfile.filename = '.'.join((get_text_line().split(' ')[-1], ext)) args.update({'file':myfile}) new_id= context.invokeFactory(portal_type, **args) obj = context[new_id] if IDexterityContent.providedBy(obj): if shasattr(obj, 'title'): obj.title = title populate_dexterity_type(obj, data) else: obj.setTitle(title) populate_archetype(obj, data) if data.get('publish', True): wftool = getToolByName(context, 'portal_workflow') try: wftool.doActionFor(obj, 'publish') except WorkflowException, e: log.warn(e)
def set(self, data, filename, content_type): """ Set """ error = '' obj = self.context primaryField = obj.getPrimaryField() if primaryField is not None: mutator = primaryField.getMutator(obj) # mimetype arg works with blob files mutator(data, content_type=content_type, mimetype=content_type) if not obj.getFilename(): obj.setFilename(filename) #patch: #check if setFilename worked, # if not we set the filename on the blob if not obj.getFilename(): field = obj.getPrimaryField() if field: blob = field.getUnwrapped(obj) if blob is not None: if shasattr(blob, 'setFilename'): blob.setFilename(filename) #end of patch obj.reindexObject() else: # some products remove the 'primary' attribute # on ATFile or ATImage (which is very bad) error = 'serverError' logger.info("An error happens : impossible to get the primary field" " for file %s, rawdata can't be created", obj.absolute_url()) return error
def setupATVocabularies(self, portal): """ Installs all AT-based Vocabularies """ vkeys = vocabs.keys() atvm = getToolByName(portal, ATVOCABULARYTOOL, None) if atvm is None: logger.info("Products.ATVocabularyManager is NOT installed") return for vkey in vkeys: if shasattr(atvm, vkey): continue logger.info("adding vocabulary %s", vkey) try: atvm.invokeFactory('SimpleVocabulary', vkey) except Exception: logger.info("Error adding vocabulary %s", vkey) vocab = atvm[vkey] for (ikey, value) in vocabs[vkey]: vocab.invokeFactory('SimpleVocabularyTerm', ikey) vocab[ikey].setTitle(value)
def onSuccess(self, fields, REQUEST=None): """ Subscribe the """ if shasattr(self, 'condition') and \ (REQUEST.form.get(self.condition, None) or self.condition=='#NONE#'): status = self.subscribe(REQUEST)
def _createTeam(self): """ Create and associate a team object. """ p_id = self.getId() pt = getToolByName(self, 'portal_teams') # Let's not create new objects in an extraneously wrapped container pt = aq_inner(pt) if not shasattr(pt.aq_base, p_id): team = _createObjectByType('OpenTeam', pt, p_id) team.setTitle(self.Title()) self.setSpaceTeams((team,)) real_team = None tms = self.getTeams() for tm in tms: if tm.getId() == p_id: real_team = tm break assert real_team is not None and team.UID() == real_team.UID() oid = self.getOwnerTuple()[1] membership = team.addMember(oid) # Give owner team mgmt privs membership.editTeamRoles(['ProjectMember', 'ProjectAdmin']) wft = getToolByName(self, 'portal_workflow') try: wft.doActionFor(membership, 'trigger') except WorkflowException: pass
def __new__cleanup(self, name, instance, value, **kwargs): if shasattr(instance, name) and not callable(getattr(instance, name)): try: delattr(instance, name) except AttributeError: # catch occasionally raised AttributeError when trying to remove ATFieldProperty pass
def _lookupChanges(self, atse_schema_id): """ Checks if schema has changed """ provider = self.lookup_provider() # only refresh schema if editor told us # to do so. If not refreshing from editor we # take schema from where we saved it if getattr(self, '__atse_should_update__', None) != True: LOG('ATSchemaEditorNG', INFO, 'Editor did not trigger update') if not shasattr(self, '_schema_protected_from_fs_changes'): LOG('ATSchemaEditorNG', INFO, 'No saved version of schema found - taking from FS') self._schema_protected_from_fs_changes = self.schema.copy() if not config.ALWAYS_SYNC_SCHEMA_FROM_DISC == True: return self._schema_protected_from_fs_changes if config.ALWAYS_SYNC_SCHEMA_FROM_DISC == True: # looking if schema has changed atse_schema = provider.atse_getSchemaById(atse_schema_id) object_schema = self.schema if create_signature(atse_schema) != create_signature(object_schema): LOG('ATSchemaEditorNG', INFO, 'Schema <%s> changed - refreshing from disk' % atse_schema_id) provider.atse_reRegisterSchema(atse_schema_id, object_schema) self.__atse_should_update__ = False LOG('ATSchemaEditorNG', INFO, 'Updating schema from editor for %s' % self.getId()) # keeping schemata in sync self._schema_protected_from_fs_changes = provider.atse_getSchemaById(atse_schema_id).copy() self.schema = self._schema_protected_from_fs_changes.copy() return self._schema_protected_from_fs_changes
def __getitem__(self, key, silent=False): """ Allows us to get field values from the template. For example using either view/title or view['title'] Enables us to have one form for both add/edit """ if IAddForm.providedBy(self): return self.request.get(key, None) if key == 'macros': return self.index.macros if key in self.request: return self.request.get(key) context = aq_inner(self.context) if hasattr(self.context, key): return getattr(context, key) elif shasattr(context, 'Schema'): field = context.Schema().get(key) if field is not None: return field.get(context) if not silent: raise KeyError('Could not get key %s in the request or context' % key)
def listMetaTags(self, context): """ retrieve the metadata for the header and make osha specific additions """ EASHW = 'European Agency for Safety and Health at Work' putils = getToolByName(context, 'plone_utils') portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state') navigation_root_path = portal_state.navigation_root_path() navigation_root = context.restrictedTraverse(navigation_root_path) # fetch plone standard meta = putils.listMetaTags(context) meta['title'] = context.Title() meta['DC.title'] = context.Title() desc = None if shasattr(context, "getField") and context.getField("seoDescription"): desc = context.getField("seoDescription").get(context) if not desc: desc = context.Description() or navigation_root.Description() desc = "".join(BeautifulSoup(desc).findAll(text=True)) meta['description'] = desc meta['DC.description'] = desc medium = { "Image": "image", "News Item": "news", "Blog Entry": "blog", } if context.portal_type in medium: meta['medium'] = medium.get(context.portal_type) Publisher = meta.get('Publisher', None) if not Publisher or Publisher == 'No publisher': meta['Publisher'] = EASHW # Gorka requests on 6.3.2008 # Just in case, I'd like to remind you the decision we took regarding # the keywords for the keywords html tag. # The keywords should be added as follows # 1.- OSH, OSHA, EU-OSHA, Occupational safety, Occupational health, # European Agency, # 2.- plus the osha keywords, plus the thesaurus ones. in that order. PREFIX_KEYWORDS = [ 'OSH', 'OSHA', 'EU-OSHA', 'Occupational safety', 'Occupational health', 'European Agency' ] lang = getToolByName(context, 'portal_languages').getPreferredLanguage() domain = "osha" SUBJECT = [ translate(target_language=lang, msgid=s, default=s, context=context, domain=domain) for s in context.Subject() ] THESAURUS = [] if hasattr(aq_inner(context), 'getField'): field = context.getField('multilingual_thesaurus') if field is not None: pvt = getToolByName(context, 'portal_vocabularies') portal_languages = getToolByName(context, 'portal_languages') lang = portal_languages.getPreferredLanguage() manager = pvt.MultilingualThesaurus._getManager() thesitems = field.getAccessor(context)() for thesitem in thesitems: THESAURUS.append(manager.getTermCaptionById( thesitem, lang)) keywords = PREFIX_KEYWORDS + SUBJECT + THESAURUS if isinstance(keywords, (list, tuple)): # convert a list to a string if keywords is None: keywords = '' else: keywords = [ x for x in keywords if type(x) in (types.StringType, types.UnicodeType) ] keywords = ', '.join(keywords) meta['keywords'] = keywords meta['DC.subject'] = keywords # Creator, Contributor, Rights meta['DC.creator'] = EASHW meta['DC.contributors'] = EASHW meta['DC.rights'] = EASHW #Language language = context.Language() if language: meta['DC.language'] = language meta['language'] = language return meta
def pHandle_moveObjectsByDelta(self, ids, delta, subset_ids=None): """Intercept modification method for re-ordering an OrderedBaseFolder specialization used in to provide drag&drop functionality directly from Plone. does not hit the ModelDDvlPlone framework presentation layer and therefore the incalidation of cache entries must be triggered by intercepting the method. """ unResult = None if self.__class__.__name__ == 'TRAColeccionCadenas': unResult = BaseBTreeFolder.moveObjectsByDelta( self, ids, delta, subset_ids=subset_ids) else: unResult = OrderedBaseFolder.moveObjectsByDelta( self, ids, delta, subset_ids=subset_ids) if not unResult: return self unaModelDDvlPloneTool = self.fModelDDvlPloneTool() if not unaModelDDvlPloneTool: return self someImpactedUIDs = [] unaOwnUID = self.UID() someImpactedUIDs.append(unaOwnUID) if shasattr(self, 'getContenedor'): unContenedor = None try: unContenedor = self.getContenedor() except: None if not (unContenedor == None): unContenedorUID = '' if shasattr(self, 'UID'): unContenedorUID = '' try: unContenedorUID = unContenedor.UID() except: None if unContenedorUID and not (unContenedorUID in someImpactedUIDs): someImpactedUIDs.append(unContenedorUID) if shasattr(self, 'getPropietario'): unPropietario = None try: unPropietario = self.getPropietario() except: None if not (unPropietario == None) and not (unPropietario == unContenedor): unPropietarioUID = '' if shasattr(self, 'UID'): unPropietarioUID = '' try: unPropietarioUID = unPropietario.UID() except: None if unPropietarioUID and not (unPropietarioUID in someImpactedUIDs): someImpactedUIDs.append(unPropietarioUID) someIds = ids if not (someIds.__class__.__name__ in [ 'list', 'tuple', 'set', ]): someIds = [ someIds, ] aMovedNewPosition = -1 someObjectValues = self.fObjectValues() for anObjectIndex in range(len(someObjectValues)): anObject = someObjectValues[anObjectIndex] anObjectId = anObject.getId() if (anObjectId in someIds): aMovedNewPosition = anObjectIndex anObjectUID = anObject.UID() if anObjectUID and not (anObjectUID in someImpactedUIDs): someImpactedUIDs.append(anObjectUID) anElementToReportUpon = None for anId in someIds: for anObject in someObjectValues: if anObject.getId() == anId: anElementToReportUpon = anObject break anElementResult = None if not (anElementToReportUpon == None): anElementResult = unaModelDDvlPloneTool.fNewResultForElement( anElementToReportUpon) unaModelDDvlPloneTool.pFlushCachedTemplatesForImpactedElementsUIDs( self, someImpactedUIDs) aMoveReport = { 'effect': 'moved', 'new_position': aMovedNewPosition, 'delta': delta, 'moved_element': anElementResult, 'parent_traversal_name': '', 'impacted_objects_UIDs': someImpactedUIDs, } unaModelDDvlPloneTool._pSetAudit_Modification(self, 'Move Sub Object', aMoveReport) return unResult
def proxyMethod(self): attr_name = '_v_%s' % key if not shasattr(self, attr_name): setattr(self, attr_name, valueFun(self)) return getattr(self, attr_name)
def isTemporary(self): # Checks to see if we are created as temporary object by # portal factory. parent = aq_parent(aq_inner(self)) return shasattr(parent, 'meta_type') and \ parent.meta_type == 'TempFolder'
def __bobo_traverse__(self, REQUEST, name): """Allows transparent access to session subobjects. """ # sometimes, the request doesn't have a response, e.g. when # PageTemplates traverse through the object path, they pass in # a phony request (a dict). RESPONSE = getattr(REQUEST, 'RESPONSE', None) # Is it a registered sub object data = self.getSubObject(name, REQUEST, RESPONSE) if data is not None: return data # Or a standard attribute (maybe acquired...) target = None method = REQUEST.get('REQUEST_METHOD', 'GET').upper() # Logic from "ZPublisher.BaseRequest.BaseRequest.traverse" # to check whether this is a browser request if (len(REQUEST.get('TraversalRequestNameStack', ())) == 0 and # NOQA not (method in ('GET', 'HEAD', 'POST') and not isinstance(RESPONSE, xmlrpc.Response))): if shasattr(self, name): target = getattr(self, name) else: if shasattr(self, name): # attributes of self come first target = getattr(self, name) else: # then views target = queryMultiAdapter((self, REQUEST), Interface, name) if target is not None: # We don't return the view, we raise an # AttributeError instead (below) target = None else: # then acquired attributes target = getattr(self, name, None) if target is not None: logger.debug( 'traverse without explicit acquisition ' 'object=%r name=%r subobject=%r url=%r referer=%r', self, name, target, REQUEST.get('ACTUAL_URL'), REQUEST.get('HTTP_REFERER', '-')) # # STOP TRAVERSING WITHOUT EXPLICIT ACQUISITION # if REQUEST.get('ACTUAL_URL') and ( IContentish.providedBy(target) or # NOQA IPloneSiteRoot.providedBy(target)): logger.warning( 'traverse without explicit acquisition ' 'object=%r name=%r subobject=%r url=%r referer=%r', self, name, target, REQUEST.get('ACTUAL_URL'), REQUEST.get('HTTP_REFERER', '-')) if not config.DRYRUN: target = None if target is not None: return target elif (method not in ('GET', 'POST') and not isinstance(RESPONSE, xmlrpc.Response) and # NOQA REQUEST.maybe_webdav_client): return NullResource(self, name, REQUEST).__of__(self) else: # Raising AttributeError will look up views for us raise AttributeError(name)
def install(self): """ Do stuff that GS will do for us soon .. """ out = StringIO() # XXX: this doesn't actually work, as it steps on work done in # Install.py # # Note that we can apply profiles after adding a Plone site using # instancemanager: does it make more sense to leave it to # instancemanager? # # # Apply membrane and remember profiles (we can't QI them) # membrane_tool = getToolByName(self, 'membrane_tool') # if not membrane_tool: # setup_tool = getToolByName(self, 'portal_setup') # for p in ('membrane', 'remember', ): # setup_tool.setImportContext('profile-%s:default' % p) # out.write( 'Switched to profile: %s \n' % p) # result = setup_tool.runAllImportSteps() # print >>out, 'Steps run: %s \n' % ', '.join(result['steps']) # Change default member to MemberOfPublic plone = getToolByName(self, 'portal_url').getPortalObject() adder = getAdderUtility(plone) adder.default_member_type = 'MemberOfPublic' # Require approval for the adding of plain old members workflow_tool = getToolByName(self, 'portal_workflow') workflow_tool.setChainForPortalTypes(['Member'], "MemberApprovalWorkflow") # Repair status_map for our new types. # TODO: setting their workflow *after* registering the types in # TODO: Install.py messes with the default active state(s) of the # TODO: members. Fix AGX to generate them after workflow # TODO: registration. membrane_tool = getToolByName(self, 'membrane_tool') cat_map = ICategoryMapper(membrane_tool) for portal_type in ['MemberOfParliament', 'Staff', 'MemberOfPublic']: cat_set = generateCategorySetIdForType(portal_type) # states = getAllWFStatesForType(self, portal_type) states = ACTIVE_MEMBRANE_STATES[portal_type] cat_map.replaceCategoryValues(cat_set, ACTIVE_STATUS_CATEGORY, states) # Change the default workflow workflow_tool = getToolByName(self, 'portal_workflow') workflow_tool.setDefaultChain('BungeniWorkflow') workflow_tool.setChainForPortalTypes(['Folder', 'Large Plone Folder'], "BungeniWorkflow") workflow_tool.updateRoleMappings() # Enable syndication # XXX: Figure out a better way to identify the content that needs syndication syndication_tool = getToolByName(self, 'portal_syndication') if not syndication_tool.isSiteSyndicationAllowed(): syndication_tool.editProperties(isAllowed=1) if not syndication_tool.isSyndicationAllowed(self.events): syndication_tool.enableSyndication(self.events) # # Change the default roles managed by teams # teams_tool = getToolByName(self, 'portal_teams') # allowed_roles = teams_tool.getDefaultAllowedRoles() # teams_tool.setDefaultAllowedRoles( # allowed_roles+['ReviewerForSpeaker', 'CurrentMP']) teams_tool = getToolByName(self, 'portal_teams') teams_tool.setAllowedTeamTypes(TEAM_TYPES) # Replace the default MailHost with a MaildropHost if (shasattr(plone, 'MailHost') and plone.MailHost.meta_type != 'Secure Maildrop Host'): plone.manage_delObjects('MailHost') if not shasattr(plone, 'MailHost'): plone.manage_addProduct[ 'SecureMaildropHost'].manage_addSecureMaildropHost('MailHost') return out.getvalue()