def setUp(self): self.portal = self.layer['portal'] combine_bundles(self.portal) persistent_directory = getUtility(IResourceDirectory, name="persistent") container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] self.production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]
def update_last_compilation(context): # Let's do the imports inline, so they are not needlessly done at startup. # Should not really matter, but oh well. from datetime import datetime from plone.registry.interfaces import IRegistry from zope.component import getUtility from Products.CMFPlone.interfaces import IBundleRegistry registry = getUtility(IRegistry) records = registry.forInterface(IBundleRegistry, prefix="plone.bundles/easyform") # Technically we only need year, month and day. # But keep this in sync with registry.xml. records.last_compilation = datetime(2020, 9, 8, 17, 52, 0) logger.info("Updated the last_compilation date of the easyform bundle.") # Run the combine-bundles import step or its handler. # Can be done with an upgrade step: # <gs:upgradeDepends # title="combine bundles" # import_steps="combine-bundles" # run_deps="false" # /> # But directly calling the basic function works fine. # See also comment here: # https://github.com/collective/collective.easyform/pull/248#issuecomment-689365240 # Also, here we can do a try/except so it does not fail on Plone 5.0, # which I think does not have the import step, not the function. try: from Products.CMFPlone.resources.browser.combine import combine_bundles except ImportError: logger.warning("Could not call combine_bundles. You should do that yourself.") return portal = api.portal.get() combine_bundles(portal)
def buildSite(self, form): # CSRF protect. DO NOT use auto CSRF protection for adding a site alsoProvides(self.request, IDisableCSRFProtection) self.request.response.setHeader('Content-type', 'application/json') extension_ids = form.get('extension_ids[]', []) extension_ids.append('castle.cms:default') # TODO: barceloneta needs to just be removed if 'plonetheme.barceloneta:default' in extension_ids: extension_ids.remove('plonetheme.barceloneta:default') site_id = form.get('site_id', 'Castle') try: site = addPloneSite( self.get_creation_context(site_id), site_id, title=form.get('title', ''), profile_id=form.get('profile_id', _DEFAULT_PROFILE), extension_ids=extension_ids, setup_content=form.get('setup_content', True), default_language=form.get('default_language', 'en'), portal_timezone=form.get('portal_timezone', 'UTC')) # delete news/events since they have default pages attached to them api.content.delete(objects=(site['news'], site['events'])) install.tiles(site, self.request) # need to reindex catalog = api.portal.get_tool('portal_catalog') catalog.manage_catalogRebuild() combine_bundles(site) if DYNAMIC_STORAGE_ENABLED: url = '{}/sites/{}'.format(self.context.absolute_url(), site_id) else: url = '{}/{}'.format(self.context.absolute_url(), site_id) # we do not allow basic auth acl_users = site.acl_users acl_users.manage_delObjects(['credentials_basic_auth']) cookie_auth = acl_users.credentials_cookie_auth # this is relative to [site]/acl_users/credentials_basic_auth # otherwise, doing /login on a site would redirect to [root]/@@secure-login cookie_auth.login_path = u'../../@@secure-login' return json.dumps({'success': True, 'url': url}) except Exception as e: LOGGER.error('Error creating site', exc_info=True) transaction.abort( ) # abort creating this site if there was an error return json.dumps({'success': False, 'msg': str(e)})
def combine_bundles(self): """Combine JS/CSS bundles together. Since this is only for Plone 5 or higher, we do the import inline. The imported function was introduced in Plone 5.0.3. """ from Products.CMFPlone.resources.browser.combine import combine_bundles combine_bundles(self.context) return 'OK'
def test_overrides(self): persistent_directory = getUtility(IResourceDirectory, name="persistent") container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] container.makeDirectory('static') static = container['static'] static.writeFile('plone-legacy-compiled.js', 'alert("Overrided legacy!");') combine_bundles(self.portal) self.assertIn(b'alert("Overrided legacy!");', self.production_folder.readFile('default.js'))
def test_overrides(self): persistent_directory = getUtility( IResourceDirectory, name="persistent") container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] container.makeDirectory('static') static = container['static'] static.writeFile('plone-legacy-compiled.js', 'alert("Overrided legacy!");') combine_bundles(self.portal) self.assertIn( 'alert("Overrided legacy!");', self.production_folder.readFile('default.js') )
def setUpPloneSite(self, portal): # Configure five.globalrequest portal.REQUEST['PARENTS'] = [portal.__parent__] setRequest(portal.REQUEST) # Install into Plone site using portal_setup applyProfile(portal, 'plone.app.contenttypes:default') applyProfile(portal, 'plone.app.mosaic:default') applyProfile(portal, 'castle.cms:default') portal.portal_workflow.setDefaultChain('simple_publication_workflow') install.tiles(portal, portal.REQUEST) combine_bundles(portal) # Clear globalrequest clearRequest()
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface(IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface(IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return # Let's join all css and js cooked_css = '' cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] for css_resource in resource.css: css_url = siteUrl + '/' + css_resource response = subrequest(css_url) if response.status == 200: css = response.getBody() cooked_css += '\n/* Resource: {0} */\n{1}\n'.format( css_resource, css if '.min.css' == css_resource[-8:] else cssmin(css)) else: cooked_css += '\n/* Could not find resource: {0} */\n\n'.format( # noqa css_resource) if not resource.js: continue js_url = siteUrl + '/' + resource.js response = subrequest(js_url) if response.status == 200: js = response.getBody() try: cooked_js += '\n/* resource: {0} */\n{1}'.format( resource.js, js if '.min.js' == resource.js[-7:] else minify(js, mangle=False, mangle_toplevel=False)) except SyntaxError: cooked_js += '\n/* resource(error cooking): {0} */\n{1}'.format( # noqa resource.js, js) else: cooked_js += '\n/* Could not find resource: {0} */\n\n'.format( js_url) cooked_js += REQUIREJS_RESET_POSTFIX js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path: logger.warn('Could not compile js/css for bundle as there is ' 'no jscompilation setting') return # Storing js resource_path = js_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) try: folder = container[resource_name] fi = StringIO(cooked_js) folder.writeFile(resource_filepath, fi) if css_path: # Storing css if defined resource_path = css_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory( OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) folder = container[resource_name] fi = StringIO(cooked_css) folder.writeFile(resource_filepath, fi) bundle.last_compilation = datetime.now() # setRequest(original_request) except NotFound: logger.info('Error compiling js/css for the bundle') # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles""" registry = getUtility(IRegistry) resources = registry.collectionOfInterface( IResourceRegistry, prefix="plone.resources", check=False ) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface( IBundleRegistry, prefix="plone.bundles", check=False ) if "plone-legacy" in bundles: bundle = bundles["plone-legacy"] else: bundle = bundles.setdefault("plone-legacy") bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path and not css_path: logger.warning( "No js_path or css_path found. We need a plone.resource " "based resource path in order to store the compiled JS and CSS." ) return # Let's join all css and js css_compiler = Compiler(output_style="compressed") cooked_css = "" cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] if css_path: for css_resource in resource.css: css_url = siteUrl + "/" + css_resource response = subrequest(css_url) if response.status == 200: logger.info("Cooking css %s", css_resource) css = response.getBody() if css_resource[-8:] != ".min.css": css = css_compiler.compile_string(css) if not isinstance(css, str): css = css.decode("utf8") cooked_css += "\n/* Resource: {} */\n{}\n".format(css_resource, css) else: cooked_css += "\n/* Could not find resource: {} */\n\n".format( css_resource ) logger.warning("Could not find resource: %s", css_resource) if not resource.js or not js_path: continue js_url = siteUrl + "/" + resource.js response = subrequest(js_url) if response.status == 200: logger.info("Cooking js %s", resource.js) js = response.getBody() if not isinstance(js, str): js = js.decode("utf8") try: cooked_js += "\n/* resource: {} */\n{}".format( resource.js, js if resource.js.endswith(".min.js") else es5.minify_print(js), ) except SyntaxError: cooked_js += "\n/* Resource (error cooking): {} */\n{}".format( resource.js, js ) logger.warning("Error cooking resource: %s", resource.js) else: logger.warning("Could not find resource: %s", resource.js) cooked_js += "\n/* Could not find resource: {} */\n\n".format(js_url) cooked_js += REQUIREJS_RESET_POSTFIX persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] def _write_resource(resource_path, cooked_string): if not resource_path: return if "++plone++" in resource_path: resource_path = resource_path.split("++plone++")[-1] if "/" in resource_path: resource_name, resource_filepath = resource_path.split("/", 1) else: resource_name = "legacy" resource_filepath = resource_path if resource_name not in container: container.makeDirectory(resource_name) if not isinstance( cooked_string, bytes ): # handle Error of OFS.Image # noqa: E501 cooked_string = cooked_string.encode("ascii", errors="ignore") try: folder = container[resource_name] fi = BytesIO(cooked_string) folder.writeFile(resource_filepath, fi) logger.info("Writing cooked resource: %s", resource_path) except NotFound: logger.warning("Error writing cooked resource: %s", resource_path) _write_resource(js_path, cooked_js) _write_resource(css_path, cooked_css) bundle.last_compilation = datetime.now() # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface( IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface( IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path and not css_path: logger.warn( 'No js_path or css_path found. We need a plone.resource ' 'based resource path in order to store the compiled JS and CSS.' ) return # Let's join all css and js css_compiler = Compiler(output_style='compressed') cooked_css = u'' cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] if css_path: for css_resource in resource.css: css_url = siteUrl + '/' + css_resource response = subrequest(css_url) if response.status == 200: logger.info('Cooking css %s', css_resource) css = response.getBody() if css_resource[-8:] != '.min.css': css = css_compiler.compile_string(css) if not isinstance(css, six.text_type): css = css.decode('utf8') cooked_css += u'\n/* Resource: {0} */\n{1}\n'.format( css_resource, css ) else: cooked_css +=\ u'\n/* Could not find resource: {0} */\n\n'.format( css_resource ) logger.warn('Could not find resource: %s', css_resource) if not resource.js or not js_path: continue js_url = siteUrl + '/' + resource.js response = subrequest(js_url) if response.status == 200: js = response.getBody() try: logger.info('Cooking js %s', resource.js) if not isinstance(js, six.text_type): js = js.decode('utf8') cooked_js += '\n/* resource: {0} */\n{1}'.format( resource.js, js if '.min.js' == resource.js[-7:] else es5.minify_print(js) ) except SyntaxError: cooked_js +=\ '\n/* Resource (error cooking): {0} */\n{1}'.format( resource.js, js ) logger.warn('Error cooking resource: %s', resource.js) else: logger.warn('Could not find resource: %s', resource.js) cooked_js += '\n/* Could not find resource: {0} */\n\n'.format( js_url ) cooked_js += REQUIREJS_RESET_POSTFIX persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] def _write_resource(resource_path, cooked_string): if not resource_path: return resource_path = resource_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) if resource_name not in container: container.makeDirectory(resource_name) if not isinstance(cooked_string, six.binary_type): # handle Error of OFS.Image # noqa: E501 cooked_string = cooked_string.encode('ascii', errors='ignore') try: folder = container[resource_name] fi = BytesIO(cooked_string) folder.writeFile(resource_filepath, fi) logger.info('Writing cooked resource: %s', resource_path) except NotFound: logger.warn('Error writing cooked resource: %s', resource_path) _write_resource(js_path, cooked_js) _write_resource(css_path, cooked_css) bundle.last_compilation = datetime.now() # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface(IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface(IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path and not css_path: logger.warn( 'No js_path or css_path found. We need a plone.resource ' 'based resource path in order to store the compiled JS and CSS.') return # Let's join all css and js css_compiler = Compiler(output_style='compressed') cooked_css = u'' cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] if css_path: for css_resource in resource.css: css_url = siteUrl + '/' + css_resource response = subrequest(css_url) if response.status == 200: logger.info('Cooking css %s', css_resource) css = response.getBody() if css_resource[-8:] != '.min.css': css = css_compiler.compile_string(css) cooked_css += u'\n/* Resource: {0} */\n{1}\n'.format( css_resource, css) else: cooked_css +=\ u'\n/* Could not find resource: {0} */\n\n'.format( css_resource ) logger.warn('Could not find resource: %s', css_resource) if not resource.js or not js_path: continue js_url = siteUrl + '/' + resource.js response = subrequest(js_url) if response.status == 200: js = response.getBody() try: logger.info('Cooking js %s', resource.js) cooked_js += '\n/* resource: {0} */\n{1}'.format( resource.js, js if '.min.js' == resource.js[-7:] else minify(js, mangle=False, mangle_toplevel=False)) except SyntaxError: cooked_js +=\ '\n/* Resource (error cooking): {0} */\n{1}'.format( resource.js, js ) logger.warn('Error cooking resource: %s', resource.js) else: logger.warn('Could not find resource: %s', resource.js) cooked_js += '\n/* Could not find resource: {0} */\n\n'.format( js_url) cooked_js += REQUIREJS_RESET_POSTFIX persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] def _write_resource(resource_path, cooked_string): if not resource_path: return resource_path = resource_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) if resource_name not in container: container.makeDirectory(resource_name) if not isinstance(cooked_string, str): # handle Error of OFS.Image cooked_string = cooked_string.encode('ascii', errors='ignore') try: folder = container[resource_name] fi = StringIO(cooked_string) folder.writeFile(resource_filepath, fi) logger.info('Writing cooked resource: %s', resource_path) except NotFound: logger.warn('Error writing cooked resource: %s', resource_path) _write_resource(js_path, cooked_js) _write_resource(css_path, cooked_css) bundle.last_compilation = datetime.now() # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def afterSetUp(self): combine_bundles(self.portal) persistent_directory = getUtility( IResourceDirectory, name="persistent") container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] self.production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface(IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface(IBundleRegistry, prefix="plone.bundles", check=False) if "plone-legacy" in bundles: bundle = bundles["plone-legacy"] else: bundle = bundles.setdefault("plone-legacy") bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just shipped # as a legacy compiled js file return # Let's join all css and js css_file = "" cooked_js = """ /* reset requirejs definitions so that people who put requirejs in legacy compilation do not get errors */ var _old_define = define; var _old_require = require; define = undefined; require = undefined; try{ """ siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package in resources: resource = resources[package] for css in resource.css: response = subrequest(siteUrl + "/" + css) if response.status == 200: css_file += response.getBody() css_file += "\n" if resource.js: response = subrequest(siteUrl + "/" + resource.js) if response.status == 200: js = response.getBody() try: cooked_js += "\n/* resource: %s */\n%s" % ( resource.js, minify(js, mangle=False, mangle_toplevel=False), ) except SyntaxError: cooked_js += "\n/* resource(error cooking): %s */\n%s" % (resource.js, js) else: cooked_js += "\n/* Could not find resource: %s */\n\n" % resource.js cooked_js += """ }catch(e){ // log it if (typeof console !== "undefined"){ console.log('Error loading javascripts!' + e); } }finally{ define = _old_define; require = _old_require; } """ cooked_css = cssmin(css_file) js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path: logger.warn("Could not compile js/css for bundle as there is " "no jscompilation setting") return # Storing js resource_path = js_path.split("++plone++")[-1] resource_name, resource_filepath = resource_path.split("/", 1) persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) try: folder = container[resource_name] fi = StringIO(cooked_js) folder.writeFile(resource_filepath, fi) if css_path: # Storing css if defined resource_path = css_path.split("++plone++")[-1] resource_name, resource_filepath = resource_path.split("/", 1) persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) folder = container[resource_name] fi = StringIO(cooked_css) folder.writeFile(resource_filepath, fi) bundle.last_compilation = datetime.now() # setRequest(original_request) except NotFound: logger.info("Error compiling js/css for the bundle") # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface( IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface( IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return # Let's join all css and js cooked_css = '' cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] for css_resource in resource.css: css_url = siteUrl + '/' + css_resource response = subrequest(css_url) if response.status == 200: css = response.getBody() cooked_css += '\n/* Resource: {0} */\n{1}\n'.format( css_resource, css if '.min.css' == css_resource[-8:] else cssmin(css) ) else: cooked_css += '\n/* Could not find resource: {0} */\n\n'.format( # noqa css_resource ) if not resource.js: continue js_url = siteUrl + '/' + resource.js response = subrequest(js_url) if response.status == 200: js = response.getBody() try: cooked_js += '\n/* resource: {0} */\n{1}'.format( resource.js, js if '.min.js' == resource.js[-7:] else minify(js, mangle=False, mangle_toplevel=False) ) except SyntaxError: cooked_js += '\n/* resource(error cooking): {0} */\n{1}'.format( # noqa resource.js, js ) else: cooked_js += '\n/* Could not find resource: {0} */\n\n'.format( js_url ) cooked_js += REQUIREJS_RESET_POSTFIX js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path: logger.warn('Could not compile js/css for bundle as there is ' 'no jscompilation setting') return # Storing js resource_path = js_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) try: folder = container[resource_name] fi = StringIO(cooked_js) folder.writeFile(resource_filepath, fi) if css_path: # Storing css if defined resource_path = css_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) persistent_directory = getUtility( IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory( OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) folder = container[resource_name] fi = StringIO(cooked_css) folder.writeFile(resource_filepath, fi) bundle.last_compilation = datetime.now() # setRequest(original_request) except NotFound: logger.info('Error compiling js/css for the bundle') # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface( IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface( IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just shipped # as a legacy compiled js file return # Let's join all css and js css_file = "" cooked_js = """ /* reset requirejs definitions so that people who put requirejs in legacy compilation do not get errors */ var _old_define = define; var _old_require = require; define = undefined; require = undefined; try{ """ siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package in resources: resource = resources[package] for css in resource.css: response = subrequest(siteUrl + '/' + css) if response.status == 200: css_file += response.getBody() css_file += '\n' if resource.js: response = subrequest(siteUrl + '/' + resource.js) if response.status == 200: js = response.getBody() try: cooked_js += '\n/* resource: %s */\n%s' % ( resource.js, minify(js, mangle=False, mangle_toplevel=False) ) except SyntaxError: cooked_js += '\n/* resource(error cooking): %s */\n%s' % ( resource.js, js) else: cooked_js += '\n/* Could not find resource: %s */\n\n' % resource.js cooked_js += """ }catch(e){ // log it if (typeof console !== "undefined"){ console.log('Error loading javascripts!' + e); } }finally{ define = _old_define; require = _old_require; } """ cooked_css = cssmin(css_file) js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path: logger.warn('Could not compile js/css for bundle as there is ' 'no jscompilation setting') return # Storing js resource_path = js_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) try: folder = container[resource_name] fi = StringIO(cooked_js) folder.writeFile(resource_filepath, fi) if css_path: # Storing css if defined resource_path = css_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) persistent_directory = getUtility( IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory( OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] if resource_name not in container: container.makeDirectory(resource_name) folder = container[resource_name] fi = StringIO(cooked_css) folder.writeFile(resource_filepath, fi) bundle.last_compilation = datetime.now() # setRequest(original_request) except NotFound: logger.info('Error compiling js/css for the bundle') # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)