source: cmfdeployment/branches/kenw-p4-wip/examples/rules/ATContentRule/__init__.py @ 2380

Last change on this file since 2380 was 2380, checked in by kenw, 8 years ago

Committing new branch intended for Plone 4 compatibility; mostly required imports of new zope packages

File size: 8.1 KB
Line 
1##################################################################
2#
3# (C) Copyright 2004 Kapil Thangavelu <k_vertigo@objectrealms.net>
4# All Rights Reserved
5#
6# This file is part of CMFDeployment.
7#
8# CMFDeployment is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# CMFDeployment is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with CMFDeployment; if not, write to the Free Software
20# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21##################################################################
22"""
23$Id: __init__.py 1165 2006-02-14 03:42:43Z hazmat $
24"""
25
26from Products.Archetypes import public as atapi
27from Products.CMFDeployment.Descriptor import DescriptorFactory
28from Products.CMFDeployment.DeploymentInterfaces import IContentRule
29from Products.CMFCore import CMFCorePermissions
30from Products.CMFCore.Expression import Expression
31from Products.CMFCore import utils
32
33from Acquisition import aq_inner, aq_parent
34from AccessControl import ClassSecurityInfo
35from OFS.SimpleItem import SimpleItem
36from Globals import DTMLFile, InitializeClass
37
38
39PROJECT_NAME = "ATContentRule"
40
41xml_export_template = """
42<mime id="%(id)s"
43      product="%(product)s"
44      factory="%(factory)s"
45      condition="%(condition)s" />
46"""
47
48def addArchetypeContentRule(self,
49                            id,
50                            condition,
51                            RESPONSE = None
52                            ):
53    """
54    add an archetype rule
55    """
56    atrule = ArchetypeContentRule(id, condition)
57    self._setObject(id, atrule)
58    if RESPONSE is not None:
59        return RESPONSE.redirect('manage_workspace')
60   
61addArchetypeContentRuleForm = DTMLFile('ui/ArchetypeContentRuleAddForm', globals())
62
63class ArchetypeContentRule(SimpleItem):
64
65    meta_type = "Archetype Content Rule"
66   
67    __implements__ = IContentRule
68
69    security = ClassSecurityInfo()
70
71    def __init__(self, id, condition):
72        self.id = id
73        self.condition = Expression( condition )
74        self.condition_text = condition
75        self.title = condition
76
77    def isValid(self, content, context):
78        if not isinstance( content, (atapi.BaseContent, atapi.BaseFolder) ):
79            return False
80        elif self.condition_text and not self.condition( context ):
81            return False
82        return True
83
84    def process(self, descriptor, context):
85        content = descriptor.getContent()
86        resource_descriptors = self.getSchemaResources( content )
87        child_descriptors = False
88        for rd in resource_descriptors:
89            descriptor.addChildDescriptor( rd )
90            child_descriptors = True
91
92        descriptor.setRenderMethod('view')
93        if child_descriptors or descriptor.isContentFolderish():
94            descriptor.setFileName( "%s/index.html"%content.getId() )
95        else:
96            descriptor.setFileName( self.getResourceName( content ) )
97
98        descriptor.rule_id = self.getId()
99           
100        return descriptor
101
102    def getSchemaResources( self, content):
103        schema = content.Schema()
104        content_path = content.absolute_url(1)
105        factory = None
106        parent = aq_parent(aq_inner(content))
107        for field in schema.filterFields():
108            if isinstance( field, (atapi.ImageField, atapi.FileField)):
109                value = field.get( content )
110            else:
111                continue
112            if not value or isinstance(value, str):
113                continue
114            if factory is None:
115                factory = DescriptorFactory( self.getDeploymentPolicy() )
116            descriptor = factory( value )
117            # xxx this isn't actually used :-( but it needs to be resolvable
118            # file objects get special treatment.  the system will work without
119            # but throw a spurious log message.
120            descriptor.setRenderMethod('index_html')
121            descriptor.setBinary( True )
122            resource_name = self.getResourceName( value )
123            #descriptor.setFileName("%s/%s"%(content.getId(), resource_name) )
124            descriptor.setFileName( resource_name )
125
126            yield descriptor
127
128    def getResourceName(self, content):
129        cid = content.getId()
130        if '.' in cid:
131            return cid
132        elif hasattr(content, 'content_type') and content.content_type:
133            if callable(content.content_type):
134                content_type = content.content_type()
135            else:
136                content_type = content.content_type
137            major, minor = content_type.split('/')
138            if major == 'text' and minor == 'plain':
139                minor = 'html'
140            if major == 'text' and minor == 'structured':
141                minor = 'html'
142            if major == 'text' and minor == 'x-rst':
143                minor = 'html'
144            return "%s.%s"%(cid, minor)
145        raise RuntimeError("Could not Determine Extension")
146
147    def toXml(self):
148        d = {'id':self.id,
149             'product':'ATContentRule',
150             'factory':'addArchetypeContentRule',
151             'condition':self.condition_text }
152
153        return xml_export_template%d
154   
155
156InitializeClass(ArchetypeContentRule)
157
158ContentSchema = atapi.BaseSchema + atapi.Schema((
159    atapi.ImageField('portrait',
160               mode='rw',
161               accessor='getPortrait',
162               mutator='setPortrait',
163               max_size=(150,150),
164               required=0,
165               widget=atapi.ImageWidget(
166                   label='Portrait',
167                   label_msgid='label_portrait',
168                   description="To add or change the portrait: click the "
169                       "\"Browse\" button; select a picture of yourself. "
170                       "Recommended image size is 75 pixels wide by 100 "
171                       "pixels tall.",
172                   description_msgid='help_portrait',
173                   i18n_domain='plone',
174                   ),
175               ),
176    ))
177
178
179class SampleImageSchemaContent( atapi.BaseContent ):
180
181    schema = ContentSchema
182    archetype_name = portal_type = meta_type = "Sample Image Content"
183
184atapi.registerType( SampleImageSchemaContent, PROJECT_NAME)
185
186
187FolderSchema = atapi.BaseFolderSchema + atapi.Schema((
188    atapi.ImageField('portrait',
189               mode='rw',
190               accessor='getPortrait',
191               mutator='setPortrait',
192               max_size=(150,150),
193               required=0,
194               widget=atapi.ImageWidget(
195                   label='Portrait',
196                   label_msgid='label_portrait',
197                   description="To add or change the portrait: click the "
198                       "\"Browse\" button; select a picture of yourself. "
199                       "Recommended image size is 75 pixels wide by 100 "
200                       "pixels tall.",
201                   description_msgid='help_portrait',
202                   i18n_domain='plone',
203                   ),
204               ),
205    ))
206
207class SampleImageSchemaFolder( atapi.BaseFolder ):
208
209    schema = FolderSchema
210    archetype_name = portal_type = meta_type = "Sample Image Folder"
211
212atapi.registerType( SampleImageSchemaFolder, PROJECT_NAME)
213
214
215def initialize(context):
216
217    content_types, constructors, ftis = atapi.process_types(
218        atapi.listTypes( PROJECT_NAME ),
219        PROJECT_NAME
220        )
221
222    utils.ContentInit(
223        PROJECT_NAME + ' Content',
224        content_types      = content_types,
225        permission         = CMFCorePermissions.AddPortalContent,
226        extra_constructors = constructors,
227        fti                = ftis,
228        ).initialize(context)
229   
230
231    context.registerClass(
232        ArchetypeContentRule,
233        permission = 'Add Content Rule',
234        constructors = ( addArchetypeContentRuleForm,
235                         addArchetypeContentRule ),
236        visibility = None
237        )
238
Note: See TracBrowser for help on using the repository browser.