source: cmfdeployment/branches/kenw-p4-wip/DeploymentPolicy.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: 10.4 KB
Line 
1##################################################################
2#
3# (C) Copyright 2002-2006 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"""
23Purpose: Organizes Content in a Deployment Target Structure
24Author: kapil thangavelu <k_vertigo@objectrealms.net> @2002-2006
25License: GPL
26Created: 8/10/2002
27$Id: DeploymentPolicy.py 1661M 2010-09-27 14:51:10Z (local) $
28"""
29
30from xml.dom.minidom import parseString
31   
32import DefaultConfiguration
33import Log
34import pipeline
35import io
36
37from Namespace import *
38from DeploymentInterfaces import IDeploymentPolicy
39from Products.CMFCore.utils import getToolByName
40
41class DeploymentPolicy(Folder):
42
43    meta_type = 'Deployment Policy'
44
45    __implements__ = IDeploymentPolicy
46
47    security = ClassSecurityInfo()
48    security.declareObjectProtected(CMFCorePermissions.ManagePortal)
49
50    manage_options = (
51
52        {'label':'Overview',
53         'action':'overview'},
54       
55        {'label':'Identification',
56         'action':'%s/manage_workspace'%DefaultConfiguration.ContentIdentification},
57
58        {'label':'Organization',
59         'action':'%s/manage_workspace'%DefaultConfiguration.ContentOrganization},
60
61        {'label':'Resources',
62         'action':'%s/manage_workspace'%DefaultConfiguration.SiteResources},
63
64        {'label':'URIs',
65         'action':'%s/manage_workspace'%DefaultConfiguration.ContentURIs},
66
67        {'label':'Rendering',
68         'action':'%s/manage_workspace'%DefaultConfiguration.ContentMastering},
69
70        {'label':'Transports', 
71         'action':'%s/manage_workspace'%DefaultConfiguration.ContentDeployment},
72
73        {'label':'Transforms',
74         'action':'%s/manage_workspace'%DefaultConfiguration.ContentTransforms},
75       
76        {'label':'History',
77         'action':'%s/manage_workspace'%DefaultConfiguration.DeploymentHistory},
78       
79        ) 
80
81    overview = DTMLFile('ui/PolicyOverview', globals())
82
83    identification = DTMLFile('ui/ContentIdentification', globals())
84    _active = 1
85    _reset_date = False
86    policy_xml = DTMLFile('ui/PolicyExport', globals())
87    xml_key = 'policy'
88
89    icon = 'misc_/CMFDeployment/policy.png'
90   
91    def __init__(self, id, title, pipeline_id):
92        self.id = id
93        self.title = title
94        self.pipeline_id = pipeline_id
95
96        assert pipeline_id in pipeline.getPipelineNames(), "invalid pipeline"
97
98    def getContentIdentification(self):
99        return self._getOb(DefaultConfiguration.ContentIdentification)
100
101    def getContentOrganization(self):
102        return self._getOb(DefaultConfiguration.ContentOrganization)
103
104    def getContentMastering(self):
105        return self._getOb(DefaultConfiguration.ContentMastering)
106
107    def getContentDeployment(self):
108        return self._getOb(DefaultConfiguration.ContentDeployment)
109
110    def getContentTransforms(self):
111        return self._getOb(DefaultConfiguration.ContentTransforms)
112
113    def getContentSources( self ):
114        return self.getContentIdentification().sources
115
116    def getDeploymentTransports( self ):
117        return self._getOb(DefaultConfiguration.ContentDeployment)
118
119    def getSiteResources( self ):
120        return self._getOb(DefaultConfiguration.SiteResources)
121
122    def getContentRules( self ):
123        return self.getContentMastering().rules
124   
125    def getDeploymentHistory(self):
126        return self._getOb(DefaultConfiguration.DeploymentHistory)
127
128    def getDeploymentURIs(self):
129        return self._getOb(DefaultConfiguration.ContentURIs)
130
131    def getDeploymentPolicy(self):
132        return self
133
134    security.declareProtected('Manage Portal', 'clearState')
135    def clearState(self, RESPONSE=None):
136        """
137        clear all persistent state from the policy, not including
138        configuration.
139        """
140        self.getDeploymentHistory().clear()
141        self.getDeploymentURIs().clear()
142
143        factory = pipeline.getPipeline( self.pipeline_id )
144        factory.clearState( self )
145       
146        if RESPONSE is not None:
147            RESPONSE.redirect('manage_workspace')
148
149    security.declarePrivate('getPipeline')
150    def getPipeline(self):
151        factory = pipeline.getPipeline( self.pipeline_id )
152        deployment_pipeline = factory()
153        return deployment_pipeline
154
155    def setActive(self, flag, RESPONSE=None):
156        self._active = not not flag
157        if RESPONSE is not None:
158            RESPONSE.redirect('overview')
159
160    def isActive(self):
161        return self._active
162   
163    def setResetDate(self, flag):
164        """ Set the state of the reset flag
165        """
166        self._reset_date = flag
167
168    def getResetDate(self):
169        """ Returns true if the incremental date should be ignored in the next deploy
170        """
171        return self._reset_date
172
173    def execute(self, REQUEST=None, RESPONSE=None):
174        """ """
175        if not self.isActive():
176            return
177       
178        if getattr(REQUEST, 'reset_date', False):
179            self.setResetDate(True)
180
181        histories = self.getDeploymentHistory()
182        history = histories.makeHistory()
183   
184        Log.attachLogMonitor(history)
185       
186        try:
187            try:
188                pipeline = self.getPipeline()
189                pipeline.process( self )
190            except:
191                if not DefaultConfiguration.DEPLOYMENT_DEBUG:
192                    raise
193                import sys, pdb, traceback
194                ec, e, tb = sys.exc_info()
195                print ec, e
196                print traceback.print_tb( tb )
197                #pdb.post_mortem( tb )
198                raise 
199        finally:
200            Log.detachLogMonitor(history)
201
202        #history.recordStatistics(display)
203        histories.attachHistory(history)
204
205        self.getDeploymentPolicy().setResetDate(False)
206#        import pdb
207#        pdb.set_trace()
208#KW:     Only call exportNotify() to email your site Managers of completion of export IF you have defined the expected site properties used by it (defined in that method below.)
209#        self.exportNotify(REQUEST)
210       
211        if RESPONSE:
212            return RESPONSE.redirect('manage_workspace')
213        return True
214
215    def exportNotify(self, REQUEST):
216            """Notifies users with site-wide Manager role of completion of static export deployment."""
217        plone_utils = self.aq_parent.plone_utils
218        mailhost=None
219        pm=None
220        try:
221           pm = self.aq_parent.portal_membership
222        except:
223            raise AttributeError, "Can't find pm tool"
224
225        zopeusers = []
226
227        for user in pm.listMembers():
228            localroles = pm.getMemberById(user.id).getRolesInContext(self.aq_parent.aq_parent);
229
230            if 'Manager' in localroles:
231               zopeusers.append(user.getProperty('email') )
232
233        mTo = ','.join(zopeusers)
234
235        try:
236           mailhost=self.aq_parent.MailHost
237        except:
238           raise AttributeError, "Can't find a Mail Host object"
239
240        #encoding=self.aq_parent.email_charset
241        #KW: URL modifying code below is client-specific - you might provide a URL in the email that links to a separate, viewable static site
242        #    and this URL is likely different than the URL you used to execute the deployment.
243        #    For our site, we define site properties of email_charset = utf-8, preview_domain = www.somedomain-preview.com, and email_from_address = info@somedomain.com
244        #obj_url=self.aq_parent.preview_domain.replace('-preview','-static')
245
246        sys_name=obj_url.replace('-static','')
247        #mMsg = "The export has completed. To review the results browse to: %s \n\n\n\n---\nCMS Portal Administrator" % (obj_url)
248        mMsg = "The export has completed. You may review the results on your static site URL.  \n\n\n\n---\nCMS Portal Administrator"
249        mFrom = self.aq_parent.email_from_address
250        mSubj = "Export has completed on %s" % (sys_name)
251
252        try:
253#           import pdb
254#           pdb.set_trace()
255#           mailhost.secureSend(mMsg, mTo, mFrom, subject=mSubj, subtype='', charset=encoding, debug=False, From=mFrom)
256#KW:        I believe the following send method below will work with Plone 4; the secureSend() is deprecated as of Plone 4.
257#           mailhost.send(mMsg, mTo, mFrom, subject=mSubj)
258        except:
259           raise AttributeError, "Can't send email"
260
261
262    def manage_afterAdd(self, item, container):
263        DefaultConfiguration.install(self)
264
265        factory = pipeline.getPipeline( self.pipeline_id )
266        factory.finishPolicyConstruction( self )
267
268    def manage_beforeDelete(self, *args):
269        factory = pipeline.getPipeline( self.pipeline_id )
270        factory.beginPolicyRemoval( self )
271       
272    def export( self, compact=False, RESPONSE=None ):
273        """
274        export to xml for download
275        """
276        ctx = io.ExportContext()
277        ctx.load( self )
278        try:
279            export = ctx.construct()
280        except:
281            import pdb, traceback, sys
282            exc_info = sys.exc_info()
283            traceback.print_exception( *exc_info )
284            #pdb.post_mortem( exc_info[-1] )
285            raise
286
287        if not compact:
288            dom = parseString( export )
289            export = dom.toprettyxml()
290
291        if RESPONSE is not None:
292            RESPONSE.setHeader("Content-Type", 'text/xml')
293            RESPONSE.setHeader("Content-Length", len( export ) )
294            RESPONSE.setHeader("Content-Disposition",
295                               'attachment; filename="%s.xml"'%(self.getId()))
296
297        return export
298   
299    def getInfoForXml( self ):
300        info =  {'attributes':{'id':self.id,
301                               'title': self.title_or_id(),
302                               'pipeline_id': self.pipeline_id } }
303        for ob in self.objectValues():
304            if hasattr( aq_base( ob ), 'xml_key' ):
305                info[ob.xml_key] = ob.getInfoForXml()
306        return info
307   
308InitializeClass(DeploymentPolicy)
309   
310
Note: See TracBrowser for help on using the repository browser.