def registerATCT(class_, project): """Registers an ATContentTypes based type One reason to use it is to hide the lingua plone related magic. """ assert IATContentType.isImplementedByInstancesOf(class_) registerType(class_, project)
def registerATCT(class_, project): """Registers an ATContentTypes based type One reason to use it is to hide the lingua plone related magic. """ assert IATContentType.implementedBy(class_) registerType(class_, project)
description=_(u'book_help_use_index', default=u'When enabled, a keyword index ' 'will be included in the PDF.')), ))) schemata.finalizeATCTSchema(BookSchema, folderish=True, moveDiscussion=False) class Book(folder.ATFolder): implements(IBook) security = ClassSecurityInfo() meta_type = "Book" schema = BookSchema def getDefaultLaTeXLayout(self): voc = getVocabularyRegistry().get(self, 'ftw.book.layoutsVocabulary') if len(voc) > 0: return voc.by_value.keys()[0] else: return None security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): return False atapi.registerType(Book, PROJECTNAME)
self.panelsConfig[pageIndex]['pageColumns'][columnIndex]['columnPanels'][panelIndex]['panelSkin'] = panelSkin self.panelsConfig[pageIndex]['pageColumns'][columnIndex]['columnPanels'][panelIndex]['panelObjectPath'] = panelObjectPath if panelObjectViewlet: self.panelsConfig[pageIndex]['pageColumns'][columnIndex]['columnPanels'][panelIndex]['panelObjectViewlet'] = panelObjectViewlet if viewletOptions is not None: self.panelsConfig[pageIndex]['pageColumns'][columnIndex]['columnPanels'][panelIndex]['viewletOptions']=viewletOptions self._p_changed = 1 security.declareProtected( permissions.ModifyPortalContent, 'movePanel') def movePanel(self, pageIndex, columnIndex, panelIndex, toColumn, toPanel): """move a panel from 'toIndex'""" if toColumn == -1: toColumn = columnIndex if toPanel == -1: toPanel = panelIndex panel = self.panelsConfig[pageIndex]['pageColumns'][columnIndex]['columnPanels'].pop(panelIndex) toColumnLen = len(self.panelsConfig[pageIndex]['pageColumns'][toColumn]['columnPanels']) if toPanel > toColumnLen: toPanel = toColumnLen self.panelsConfig[pageIndex]['pageColumns'][toColumn]['columnPanels'].insert(toPanel, panel) self._p_changed = 1 def getText(self): """ return the whole ContentPanels content, one panel after another, to add support for collective.portlet.content. """ return self.restrictedTraverse('contentpanels_body').render() registerType(ContentPanels, PROJECTNAME)
from Products.ATContentTypes.config import HAS_LINGUA_PLONE if HAS_LINGUA_PLONE: from Products.LinguaPlone.public import registerType else: from Products.Archetypes.atapi import registerType from ftw.blog.interfaces import IBlogCategory from ftw.blog.config import PROJECTNAME BlogCategorySchema = folder.ATFolderSchema.copy() schemata.finalizeATCTSchema(BlogCategorySchema, folderish=True, moveDiscussion=False) class BlogCategory(folder.ATFolder): """Blog Category""" implements(IBlogCategory) security = ClassSecurityInfo() portal_type = "BlogCategory" schema = BlogCategorySchema security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): return False registerType(BlogCategory, PROJECTNAME)
meta_type = "ShopCategory" schema = ShopCategorySchema def fullTitle(self): """Returns a fully qualified title for the category, including parent categories' titles if applicable. """ parent = self title_chain = [] while parent.portal_type =='ShopCategory': title_chain.append(parent.Title()) parent = aq_parent(aq_inner(parent)) title_chain.reverse() return title_chain registerType(ShopCategory, PROJECTNAME) def add_to_containing_category(context, event): """ @param context: Zope object for which the event was fired for. Usually this is Plone content object. @param event: Subclass of event. """ if not event.__class__ == ObjectRemovedEvent: parent = aq_parent(context) if parent.portal_type == 'ShopCategory': context.addToCategory(parent.UID())
security = ClassSecurityInfo() title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') security.declareProtected(View, 'tag') def tag(self, **kwargs): """Generate image tag using the api of the ImageField """ return self.getField('image').tag(self, **kwargs) def __bobo_traverse__(self, REQUEST, name): """Transparent access to image scales """ if name.startswith('image'): field = self.getField('image') image = None if name == 'image': image = field.getScale(self) else: scalename = name[len('image_'):] if scalename in field.getAvailableSizes(self): image = field.getScale(self, scale=scalename) if image is not None and not isinstance(image, basestring): # image might be None or '' for empty images return image return ATCTFileContent.__bobo_traverse__(self, REQUEST, name) atapi.registerType(Video, PROJECTNAME)
return dimension_dict.get('dimensions', []) def getDimensionsLabel(self): dimension_dict = self.getDimensionDict() return dimension_dict.get('dimension_unit', None) def getPriceUnit(self): dimension_dict = self.getDimensionDict() if 'price_unit' in dimension_dict: return dimension_dict['price_unit'] return dimension_dict.get('dimension_unit', None) def getPriceModifier(self): dimension_dict = self.getDimensionDict() return dimension_dict.get('price_to_dimension_modifier', 1) def add_to_containing_category(context, event): """ @param context: Zope object for which the event was fired for. Usually this is Plone content object. @param event: Subclass of event. """ if not event.__class__ == ObjectRemovedEvent: parent = aq_parent(context) context.addToCategory(parent.UID()) registerType(ShopItem, PROJECTNAME)
'permissions': (View, ) }, ) schema = TabbedSubpagesSchema security.declareProtected(View, 'getTargetObjectLayout') def getTargetObjectLayout(self, target): """ Returns target object 'view' action page template """ if HAS_ISBD and ISelectableBrowserDefault.providedBy(target): return target.getLayout() else: view = target.getTypeInfo().getActionById('view') or 'base_view' # If view action is view, try to guess correct template if view == 'view': view = target.portal_type.lower() + '_view' return view try: from Products.LinguaPlone.public import registerType except ImportError: from Products.Archetypes.public import registerType registerType(TabbedSubpages, PROJECTNAME)
return True security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): """ Always False: the default page is automatic for multipage """ return False security.declareProtected(CCP.View, 'getPAMDefaultPage') def getPAMDefaultPage(self): """ Return the first user visible article as default page if ViewTOC is unchecked (i.e, it redirect the user to the first page) """ request = getattr(self, 'REQUEST', None) force_toc = request.get('force_toc', False) pages = self.getPages() if force_toc or self.getViewTOCFirst() or len(pages) == 0: return request.RESPONSE.redirect( pages[0].getObject().absolute_url() + '/folder_listing') else: return request.RESPONSE.redirect( pages[0].getObject().absolute_url()) registerType(PloneArticleMultiPage, PROJECTNAME)
def validate_managers(self, value): """Make sure issue tracker managers are actual user ids""" return self._validate_user_ids(value) def validate_technicians(self, value): """Make sure issue technicians are actual user ids""" return self._validate_user_ids(value) def validate_watchers(self, value): """Make sure watchers are actual user ids or email addresses.""" membership = getToolByName(self, 'portal_membership') plone_utils = getToolByName(self, 'plone_utils') notFound = [] for userId in value: member = membership.getMemberById(userId) if member is None: # Maybe an email address if not plone_utils.validateSingleEmailAddress(userId): notFound.append(userId) if notFound: return "The following user ids could not be found: %s" % \ ','.join(notFound) return None def getDefaultManagers(self): """The default list of managers should include the tracker owner""" return (self.Creator(), ) atapi.registerType(PoiTracker, PROJECTNAME)
CarouselBannerSchema['title'].storage = atapi.AnnotationStorage() CarouselBannerSchema['description'].storage = atapi.AnnotationStorage() CarouselBannerSchema['description'].widget.visible = { 'view': 'hidden', 'edit': 'hidden' } CarouselBannerSchema['remoteUrl'].widget.label = _('Link URL') CarouselBannerSchema['remoteUrl'].required = False schemata.finalizeATCTSchema(CarouselBannerSchema, moveDiscussion=False) class CarouselBanner(link.ATLink): """A carousel banner which may include an image, text, and/or link.""" implements(ICarouselBanner) meta_type = portal_type = "Carousel Banner" schema = CarouselBannerSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- def getSize(self, scale=None): "Return the width and height of the image" return self.getField('image').getSize(self, scale=scale) atapi.registerType(CarouselBanner, PROJECTNAME)
required=False, allowable_content_types=('text/plain', ), default_content_type='text/plain', default_input_type='text/plain', default_output_type='text/x-html-safe', widget=atapi.RichWidget( label=_(u'label_supplier_address', default=u"Address"), description=_(u'help_supplier_address', default=u"Supplier's postal address"))))) SupplierSchema['title'].widget.label = _(u"label_name", default="Name") SupplierSchema['title'].widget.description = _(u"help_name", default="The supplier's name") SupplierSchema['description'].widget.visible = { 'edit': 'invisible', 'view': 'invisible' } class Supplier(base.ATCTContent): """A supplier """ implements(ISupplier) meta_type = "Supplier" schema = SupplierSchema registerType(Supplier, PROJECTNAME)
meta_type = "ShopCategory" schema = ShopCategorySchema def fullTitle(self): """Returns a fully qualified title for the category, including parent categories' titles if applicable. """ parent = self title_chain = [] while parent.portal_type == 'ShopCategory': title_chain.append(parent.Title()) parent = aq_parent(aq_inner(parent)) title_chain.reverse() return title_chain registerType(ShopCategory, PROJECTNAME) def add_to_containing_category(context, event): """ @param context: Zope object for which the event was fired for. Usually this is Plone content object. @param event: Subclass of event. """ if not event.__class__ == ObjectRemovedEvent: parent = aq_parent(context) if parent.portal_type == 'ShopCategory': context.addToCategory(parent.UID())
from Products.CMFPlone import PloneMessageFactory as _ from Products.LinguaPlone.public import BaseContent from Products.LinguaPlone.public import BaseSchema from Products.LinguaPlone.public import FileWidget from Products.LinguaPlone.public import registerType from Products.LinguaPlone.public import Schema BlobelFishSchema = BaseSchema.copy() + Schema(( BlobField(name='guide', primary=True, languageIndependent=True, widget=FileWidget( label=_(u'label_file', default=u'File'), description=_(u''), )), StringField( name='teststr', languageIndependent=True, ), )) class BlobelFish(BaseContent): """ a multilingual fish """ schema = BlobelFishSchema _at_rename_after_creation = True registerType(BlobelFish, packageName)
rows=10, allow_file_upload=False), ), )) # Set storage on fields copied from ATFolderSchema, making sure # they work well with the python bridge properties. laneskaintzaFolderSchema['title'].storage = atapi.AnnotationStorage() laneskaintzaFolderSchema['description'].storage = atapi.AnnotationStorage() schemata.finalizeATCTSchema( laneskaintzaFolderSchema, folderish=True, moveDiscussion=False ) class laneskaintzaFolder(folder.ATFolder): """Description of the Example Type""" implements(IlaneskaintzaFolder) meta_type = "laneskaintzaFolder" schema = laneskaintzaFolderSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- atapi.registerType(laneskaintzaFolder, PROJECTNAME)
implements(IBlogEntry) security = ClassSecurityInfo() portal_type = "BlogEntry" schema = BlogEntrySchema text = atapi.ATFieldProperty('text') #returns the category uid and the parent category uid def getCategoryUids(self): cats = aq_inner(self).getCategories() uids = [c.UID() for c in cats] parent_uids = [] for pc in cats: parent = aq_inner(pc).aq_parent puid = parent.UID() grand_parent = aq_inner(parent).aq_parent if puid not in parent_uids \ and grand_parent.Type() == 'Blog Category': parent_uids.append(puid) DateTime(self.CreationDate()).strftime('%m/%Y') return parent_uids + uids security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): return False registerType(BlogEntry, PROJECTNAME)
default=u'When enabled, a keyword index ' 'will be included in the PDF.'))), ))) schemata.finalizeATCTSchema(BookSchema, folderish=True, moveDiscussion=False) class Book(folder.ATFolder): implements(IBook) security = ClassSecurityInfo() meta_type = "Book" schema = BookSchema def getDefaultLaTeXLayout(self): voc = getVocabularyRegistry().get(self, 'ftw.book.layoutsVocabulary') if len(voc) > 0: return voc.by_value.keys()[0] else: return None security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): return False atapi.registerType(Book, PROJECTNAME)
_at_rename_after_creation = True security = ClassSecurityInfo() def indexObject(self): pass def reindexObject(self, idxs=[]): pass def unindexObject(self): pass def get_target(self): res = self.getRefs(self.getField('target').relationship) if not res: if not isTranslatable(self): return # fall back to canonicals target canonical = self.getCanonical() res = canonical.getRefs(self.getField('target').relationship) if not res: return res = res[0] if isTranslatable(res): lt = api.portal.get_tool('portal_languages') res = res.getTranslation(lt.getPreferredLanguage()) or res return res atapi.registerType(CollageAlias, 'Collage')
security.declareProtected(View, 'Title') def ContactEmail(self): return self.getContact_email() def Title(self): """Return the Title as firstName middleName(when available) lastName, suffix(when available)""" try: # Get the fields using the accessors, so they're properly Unicode encoded. # We also can't use the %s method of string concatentation for the same reason. # Is there another way to manage this? fn = self.getFirstName() ln = self.getLastName() except AttributeError: return u"new person" # YTF doesn't this display on the New Person page? # Couldn't call superclass's Title() for some unknown reason if self.getMiddleName(): mn = " " + self.getMiddleName() + " " else: mn = " " t = fn + mn + ln #if self.getSuffix(): # t = t + ", " + self.getSuffix() return t # Content type registration for the Archetypes machinery atapi.registerType(Person, config.PROJECTNAME)
archetype_name = 'Article with location' content_icon = 'plonearticle.gif' schema = ArticleWithLocationSchema typeDescription = 'An article with a location field' typeDescMsgId = 'description_edit_articlewithlocation' # Set up our views - these are available from the 'display' menu # default_view = 'pa_model1' # immediate_view = 'pa_model1' # suppl_views = ( # 'pa_model2', # 'pa_model3', # 'pa_model4', # 'pa_model5', # 'pa_model6', # 'pa_model7', # 'pa_model8', # 'pa_model9', # 'pa_model10', # ) # Make sure we get title-to-id generation when an object is created _at_rename_after_creation = True # Get the standard actions (tabs) actions = ArticleWithLocationActions security = ClassSecurityInfo() registerType(ArticleWithLocation, config.PROJECTNAME)
from ftw.book.interfaces import IChapter from ftw.contentpage.content.schema import finalize from simplelayout.base.interfaces import ISimpleLayoutBlock from simplelayout.base.interfaces import ISimpleLayoutCapable from zope.interface import implements try: from Products.LinguaPlone.public import registerType except ImportError: # No multilingual support from Products.Archetypes.atapi import registerType chapter_schema = folder.ATFolder.schema.copy() finalize(chapter_schema, hide=['description']) chapter_schema['excludeFromNav'].default = False class Chapter(folder.ATFolder): implements(IChapter, ISimpleLayoutCapable, ISimpleLayoutBlock) security = ClassSecurityInfo() schema = chapter_schema security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): return False registerType(Chapter, PROJECTNAME)
'permissions': (View, ) }, ) schema = TabbedSubpagesSchema security.declareProtected(View, 'getTargetObjectLayout') def getTargetObjectLayout(self, target): """ Returns target object 'view' action page template """ if HAS_ISBD and ISelectableBrowserDefault.isImplementedBy(target): return target.getLayout() else: view = target.getTypeInfo().getActionById('view') or 'base_view' # If view action is view, try to guess correct template if view == 'view': view = target.portal_type.lower() + '_view' return view try: from Products.LinguaPlone.public import registerType except ImportError: from Products.Archetypes.public import registerType registerType(TabbedSubpages)
security.declareProtected("View", 'getLocation') def getLocation(self): field_value = self.getField('location').get(self) if not field_value: block = self.get_addressblock() complete_address = '' if block: street = block.getAddress() if street: complete_address = complete_address + street + ',' zip = block.getZip() if zip: complete_address = complete_address + ' ' + zip city = block.getCity() if city: complete_address = complete_address + ' ' + city return complete_address.strip(',') return '' else: return field_value security.declareProtected("View", 'event_url') def event_url(self): block = self.get_addressblock() if block: return block.getWww() return '' registerType(EventPage, PROJECTNAME)
htmlblock_schema = ATContentTypeSchema.copy() + \ textblock.default_schema.copy() htmlblock_schema['title'].required = False htmlblock_schema['description'].widget.visible = { 'view': 'invisible', 'edit': 'invisible' } htmlblock_schema['text'].validators = () htmlblock_schema['text'].default_output_type = 'text/html' htmlblock_schema['text'].widget = atapi.TextAreaWidget(label=_( u'label_html', default=u'HTML'), description='', rows=32, cols=70) finalize(htmlblock_schema) class HTMLBlock(textblock.TextBlock): """HTML block for books. """ security = ClassSecurityInfo() implements(IHTMLBlock) schema = htmlblock_schema atapi.registerType(HTMLBlock, PROJECTNAME)
from ftw.book.config import PROJECTNAME from ftw.book.interfaces import IRemark from ftw.contentpage.content import textblock from ftw.contentpage.content.schema import finalize from zope.interface import implements try: from Products.LinguaPlone import public as atapi except ImportError: from Products.Archetypes import atapi remark_schema = ATContentTypeSchema.copy() + \ textblock.default_schema.copy() remark_schema['title'].required = False remark_schema['title'].searchable = 0 finalize(remark_schema, hide=['description', 'showTitle']) class Remark(textblock.TextBlock): """A simplelayout block used for comments """ security = ClassSecurityInfo() implements(IRemark) schema = remark_schema atapi.registerType(Remark, PROJECTNAME)
# Raise exception if there has been bad things with the script compiling field = self.schema["mipago_payment_amountOverride"] script = atapi.ObjectField.get(field, self) if len(script.warnings) > 0: log.warn("Python script " + self.title_or_id() + " has warning:" + str(script.warnings)) if len(script.errors) > 0: log.error("Python script " + self.title_or_id() + " has errors: " + str(script.errors)) raise ValueError("Python script " + self.title_or_id() + " has errors: " + str(script.errors)) security.declarePrivate('sanifyFields') def sanifyFields(self, form): # Makes request.form fields accessible in a script # # Avoid Unauthorized exceptions since REQUEST.form is inaccesible result = {} for field in form: result[field] = form[field] return result atapi.registerType(MiPagoAdapter, PROJECTNAME)
from Products.PloneGlossary.config import PROJECTNAME ExampleGlossarySchema = PloneGlossary.schema.copy() class ExampleGlossary(PloneGlossary): """ExampleGlossary""" implements(IPloneGlossary) definition_types = ('ExampleGlossaryDefinition',) meta_type = 'ExampleGlossary' schema = ExampleGlossarySchema ExampleGlossaryDefinitionSchema = PloneGlossaryDefinition.schema.copy() class ExampleGlossaryDefinition(PloneGlossaryDefinition): """ExamplePloneGlossaryDefinition""" implements(IPloneGlossaryDefinition) meta_type = 'ExampleGlossaryDefinition' schema = ExampleGlossaryDefinitionSchema registerType(ExampleGlossary, PROJECTNAME) registerType(ExampleGlossaryDefinition, PROJECTNAME)
if not hasattr(self, PLONEGLOSSARY_CATALOG): # Add a new catalog if not exists cat = self._initCatalog() else: cat = self.getCatalog() # clear catalog cat.manage_catalogClear() # Reindex glossary definitions for obj in self.objectValues(): if obj.portal_type in self.definition_types: cat.catalog_object(obj) registerType(PloneGlossary, PROJECTNAME) ### # Events handlers ### def glossaryAdded(glossary, event): """A glossary has been added""" container = event.newParent # FIXME: Fix this when AT don't need manage_afterAdd any more super(glossary.__class__, glossary).manage_afterAdd(glossary, container) glossary._initCatalog() return
portal_type = "Article" schema = ArticleSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') text = atapi.ATFieldProperty('text') hideTitle = atapi.ATFieldProperty('hideTitle') hideDescription = atapi.ATFieldProperty('hideDescription') security = ClassSecurityInfo() security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): """ Override BrowserDefaultMixin because default page stuff doesn't make sense for topics. """ return False try: from Products.DynamicHeader.interfaces import IDynamicHeader classImplements(Article, IDynamicHeader) except: # No dynamic header support pass atapi.registerType(Article, PROJECTNAME)
folder_schema = schema_cleanup(folder.ATFolderSchema.copy()) type_schema = folder_schema + document.ATDocumentSchema.copy() schemata.finalizeATCTSchema(type_schema, moveDiscussion=False) @implementer(IFolderishDocument) class FolderishDocument(folder.ATFolder, document.ATDocument): portal_type = 'Folderish Document' _at_rename_after_creation = True schema = type_schema atapi.registerType(FolderishDocument, PROJECTNAME) # EVENT folder_schema = schema_cleanup(folder.ATFolderSchema.copy()) type_schema = folder_schema + event.ATEventSchema.copy() schemata.finalizeATCTSchema(type_schema, moveDiscussion=False) type_schema.changeSchemataForField('location', 'default') type_schema.moveField('location', before='attendees') # Move location back to main schemata # noqa @implementer(IFolderishEvent) class FolderishEvent(folder.ATFolder, event.ATEvent):
ThemeTaggable.setThemes(self, value, **kw) security.declareProtected(View, 'download') def download(self, REQUEST=None, RESPONSE=None): """ Download the file """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE field = self.getField('image') return field.download(self, REQUEST, RESPONSE) registerType(Promotion, PROJECTNAME) class FrontpageSectionIndex(object): """ Front page section index """ implements(IFrontpageSectionIndex) adapts(IExternalPromotion) def __init__(self, context, request): """ """ self.context = context def __call__(self): """ """ return u'/'.join(self.context.getPhysicalPath()[:-1])
meta_type = 'Article' portal_type = 'Article' allowed_content_types = [] + list( getattr(ExternalHighlight, 'allowed_content_types', [])) + list( getattr(ATNewsItem, 'allowed_content_types', [])) filter_content_types = 1 global_allow = 1 immediate_view = 'base_view' default_view = 'highlight_view' suppl_views = () typeDescription = "Article" typeDescMsgId = 'description_edit_highlight' _at_rename_after_creation = True schema = Article_schema content_icon = 'highlight_icon.gif' # LinguaPlone doesn't check base classes for mutators security.declareProtected(ModifyPortalContent, 'setThemes') def setThemes(self, value, **kw): """ Use the tagging adapter to set the themes. """ # value = filter(None, value) value = [val for val in value if val] tagging = IThemeTagging(self) tagging.tags = value registerType(Article, PROJECTNAME)
CarouselBannerSchema['title'].storage = atapi.AnnotationStorage() CarouselBannerSchema['description'].storage = atapi.AnnotationStorage() CarouselBannerSchema['description'].widget.visible = { 'view': 'hidden', 'edit': 'hidden' } CarouselBannerSchema['remoteUrl'].widget.label = _(u'Link URL') CarouselBannerSchema['remoteUrl'].required = False schemata.finalizeATCTSchema(CarouselBannerSchema, moveDiscussion=False) class CarouselBanner(link.ATLink): """A carousel banner which may include an image, text, and/or link.""" implements(ICarouselBanner) meta_type = portal_type = "Carousel Banner" schema = CarouselBannerSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- def getSize(self, scale=None): "Return the width and height of the image" return self.getField('image').getSize(self, scale=scale) atapi.registerType(CarouselBanner, PROJECTNAME)
if file is not None and primary_field_name == 'image': self.setImage(file) elif file is not None and primary_field_name == 'file': self.setFile(file) if title is not None: self.setTitle(title) if kwargs: self.edit(**kwargs) else: self.reindexObject() # compatibility methods when used as ATImage replacement def __bobo_traverse__(self, REQUEST, name): """ helper to access image scales the old way during `unrestrictedTraverse` calls """ if isinstance(REQUEST, dict): if '_' in name: fieldname, scale = name.split('_', 1) else: fieldname, scale = name, None field = self.getField(fieldname) handler = IImageScaleHandler(field, None) if handler is not None: image = handler.getScale(self, scale) if image is not None: return image return super(ATBlob, self).__bobo_traverse__(REQUEST, name) registerType(ATBlob, packageName)
CollageRowSchema['excludeFromNav'].default = True # support show in navigation feature and at marshalling finalizeATCTSchema(CollageRowSchema, folderish=True, moveDiscussion=False) @implementer(ICollageRow) class CollageRow(BrowserDefaultMixin, LayoutContainer, atapi.OrderedBaseFolder): schema = CollageRowSchema _at_rename_after_creation = True security = ClassSecurityInfo() def SearchableText(self): return self.aggregateSearchableText() def indexObject(self): pass def reindexObject(self, idxs=[]): pass def unindexObject(self): pass atapi.registerType(CollageRow, 'Collage')
new_value = self.REQUEST.get('text',None) if new_value is not None: formatted = portal_transforms.convertTo('text/plain', new_value).getData().replace('\r','').replace('\n','') cropped = len(formatted) > 30 and formatted[:30] or formatted last_space = cropped.rfind(' ') if last_space == -1: pass else: cropped = cropped[:last_space] field.set(self,cropped.lstrip()) else: field.set(self,value) security.declareProtected(View, 'tag') def tag(self, **kwargs): """Generate image tag using the api of the ImageField """ if 'title' not in kwargs: if self.getImageAltText(): kwargs['title'] = self.getImageAltText() elif self.getImageCaption(): kwargs['title'] = self.getImageCaption() else: kwargs['title'] = self.Title() if 'alt' not in kwargs: kwargs['alt'] = self.getImageAltText() return self.getField('image').tag(self, **kwargs) atapi.registerType(Paragraph, config.PROJECTNAME)
textblock_schema['text'].widget.filter_buttons = ('image', ) finalize(textblock_schema) class TextBlock(ATCTContent, HistoryAwareMixin): """Textblock for Contentpage """ security = ClassSecurityInfo() implements(ITextBlock, ISimpleLayoutBlock) schema = textblock_schema #Special workarround for empty titles, otherwise we have "[...]" #results in the search function def setTitle(self, value): portal_transforms = getToolByName(self, 'portal_transforms') field = self.schema['title'] if not value: new_value = self.REQUEST.get('text', None) if new_value is not None: converted = portal_transforms.convertTo( 'text/plain', new_value).getData().replace('\r', '').replace('\n', '') crop = self.restrictedTraverse('@@plone').cropText cropped = crop(converted, 30, '') field.set(self, cropped.strip()) else: field.set(self, value) atapi.registerType(TextBlock, config.PROJECTNAME)
widget=atapi.SelectionWidget( label=_(u"label_importance", default=u"Importance"), description=_(u"help_importance", default=u"Select the importance of the teaser. " u"The frequency of the teaser will be " u"set accordingly."), ), ), )) schemata.finalizeATCTSchema(type_schema, folderish=False, moveDiscussion=False) @implementer(ITeaser) class Teaser(base.ATCTContent, image.ATCTImageTransform, HistoryAwareMixin): portal_type = "Teaser" _at_rename_after_creation = True schema = type_schema security = ClassSecurityInfo() @security.protected(View) def tag(self, **kwargs): """Generate image tag using the api of the ImageField """ if 'title' not in kwargs: kwargs['title'] = self.title.encode('utf-8') return self.getField('image').tag(self, **kwargs) atapi.registerType(Teaser, PROJECTNAME)
, 'permissions': (View,) }, ) schema = TabbedSubpagesSchema security.declareProtected(View, 'getTargetObjectLayout') def getTargetObjectLayout(self, target): """ Returns target object 'view' action page template """ if HAS_ISBD and ISelectableBrowserDefault.providedBy(target): return target.getLayout() else: view = target.getTypeInfo().getActionById('view') or 'base_view' # If view action is view, try to guess correct template if view == 'view': view = target.portal_type.lower() + '_view' return view try: from Products.LinguaPlone.public import registerType except ImportError: from Products.Archetypes.public import registerType registerType(TabbedSubpages, PROJECTNAME)
implements(IMap) portal_type = "Map" schema = MapSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') latitude = atapi.ATFieldProperty('latitude') longitude = atapi.ATFieldProperty('longitude') geocode = atapi.ATFieldProperty('geocode') depth = atapi.ATFieldProperty('depth') hideControls = atapi.ATFieldProperty('hideControls') enableScrollZoom = atapi.ATFieldProperty('enableScrollZoom') center = atapi.ATFieldProperty('enableCenteredView') mapType = atapi.ATFieldProperty('mapType') layer = atapi.ATFieldProperty('layer') def getMapType(self): """ backward compatibility merge old maptype to map v3 """ value = self.Schema()['mapType'].get(self) if value.startswith('G_'): if value == 'G_NORMAL_MAP': return 'ROADMAP' return value[2:-4] return value atapi.registerType(Map, PROJECTNAME)
schema = type_schema security = ClassSecurityInfo() security.declareProtected(View, 'tag') def tag(self, **kwargs): """Generate image tag using the api of the ImageField """ if 'title' not in kwargs: kwargs['title'] = self.getImageCaption() return self.getField('image').tag(self, **kwargs) def __bobo_traverse__(self, REQUEST, name): """Transparent access to image scales """ if name.startswith('image'): field = self.getField('image') image = None if name == 'image': image = field.getScale(self) else: scalename = name[len('image_'):] if scalename in field.getAvailableSizes(self): image = field.getScale(self, scale=scalename) if image is not None and not isinstance(image, basestring): # image might be None or '' for empty images return image return folderishtypes.FolderishEvent.__bobo_traverse__(self, REQUEST, name) atapi.registerType(Project, PROJECTNAME)
label=_(u"label_importance", default=u"Importance"), description=_(u"help_importance", default=u"Select the importance of the teaser. " +\ u"The frequency of the teaser will be " +\ u"set accordingly."), ), ), )) schemata.finalizeATCTSchema(type_schema, folderish=False, moveDiscussion=False) class Teaser(base.ATCTContent, image.ATCTImageTransform, HistoryAwareMixin): implements(ITeaser) portal_type = "Teaser" _at_rename_after_creation = True schema = type_schema security = ClassSecurityInfo() security.declareProtected(View, 'tag') def tag(self, **kwargs): """Generate image tag using the api of the ImageField """ if 'title' not in kwargs: kwargs['title'] = self.title return self.getField('image').tag(self, **kwargs) atapi.registerType(Teaser, PROJECTNAME)
from Products.Archetypes.atapi import registerType news_schema = contentpage.ContentPageSchema.copy() news_schema['effectiveDate'].required = True news_schema['effectiveDate'].default_method = 'getDefaultEffectiveDate' news_schema.changeSchemataForField('effectiveDate', 'default') news_schema.changeSchemataForField('expirationDate', 'default') news_schema.moveField('image', after='description') # Protect the teaser image with a specific permission permission = "ftw.contentpage: Edit teaser image on News" for name in image_schema.keys(): news_schema[name].write_permission = permission class News(contentpage.ContentPage): implements(INews) security = ClassSecurityInfo() schema = news_schema def getDefaultEffectiveDate(self): return DateTime().Date() registerType(News, PROJECTNAME)
refs = self.getReferences_list() refs.append(ob) self.setReferences_list(refs) return out security.declareProtected(ADD_CONTENT_PERMISSION, 'logImportReport') def logImportReport(self, report, **kwargs): """Store the import report. """ # Just pass off the import report to the place that actually did the importing. # XXX Should have a security check here though! self.getAssociatedBibFolder().logImportReport(report, **kwargs) security.declareProtected(ADD_CONTENT_PERMISSION, 'getEnableDuplicatesManager') def getEnableDuplicatesManager(self, **kwargs): """Check if the DuplicatesManager is enabled in the assoc. bibfolder """ if self.getAssociatedBibFolder(): return self.getAssociatedBibFolder().getEnableDuplicatesManager(**kwargs) else: return False security.declareProtected(ADD_CONTENT_PERMISSION, 'getDuplicatesMatchingPolicy') def getDuplicatesMatchingPolicy(self, **kwargs): """Retrieve the DuplicatesMatchingPolicy from the assoc. bibfolder """ if self.getAssociatedBibFolder(): return self.getAssociatedBibFolder().getDuplicatesMatchingPolicy(**kwargs) registerType(BibliographyList)
meta_type = "Image Gallery" schema = ImageGallerySchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') # -*- Your ATSchema to Python Property Bridges Here ... -*- def effective_page_size(self, images): """If the page size is lower equal 0, all images should be shown on one page. This method returns the number of images in that case. """ page_size = self.getPage_size() if page_size <= 0: return len(images) return page_size def validate_slideshow_interval(self, value): try: value = int(value) except ValueError: return _(u"The interval time should be an integer.") if value < 1: return _(u"The interval time should not be lower than 1.") if value > 30: return _(u"The interval time should not be greater than 30.") return None atapi.registerType(ImageGallery, PROJECTNAME)
def processSingleImport(self, entry, infer_references=True, **kwargs): """ """ bf = self.getAssociatedBibFolder() # No need to put in a security check on the 'real' context (i.e. bf) # here because bf.processSingleImport(...) calls self.invokeFactory(...) # which has security built-in. result = bf.processSingleImport(entry, infer_references=infer_references, **kwargs) if len(result) == 2: # skipped references only return report_line and import_status report_line, import_status = result out = (report_line, import_status, None ) elif len(result) == 3: # successfully imported references additionally return an object report_line, import_status, ob = result out = (report_line, import_status, ob ) # This is just for clarity return out security.declareProtected(BIBFOLDER_ADD_CONTENT_PERMISSION, 'logImportReport') def logImportReport(self, report): """Store the import report. """ # Just pass off the import report to the place that actually did the importing. # XXX Should have a security check here though! self.getAssociatedBibFolder().logImportReport(report) registerType(BibliographyTopic, PROJECTNAME)
CollageColumnSchema['excludeFromNav'].default = True # support show in navigation feature and at marshalling finalizeATCTSchema(CollageColumnSchema, folderish=True, moveDiscussion=False) @implementer(ICollageColumn) class CollageColumn(BrowserDefaultMixin, LayoutContainer, atapi.OrderedBaseFolder): schema = CollageColumnSchema _at_rename_after_creation = True security = ClassSecurityInfo() def SearchableText(self): return self.aggregateSearchableText() def indexObject(self): pass def reindexObject(self, idxs=[]): pass def unindexObject(self): pass atapi.registerType(CollageColumn, 'Collage')
def getDimensionsLabel(self): dimension_dict = self.getDimensionDict() return dimension_dict.get('dimension_unit', None) def getPriceUnit(self): dimension_dict = self.getDimensionDict() if 'price_unit' in dimension_dict: return dimension_dict['price_unit'] return dimension_dict.get('dimension_unit', None) def getPriceModifier(self): dimension_dict = self.getDimensionDict() return dimension_dict.get('price_to_dimension_modifier', 1) def add_to_containing_category(context, event): """ @param context: Zope object for which the event was fired for. Usually this is Plone content object. @param event: Subclass of event. """ if not event.__class__ == ObjectRemovedEvent: parent = aq_parent(context) context.addToCategory(parent.UID()) registerType(ShopItem, PROJECTNAME)
htmlblock_schema = ATContentTypeSchema.copy() + \ textblock.default_schema.copy() htmlblock_schema['title'].required = False htmlblock_schema['description'].widget.visible = {'view': 'invisible', 'edit': 'invisible'} htmlblock_schema['text'].validators = () htmlblock_schema['text'].default_output_type = 'text/html' htmlblock_schema['text'].widget = atapi.TextAreaWidget( label=_(u'label_html', default=u'HTML'), description='', rows=32, cols=70) finalize(htmlblock_schema) class HTMLBlock(textblock.TextBlock): """HTML block for books. """ security = ClassSecurityInfo() implements(IHTMLBlock) schema = htmlblock_schema atapi.registerType(HTMLBlock, PROJECTNAME)
class Article(folder.ATFolder): """An article.""" implements(IArticle) portal_type = "Article" schema = ArticleSchema title = atapi.ATFieldProperty('title') description = atapi.ATFieldProperty('description') text = atapi.ATFieldProperty('text') hideTitle = atapi.ATFieldProperty('hideTitle') hideDescription = atapi.ATFieldProperty('hideDescription') security = ClassSecurityInfo() security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): """Override BrowserDefaultMixin because default page stuff doesn't make sense for topics. """ return False try: from Products.DynamicHeader.interfaces import IDynamicHeader classImplements(Article, IDynamicHeader) # pragma: no cover except: # No dynamic header support pass atapi.registerType(Article, PROJECTNAME)
schema = Highlight_schema _at_rename_after_creation = True security = ClassSecurityInfo() # LinguaPlone doesn't check base classes for mutators security.declareProtected(ModifyPortalContent, 'setThemes') def setThemes(self, value, **kw): """ Use the tagging adapter to set the themes. """ # value = filter(None, value) value = [val for val in value if val] tagging = IThemeTagging(self) tagging.tags = value security.declareProtected(View, 'download') def download(self, REQUEST=None, RESPONSE=None): """ Download the file """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE img_field = self.getField('image') return img_field.download(self, REQUEST, RESPONSE) registerType(Highlight, PROJECTNAME)
) CollageSchema = CollageSchema + CommonCollageSchema.copy() # move description to main edit page CollageSchema["description"].schemata = "default" # support show in navigation feature and at marshalling # speciel case set folderish to False since we want related items to be used finalizeATCTSchema(CollageSchema, folderish=False, moveDiscussion=False) class Collage(LayoutContainer, ATCTMixin, atapi.OrderedBaseFolder): # FIXME: Do we always need Zope 2 style interfaces ? __implements__ = (getattr(atapi.OrderedBaseFolder, "__implements__", ()), getattr(ATCTMixin, "__implements__", ())) schema = CollageSchema _at_rename_after_creation = True security = ClassSecurityInfo() implements(ICollage, INonStructuralFolder) def SearchableText(self): return self.aggregateSearchableText() atapi.registerType(Collage, "Collage")
, 'permissions': (View,) }, ) schema = TabbedSubpagesSchema security.declareProtected(View, 'getTargetObjectLayout') def getTargetObjectLayout(self, target): """ Returns target object 'view' action page template """ if HAS_ISBD and ISelectableBrowserDefault.isImplementedBy(target): return target.getLayout() else: view = target.getTypeInfo().getActionById('view') or 'base_view' # If view action is view, try to guess correct template if view == 'view': view = target.portal_type.lower() + '_view' return view try: from Products.LinguaPlone.public import registerType except ImportError: from Products.Archetypes.public import registerType registerType(TabbedSubpages)
from Products.ATContentTypes.config import HAS_LINGUA_PLONE if HAS_LINGUA_PLONE: from Products.LinguaPlone.public import registerType else: from Products.Archetypes.atapi import registerType from ftw.blog.interfaces import IBlog from ftw.blog.config import PROJECTNAME BlogSchema = folder.ATFolderSchema.copy() schemata.finalizeATCTSchema(BlogSchema, folderish=True, moveDiscussion=False) class Blog(folder.ATFolder): """The Ftw Blog Type""" implements(IBlog) portal_type = "Blog" schema = BlogSchema security = ClassSecurityInfo() security.declarePublic('canSetDefaultPage') def canSetDefaultPage(self): return False registerType(Blog, PROJECTNAME)