def __call__(self, fname=None, fset=None): # Note that fset (field set) is not used. This is added so # the function signature is the same as in plone.app.z3cform. # This may avoid errors. res = {'errmsg': ''} if fname is None: return json.dumps(res) form = aq_inner(self.context) context = aq_inner(form.context) request = self.request processInputs(request) setPageEncoding(request) raw_fname = fname[len(form.prefix) + 1:] formlib_field = form.form_fields[raw_fname] widgets = formlib.setUpWidgets( (formlib_field,), form.prefix, context, request, form=form, adapters={}, ignore_request=False) widget = widgets[raw_fname] error = None try: widget.getInputValue() except: pass error = widget.error() res['errmsg'] = error or '' self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
def _extractDataManagers(self): # we extract object values from the request for conveinent use by any # step. data_adapters = {} fields = form.Fields() for step in self.controller.getTraversedFormSteps(): # call processInputs to convert request.form to unicode processInputs(step.request) # Five only convert request.form to unicode, but (some) formlib # widgets use request so we need to get unicode values from # request.form and copy them to request for key in step.request.form.keys(): step.request[key] = step.request.form[key] if not interfaces.IWizardFormStep.providedBy(step): continue data_adapters.update(step.getSchemaAdapters()) widgets = form.setUpEditWidgets( step.form_fields, step.prefix, step.context, step.request, adapters=data_adapters, ignore_request=False ) fields += step.form_fields data = {} form.getWidgetsData(widgets, step.prefix, data) # extract the form data to the adapters actualize # their state. self._restoreAdapterValues(data, data_adapters) return data_adapters, fields
def __call__(self, fname): res = {'errmsg': ''} form = aq_inner(self.context) context = aq_inner(form.context) request = self.request processInputs(request) setPageEncoding(request) raw_fname = fname[len(form.prefix) + 1:] formlib_field = form.form_fields[raw_fname] widgets = formlib.setUpWidgets( (formlib_field,), form.prefix, context, request, form=form, adapters={}, ignore_request=False) widget = widgets[raw_fname] error = None try: widget.getInputValue() except: pass error = widget.error() res['errmsg'] = error or '' self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
def update(self): processInputs(self.request) self.errors = {} submitted = False form = self.request.form if 'form.button.Cancel' in form: IStatusMessage(self.request).add(_(u'Changes canceled.')) portal_url = getToolByName(self.context, 'portal_url')() self.request.response.redirect("%s/plone_control_panel"% portal_url) return False if 'form.button.Select' in form: self.authorize() submitted = True registry = getUtility(IRegistry) settings = registry.forInterface(IExhibitSettings) selected = form.get('selected_types', None) if isinstance(selected, basestring): selected = (selected,) settings.exhibit_item_types = tuple(selected) if submitted and not self.errors: IStatusMessage(self.request).add(u"Updated content type list") elif submitted: IStatusMessage(self.request).add(_(u"There were errors"), 'error') return True
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++%s++%s" % (THEME_RESOURCE_NAME, self.name,) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = "%s/%s" % (self.portalUrl, self.themeBasePath,) self.editable = IWritableResourceDirectory.providedBy(self.resourceDirectory) settings = getUtility(IRegistry).forInterface(IThemeSettings, False) self.active = (settings.enabled and self.name == getCurrentTheme()) self.rulesFileName = RULE_FILENAME self.jsVariables = "var CURRENT_SELECTION='%s'; var THEME_BASE_URL='%s'; var THEME_BASE_PATH_ENCODED='%s'; var EDITABLE=%s; var RULE_FILENAME='%s';" % ( self.request.get('file-selector') or '', self.themeBaseUrl, self.themeBasePathEncoded, str(self.editable).lower(), self.rulesFileName )
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++{0:s}++{1:s}".format( THEME_RESOURCE_NAME, self.name ) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = '/'.join([self.portalUrl, self.themeBasePath]) self.editable = IWritableResourceDirectory.providedBy( self.resourceDirectory ) if self.editable: self.resourceUrl = self.resourceDirectory.context.absolute_url() else: self.resourceUrl = None settings = getUtility(IRegistry).forInterface(IThemeSettings, False) self.active = (settings.enabled and self.name == getCurrentTheme()) self.rulesFileName = RULE_FILENAME
def validate_input(self, formname, fieldname, value=None): """Given a form (view) name, a field name and the submitted value, validate the given field. """ # Abort if there was no value changed. Note that the actual value # comes along the submitted form, since a widget may require more than # a single form field to validate properly. if value is None: return context = aq_inner(self.context) request = aq_inner(self.request) processInputs(self.request) # Find the form, the field and the widget form = getMultiAdapter((context, request), name=formname) form = form.__of__(context) raw_fieldname = fieldname[len(form.prefix)+1:] formlib_field = form.form_fields[raw_fieldname] widgets = formlib.setUpWidgets((formlib_field,), form.prefix, context, request, form=form, adapters={}, ignore_request=False) widget = widgets[raw_fieldname] # Attempt to convert the value - this will trigge validation ksscore = self.getCommandSet('core') kssplone = self.getCommandSet('plone') validate_and_issue_message(ksscore, widget, fieldname, kssplone)
def update(self): # BBB: for CMFDefault < 2.3 (explicit charset required) self.request.RESPONSE.setHeader('Content-Type', 'text/html; charset=%s' % HTTPRequest.default_encoding) # BBB: for Zope < 4 if not getattr(self.request, 'postProcessInputs', False): processInputs(self.request, [HTTPRequest.default_encoding]) super(FiveFormlibMixin, self).update()
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.customizationsPackageName = CUSTOMIZATIONS_PACKAGE_NAME self.portalUrl = getToolByName(self.context, 'portal_url')() self.jsVariables = "" % ( )
def update(self): # XXX: if we don't set default_encoding explicitly, main_template might # set a different charset self.request.RESPONSE.setHeader('Content-Type', 'text/html; charset=%s' % HTTPRequest.default_encoding) # BBB: for Zope < 2.14 if not getattr(self.request, 'postProcessInputs', False): processInputs(self.request, [HTTPRequest.default_encoding]) super(_EditFormMixin, self).update()
def update(self): pprop = getToolByName(self.context, 'portal_properties') charsets = [pprop.site_properties.default_charset] processInputs(self.request, charsets) content_type = 'text/html; charset=%s' % charsets[0] self.request.RESPONSE.setHeader('Content-Type', content_type) super(EditFormBase, self).update() if self.request.form.has_key('form.exportbutton'): self.send_csv_data()
def update(self): # BBB: for Zope < 2.14 if not getattr(self.request, 'postProcessInputs', False): processInputs(self.request, [HTTPRequest.default_encoding]) self.adapter = getAdapter(self.context, IComponentsSetupSchema) if 'apply' in self.request.form: self.adapter.body = self.request.form['body'] self.status = 'Saved changes.'
def saveFile(self, path, value): processInputs(self.request) path = self.request.form.get("path", path) value = self.request.form.get("value", value) path = path.lstrip("/").encode("utf-8") value = value.replace("\r\n", "\n").encode("utf-8") self.context.writeFile(path, value) return " " # Zope no likey empty responses
def saveFile(self, path, value): processInputs(self.request) path = self.request.form.get('path', path) value = self.request.form.get('value', value) path = path.lstrip('/').encode('utf-8') value = value.replace('\r\n', '\n').encode('utf-8') self.context.writeFile(path, value) return ' ' # Zope no likey empty responses
def update(self): # XXX: if we don't set default_encoding explicitly, main_template might # set a different charset self.request.response.setHeader( 'Content-Type', 'text/html; charset=%s' % HTTPRequest.default_encoding) # BBB: for Zope < 2.14 if not getattr(self.request, 'postProcessInputs', False): processInputs(self.request, [HTTPRequest.default_encoding]) super(_EditFormMixin, self).update()
def update(self): processInputs(self.request) self.errors = {} submitted = False form = self.request.form if 'form.button.Cancel' in form: self.redirect(_(u"Changes canceled.")) return False if 'form.button.Import' in form: self.authorize() submitted = True replaceExisting = form.get('replaceExisting', False) newslettercreatorArchive = form.get('newslettercreatorArchive', None) newslettercreatorZip = None performImport = False try: newslettercreatorZip = zipfile.ZipFile(newslettercreatorArchive) except (zipfile.BadZipfile, zipfile.LargeZipFile,): logger.exception("Could not read zip file") self.errors['newslettercreatorArchive'] = _('error_invalid_zip', default=u"The uploaded file is not a valid Zip archive" ) if newslettercreatorZip: resourceName = extractResourceName(newslettercreatorZip) newslettercreatorContainer = getOrCreatePersistentResourceDirectory() newslettercreatorExists = resourceName in newslettercreatorContainer if newslettercreatorExists: if not replaceExisting: self.errors['newslettercreatorArchive'] = _('error_already_installed', u"This newsletter theme is already installed. Select 'Replace existing newsletter theme' and re-upload to replace it." ) else: del newslettercreatorContainer[resourceName] performImport = True else: performImport = True if performImport: newslettercreatorContainer.importZip(newslettercreatorZip) if submitted and not self.errors: IStatusMessage(self.request).add(_(u"Changes saved")) elif submitted: IStatusMessage(self.request).add(_(u"There were errors"), 'error') return True
def decoded_request_func(self, *args, **kw): if 'request' in kw: request = kw['request'] else: try: request = self.request except AttributeError: raise ValueError('Unable to find request.') orig_form = request.form.copy() decode.processInputs(request) res = func(self, *args, **kw) request.form = orig_form return res
def update(self): processInputs(self.request) self.errors = {} submitted = False form = self.request.form registry = getUtility(IRegistry) settings = registry.forInterface(ISettings) if 'form.button.Cancel' in form: IStatusMessage(self.request).add(_(u'Changes canceled.')) portal_url = getToolByName(self.context, 'portal_url')() self.request.response.redirect("%s/plone_control_panel" % portal_url) return False if 'form.button.Save' in form: self.authorize() submitted = True default = form.get('default_style', None) settings.default_style = default style_file = form.get('csl_file', None) if style_file is not None and style_file.filename: citation_styles = settings.citation_styles if citation_styles is None: citation_styles = {} style = etree.parse(style_file).getroot() style_info = style.find( '{http://purl.org/net/xbiblio/csl}info') style_id = unicode( style_info.find( '{http://purl.org/net/xbiblio/csl}title').text) citation_styles[style_id] = unicode(etree.tostring(style)) settings.citation_styles = citation_styles if submitted and not self.errors: IStatusMessage(self.request).add(u"Updated citation styles") elif submitted: IStatusMessage(self.request).add(_(u"There were errors"), 'error') return True
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++{0:s}++{1:s}".format( THEME_RESOURCE_NAME, self.name ) self.themeBasePathEncoded = urllib.parse.quote_plus(self.themeBasePath) self.themeBaseUrl = '/'.join([self.portalUrl, self.themeBasePath]) try: registry = getUtility(IRegistry) self.lessUrl = registry['plone.resources.lessc'] self.lessVariables = self.portalUrl + '/' + registry['plone.resources.less-variables'] except: self.lessUrl = None self.lessVariables = None self.editable = IWritableResourceDirectory.providedBy( self.resourceDirectory ) if self.editable: self.resourceUrl = self.resourceDirectory.context.absolute_url() else: self.resourceUrl = None policy = theming_policy(self.request) settings = policy.getSettings() self.active = (settings.enabled and self.name == policy.getCurrentTheme()) self.rulesFileName = RULE_FILENAME
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++{0:s}++{1:s}".format( THEME_RESOURCE_NAME, self.name ) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = '/'.join([self.portalUrl, self.themeBasePath]) try: registry = getUtility(IRegistry) self.lessUrl = registry['plone.resources.lessc'] self.lessVariables = self.portalUrl + '/' + registry['plone.resources.less-variables'] except: self.lessUrl = None self.lessVariables = None self.editable = IWritableResourceDirectory.providedBy( self.resourceDirectory ) if self.editable: self.resourceUrl = self.resourceDirectory.context.absolute_url() else: self.resourceUrl = None policy = theming_policy(self.request) settings = policy.getSettings() self.active = (settings.enabled and self.name == policy.getCurrentTheme()) self.rulesFileName = RULE_FILENAME
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++{0:s}++{1:s}".format(THEME_RESOURCE_NAME, self.name) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = '/'.join([self.portalUrl, self.themeBasePath]) self.editable = IWritableResourceDirectory.providedBy( self.resourceDirectory) settings = getUtility(IRegistry).forInterface(IThemeSettings, False) self.active = (settings.enabled and self.name == getCurrentTheme()) self.rulesFileName = RULE_FILENAME
def update(self): processInputs(self.request) self.errors = {} submitted = False form = self.request.form registry = getUtility(IRegistry) settings = registry.forInterface(ISettings) if 'form.button.Cancel' in form: IStatusMessage(self.request).add(_(u'Changes canceled.')) portal_url = getToolByName(self.context, 'portal_url')() self.request.response.redirect("%s/plone_control_panel"% portal_url) return False if 'form.button.Save' in form: self.authorize() submitted = True default = form.get('default_style', None) settings.default_style = default style_file = form.get('csl_file', None) if style_file is not None and style_file.filename: citation_styles = settings.citation_styles if citation_styles is None: citation_styles = {} style = etree.parse(style_file).getroot() style_info = style.find('{http://purl.org/net/xbiblio/csl}info') style_id = unicode(style_info.find('{http://purl.org/net/xbiblio/csl}title').text) citation_styles[style_id] = unicode(etree.tostring(style)) settings.citation_styles = citation_styles if submitted and not self.errors: IStatusMessage(self.request).add(u"Updated citation styles") elif submitted: IStatusMessage(self.request).add(_(u"There were errors"), 'error') return True
def update(self): processInputs(self.request) self.adapters = self.wizard.data_manager.adapters super(CheckoutAddress, self).update() # If the user has set up alternate opt-in language, use it instead opt_in_text = None portal = getToolByName(self.context, 'portal_url').getPortalObject() try: opt_in_text = IGetPaidManagementOptions( portal).alternate_opt_in_text except AttributeError: opt_in_text = None if opt_in_text and len(opt_in_text): formSchemas = component.getUtility(interfaces.IFormSchemas) widgets = self._getWidgetsByInterface( formSchemas.getInterface('contact_information') ) for w in widgets: if w.name == 'form.marketing_preference': w.context.title = opt_in_text
def update(self): processInputs(self.request) setPageEncoding(self.request) super(FiveFormlibMixin, self).update()
def update(self): # XXX: complexity too high: refactoring needed processInputs(self.request) self._setup() self.errors = {} form = self.request.form if 'form.button.Cancel' in form: IStatusMessage(self.request).add(_(u"Changes cancelled")) self.redirect("{0}/@@overview-controlpanel".format(self.site_url)) return False if 'form.button.Enable' in form: self.authorize() themeSelection = form.get('themeName', None) if themeSelection: themeData = self.getThemeData( self.availableThemes, themeSelection ) applyTheme(themeData) self.theme_settings.enabled = True IStatusMessage( self.request ).add( _( u"Theme enabled. Note that this control panel page is " u"never themed." ) ) self._setup() return True if 'form.button.InvalidateCache' in form: self.authorize() policy = theming_policy() policy.invalidateCache() return True if 'form.button.Disable' in form: self.authorize() applyTheme(None) self.theme_settings.enabled = False IStatusMessage(self.request).add(_(u"Theme disabled.")) self._setup() return True if 'form.button.AdvancedSave' in form: self.authorize() self.theme_settings.readNetwork = form.get('readNetwork', False) themeEnabled = form.get('themeEnabled', False) rules = form.get('rules', None) prefix = form.get('absolutePrefix', None) doctype = str(form.get('doctype', "")) hostnameBlacklist = form.get('hostnameBlacklist', []) parameterExpressions = {} parameterExpressionsList = form.get('parameterExpressions', []) for line in parameterExpressionsList: try: name, expression = line.split('=', 1) name = str(name.strip()) expression = str(expression.strip()) parameterExpressions[name] = expression except ValueError: message = _( 'error_invalid_parameter_expressions', default=u"Please ensure you enter one expression per " u"line, in the format <name> = <expression>." ) self.errors['parameterExpressions'] = message themeBase = form.get('themeBase', None) markSpecialLinks = form.get('markSpecialLinks', None) extLinksOpenInNewWindow = form.get('extLinksOpenInNewWindow', None) if not self.errors: # Trigger onDisabled() on plugins if theme was active # previously and rules were changed if self.theme_settings.rules != rules: applyTheme(None) self.theme_settings.enabled = themeEnabled self.theme_settings.rules = rules self.theme_settings.absolutePrefix = prefix self.theme_settings.parameterExpressions = parameterExpressions self.theme_settings.hostnameBlacklist = hostnameBlacklist self.theme_settings.doctype = doctype # Theme base settings if themeBase is not None: if six.PY2: themeBase = themeBase.encode('utf-8') self.pskin.default_skin = themeBase if markSpecialLinks is not None: self.mark_special_links = markSpecialLinks if extLinksOpenInNewWindow is not None: self.ext_links_open_new_window = extLinksOpenInNewWindow IStatusMessage(self.request).add(_(u"Changes saved")) self._setup() return True else: IStatusMessage(self.request).add( _(u"There were errors"), 'error' ) self.redirectToFieldset('advanced') return False if 'form.button.Import' in form: self.authorize() enableNewTheme = form.get('enableNewTheme', False) replaceExisting = form.get('replaceExisting', False) themeArchive = form.get('themeArchive', None) themeZip = None performImport = False try: themeZip = zipfile.ZipFile(themeArchive) except (zipfile.BadZipfile, zipfile.LargeZipFile): logger.exception("Could not read zip file") self.errors['themeArchive'] = _( 'error_invalid_zip', default=u"The uploaded file is not a valid Zip archive" ) if themeZip: try: themeData = extractThemeInfo(themeZip, checkRules=False) except (ValueError, KeyError) as e: logger.warn(str(e)) self.errors['themeArchive'] = _( 'error_no_rules_file', u"The uploaded file does not contain a valid theme " u"archive." ) else: themeContainer = getOrCreatePersistentResourceDirectory() themeExists = themeData.__name__ in themeContainer if themeExists: if not replaceExisting: self.errors['themeArchive'] = _( 'error_already_installed', u"This theme is already installed. Select " u"'Replace existing theme' and re-upload to " u"replace it." ) else: del themeContainer[themeData.__name__] performImport = True else: performImport = True if performImport: themeContainer.importZip(themeZip) themeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, themeData.__name__ ) if themeDirectory is not None: # If we don't have a rules file, use the template if themeData.rules == u"/++{0:s}++{1:s}/{2:s}".format( THEME_RESOURCE_NAME, themeData.__name__, RULE_FILENAME, ) and not themeDirectory.isFile(RULE_FILENAME): templateThemeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, TEMPLATE_THEME ) themeDirectory.writeFile( RULE_FILENAME, templateThemeDirectory.readFile(RULE_FILENAME) ) if not themeDirectory.isFile(DEFAULT_THEME_FILENAME): IStatusMessage(self.request).add( _( u"A boilerplate rules.xml was added to " u"your theme, but no index.html file " u"found. Update rules.xml to reference " u"the current theme file." ), 'warning', ) plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if pluginSettings is not None: for name, plugin in plugins: plugin.onCreated( themeData.__name__, pluginSettings[name], pluginSettings ) if enableNewTheme: applyTheme(themeData) self.theme_settings.enabled = True if not self.errors: self.redirect( "{0}/++theme++{1}/@@theming-controlpanel-mapper".format( self.site_url, themeData.__name__ ) ) return False else: IStatusMessage(self.request).add( _(u"There were errors"), "error" ) self.renderOverlay('upload') return True if 'form.button.CreateTheme' in form: self.authorize() title = form.get('title') description = form.get('description') or '' baseOn = form.get('baseOn', TEMPLATE_THEME) enableImmediately = form.get('enableImmediately', True) if not title: self.errors['title'] = _(u"Title is required") IStatusMessage(self.request).add( _(u"There were errors"), 'error' ) self.renderOverlay('new-theme') return True else: if any(x.__name__ == title for x in getZODBThemes()): self.errors['title'] = _(u"Duplicate title") IStatusMessage(self.request).add( _(u"This title is already in use"), 'error' ) return True name = createThemeFromTemplate(title, description, baseOn) self._setup() if enableImmediately: themeData = self.getThemeData(self.availableThemes, name) applyTheme(themeData) self.theme_settings.enabled = True self.redirect( "{0}/++theme++{1}/@@theming-controlpanel-mapper".format( self.site_url, name ) ) return False if 'form.button.DeleteSelected' in form: self.authorize() toDelete = form.get('themes', []) themeDirectory = getOrCreatePersistentResourceDirectory() for theme in toDelete: del themeDirectory[theme] IStatusMessage(self.request).add(_(u"Theme deleted"), 'info') self._setup() return True return True
def __init__(self, context, request): BrowserView.__init__(self, context, request) processInputs(self.request, self.charsets) setPageEncoding(self.request) self._setUpWidgets()
def update(self): processInputs(self.request) self._setup() self.errors = {} submitted = False form = self.request.form if 'form.button.Cancel' in form: self.redirect(_(u"Changes canceled.")) return False if 'form.button.BasicSave' in form: self.authorize() submitted = True self.settings.enabled = form.get('enabled', False) themeSelection = form.get('selectedTheme', None) if themeSelection != "_other_": themeData = self.getThemeData(self.availableThemes, themeSelection) applyTheme(themeData) if 'form.button.AdvancedSave' in form: self.authorize() submitted = True self.settings.readNetwork = form.get('readNetwork', False) rules = form.get('rules', None) prefix = form.get('absolutePrefix', None) doctype = str(form.get('doctype', "")) hostnameBlacklist = form.get('hostnameBlacklist', []) parameterExpressions = {} parameterExpressionsList = form.get('parameterExpressions', []) for line in parameterExpressionsList: try: name, expression = line.split('=', 1) parameterExpressions[str(name.strip())] = str(expression.strip()) except ValueError: self.errors['parameterExpressions'] = _('error_invalid_parameter_expressions', default=u"Please ensure you enter one expression per line, in the format <name> = <expression>." ) if not self.errors: # Trigger onDisabled() on plugins if theme was active # previously and rules were changed if self.settings.rules != rules: applyTheme(None) self.settings.rules = rules self.settings.absolutePrefix = prefix self.settings.parameterExpressions = parameterExpressions self.settings.hostnameBlacklist = hostnameBlacklist self.settings.doctype = doctype if 'form.button.Import' in form: self.authorize() submitted = True enableNewTheme = form.get('enableNewTheme', False) replaceExisting = form.get('replaceExisting', False) themeArchive = form.get('themeArchive', None) themeZip = None performImport = False try: themeZip = zipfile.ZipFile(themeArchive) except (zipfile.BadZipfile, zipfile.LargeZipFile,): logger.exception("Could not read zip file") self.errors['themeArchive'] = _('error_invalid_zip', default=u"The uploaded file is not a valid Zip archive" ) if themeZip: try: themeData = extractThemeInfo(themeZip) except (ValueError, KeyError,), e: logger.warn(str(e)) self.errors['themeArchive'] = _('error_no_rules_file', u"The uploaded file does not contain a valid theme archive." ) else: themeContainer = getOrCreatePersistentResourceDirectory() themeExists = themeData.__name__ in themeContainer if themeExists: if not replaceExisting: self.errors['themeArchive'] = _('error_already_installed', u"This theme is already installed. Select 'Replace existing theme' and re-upload to replace it." ) else: del themeContainer[themeData.__name__] performImport = True else: performImport = True if performImport: themeContainer.importZip(themeZip) themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, themeData.__name__) if themeDirectory is not None: plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if pluginSettings is not None: for name, plugin in plugins: plugin.onCreated(themeData.__name__, pluginSettings[name], pluginSettings) if enableNewTheme: applyTheme(themeData) self.settings.enabled = True
def update(self): # BBB: for Zope < 2.14 if not getattr(self.request, 'postProcessInputs', False): processInputs(self.request, [HTTPRequest.default_encoding]) super(ComponentsSetupView, self).update()
def update(self): if not getattr(self.request, '__inputs_processed', False): decode.processInputs(self.request) decode.setPageEncoding(self.request) self.request.__inputs_processed = True super(FiveFormlibMixin, self).update()
def setup(self): processInputs(self.request)
def getFrame(self): """AJAX method to load a frame's contents Expects two query string parameters: ``path`` - the path to fetch - and ``theme``, which can be 'off', to disable the theme and 'apply' to apply the current theme to the response. Additionally: - a query string parameter ``links`` can be set to one of ``disable`` or ``replace``. The former will disable hyperlinks; the latter will replace them with links using the ``@@themeing-controlpanel-getframe`` view. - a query string parameter ``forms`` can be set to one of ``disable`` or ``replace``. The former will disable forms ; the latter will replace them with links using the ``@@themeing-controlpanel-getframe`` view. - a query string parameter ``title`` can be set to give a new page title """ processInputs(self.request) path = self.request.form.get('path', None) theme = self.request.form.get('theme', 'off') links = self.request.form.get('links', None) forms = self.request.form.get('forms', None) title = self.request.form.get('title', None) if not path: return "<html><head></head><body></body></html>" portal = getPortal() portal_url = portal.absolute_url() response = subrequest(path, root=portal) result = response.getBody() content_type = response.headers.get('content-type') encoding = None if content_type is not None and ';' in content_type: content_type, encoding = content_type.split(';', 1) if encoding is None: encoding = 'utf-8' else: # e.g. charset=utf-8 encoding = encoding.split('=', 1)[1].strip() # Not HTML? Return as-is if content_type is None or not content_type.startswith('text/html'): if len(result) == 0: result = ' ' # Zope does not deal well with empty responses return result result = result.decode(encoding).encode('ascii', 'xmlcharrefreplace') if len(result) == 0: result = ' ' # Zope does not deal well with empty responses if theme == 'off': self.request.response.setHeader('X-Theme-Disabled', '1') elif theme == 'apply': self.request.response.setHeader('X-Theme-Disabled', '1') themeInfo = getThemeFromResourceDirectory(self.context) registry = getUtility(IRegistry) settings = registry.forInterface(IThemeSettings, False) context = self.context try: context = findContext(portal.restrictedTraverse(path)) except (KeyError, NotFound,): pass serializer = getHTMLSerializer([result], pretty_print=False) try: transform = compileThemeTransform(themeInfo.rules, themeInfo.absolutePrefix, settings.readNetwork, themeInfo.parameterExpressions or {}) except lxml.etree.XMLSyntaxError, e: return self.theme_error_template(error=e.msg) params = prepareThemeParameters(context, self.request, themeInfo.parameterExpressions or {}) # Fix url and path since the request gave us this view params['url'] = quote_param("%s%s" % (portal_url, path,)) params['path'] = quote_param("%s%s" % (portal.absolute_url_path(), path,)) if themeInfo.doctype: serializer.doctype = themeInfo.doctype if not serializer.doctype.endswith('\n'): serializer.doctype += '\n' serializer.tree = transform(serializer.tree, **params) result = ''.join(serializer)
def update(self): processInputs(self.request) self._setup() self.errors = {} form = self.request.form if 'form.button.Cancel' in form: IStatusMessage(self.request).add(_(u"Changes cancelled")) portalUrl = getToolByName(self.context, 'portal_url')() self.redirect("%s/plone_control_panel" % portalUrl) return False if 'form.button.Enable' in form: self.authorize() themeSelection = form.get('themeName', None) if themeSelection: themeData = self.getThemeData(self.availableThemes, themeSelection) applyTheme(themeData) self.settings.enabled = True IStatusMessage(self.request).add(_(u"Theme enabled. Note that this control panel page is never themed.")) self._setup() return True if 'form.button.Disable' in form: self.authorize() applyTheme(None) self.settings.enabled = False IStatusMessage(self.request).add(_(u"Theme disabled.")) self._setup() return True if 'form.button.AdvancedSave' in form: self.authorize() self.settings.readNetwork = form.get('readNetwork', False) themeEnabled = form.get('themeEnabled', False) rules = form.get('rules', None) prefix = form.get('absolutePrefix', None) doctype = str(form.get('doctype', "")) hostnameBlacklist = form.get('hostnameBlacklist', []) parameterExpressions = {} parameterExpressionsList = form.get('parameterExpressions', []) for line in parameterExpressionsList: try: name, expression = line.split('=', 1) parameterExpressions[str(name.strip())] = \ str(expression.strip()) except ValueError: self.errors['parameterExpressions'] = \ _('error_invalid_parameter_expressions', default=u"Please ensure you enter one " u"expression per line, in the " u"format <name> = <expression>." ) themeBase = form.get('themeBase', None) markSpecialLinks = form.get('markSpecialLinks', None) extLinksOpenInNewWindow = form.get('extLinksOpenInNewWindow', None) usePopups = form.get('usePopups', None) iconVisibility = form.get('iconVisibility', None) if not self.errors: # Trigger onDisabled() on plugins if theme was active # previously and rules were changed if self.settings.rules != rules: applyTheme(None) self.settings.enabled = themeEnabled self.settings.rules = rules self.settings.absolutePrefix = prefix self.settings.parameterExpressions = parameterExpressions self.settings.hostnameBlacklist = hostnameBlacklist self.settings.doctype = doctype # Theme base settings if themeBase is not None: self.skinsSettings.theme = themeBase.encode('utf-8') if markSpecialLinks is not None: self.skinsSettings.mark_special_links = markSpecialLinks if extLinksOpenInNewWindow is not None: self.skinsSettings.ext_links_open_new_window = extLinksOpenInNewWindow if usePopups is not None: self.skinsSettings.use_popups = usePopups if iconVisibility is not None: self.skinsSettings.icon_visibility = iconVisibility.encode('utf-8') IStatusMessage(self.request).add(_(u"Changes saved")) self._setup() return True else: IStatusMessage(self.request).add(_(u"There were errors"), 'error') self.redirectToFieldset('advanced') return False if 'form.button.Import' in form: self.authorize() enableNewTheme = form.get('enableNewTheme', False) replaceExisting = form.get('replaceExisting', False) themeArchive = form.get('themeArchive', None) themeZip = None performImport = False try: themeZip = zipfile.ZipFile(themeArchive) except (zipfile.BadZipfile, zipfile.LargeZipFile,): logger.exception("Could not read zip file") self.errors['themeArchive'] = _('error_invalid_zip', default=u"The uploaded file is not a valid Zip archive" ) if themeZip: try: themeData = extractThemeInfo(themeZip, checkRules=False) except (ValueError, KeyError,), e: logger.warn(str(e)) self.errors['themeArchive'] = _('error_no_rules_file', u"The uploaded file does not contain " u"a valid theme archive." ) else: themeContainer = getOrCreatePersistentResourceDirectory() themeExists = themeData.__name__ in themeContainer if themeExists: if not replaceExisting: self.errors['themeArchive'] = \ _('error_already_installed', u"This theme is already installed. " u"Select 'Replace existing theme' " u"and re-upload to replace it." ) else: del themeContainer[themeData.__name__] performImport = True else: performImport = True if performImport: themeContainer.importZip(themeZip) themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, themeData.__name__) if themeDirectory is not None: # If we don't have a rules file, use the template if themeData.rules == u"/++%s++%s/%s" % (THEME_RESOURCE_NAME, themeData.__name__, RULE_FILENAME,): if not themeDirectory.isFile(RULE_FILENAME): templateThemeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, TEMPLATE_THEME) themeDirectory.writeFile(RULE_FILENAME, templateThemeDirectory.readFile(RULE_FILENAME)) if not themeDirectory.isFile(DEFAULT_THEME_FILENAME): IStatusMessage(self.request).add( _(u"A boilerplate rules.xml was added to your theme, but no index.html file found. Update rules.xml to reference the current theme file."), 'warning', ) plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if pluginSettings is not None: for name, plugin in plugins: plugin.onCreated(themeData.__name__, pluginSettings[name], pluginSettings) if enableNewTheme: applyTheme(themeData) self.settings.enabled = True if not self.errors: portalUrl = getToolByName(self.context, 'portal_url')() self.redirect( "%s/++theme++%s/@@theming-controlpanel-mapper" % ( portalUrl, themeData.__name__,) ) return False else: IStatusMessage(self.request).add( _(u"There were errors"), "error" ) self.renderOverlay('upload') return True
def save(self, value): """Save the rules file (AJAX request) """ processInputs(self.request) value = value.replace('\r\n', '\n') self.context.writeFile(RULE_FILENAME, value.encode('utf-8'))
def update(self): # XXX: complexity too high: refactoring needed processInputs(self.request) self._setup() self.errors = {} form = self.request.form if 'form.button.Cancel' in form: IStatusMessage(self.request).add(_(u"Changes cancelled")) portalUrl = getToolByName(self.context, 'portal_url')() self.redirect("{0:s}/@@overview-controlpanel".format(portalUrl)) return False if 'form.button.Enable' in form: self.authorize() themeSelection = form.get('themeName', None) if themeSelection: themeData = self.getThemeData(self.availableThemes, themeSelection) applyTheme(themeData) self.theme_settings.enabled = True IStatusMessage(self.request).add( _(u"Theme enabled. Note that this control panel page is " u"never themed.")) self._setup() return True if 'form.button.InvalidateCache' in form: self.authorize() policy = theming_policy() policy.invalidateCache() return True if 'form.button.Disable' in form: self.authorize() applyTheme(None) self.theme_settings.enabled = False IStatusMessage(self.request).add(_(u"Theme disabled.")) self._setup() return True if 'form.button.AdvancedSave' in form: self.authorize() self.theme_settings.readNetwork = form.get('readNetwork', False) themeEnabled = form.get('themeEnabled', False) rules = form.get('rules', None) prefix = form.get('absolutePrefix', None) doctype = str(form.get('doctype', "")) hostnameBlacklist = form.get('hostnameBlacklist', []) parameterExpressions = {} parameterExpressionsList = form.get('parameterExpressions', []) for line in parameterExpressionsList: try: name, expression = line.split('=', 1) name = str(name.strip()) expression = str(expression.strip()) parameterExpressions[name] = expression except ValueError: message = _( 'error_invalid_parameter_expressions', default=u"Please ensure you enter one expression per " u"line, in the format <name> = <expression>.") self.errors['parameterExpressions'] = message themeBase = form.get('themeBase', None) markSpecialLinks = form.get('markSpecialLinks', None) extLinksOpenInNewWindow = form.get('extLinksOpenInNewWindow', None) if not self.errors: # Trigger onDisabled() on plugins if theme was active # previously and rules were changed if self.theme_settings.rules != rules: applyTheme(None) self.theme_settings.enabled = themeEnabled self.theme_settings.rules = rules self.theme_settings.absolutePrefix = prefix self.theme_settings.parameterExpressions = parameterExpressions self.theme_settings.hostnameBlacklist = hostnameBlacklist self.theme_settings.doctype = doctype # Theme base settings if themeBase is not None: self.pskin.default_skin = themeBase.encode('utf-8') if markSpecialLinks is not None: self.mark_special_links = markSpecialLinks if extLinksOpenInNewWindow is not None: self.ext_links_open_new_window = extLinksOpenInNewWindow IStatusMessage(self.request).add(_(u"Changes saved")) self._setup() return True else: IStatusMessage(self.request).add(_(u"There were errors"), 'error') self.redirectToFieldset('advanced') return False if 'form.button.Import' in form: self.authorize() enableNewTheme = form.get('enableNewTheme', False) replaceExisting = form.get('replaceExisting', False) themeArchive = form.get('themeArchive', None) themeZip = None performImport = False try: themeZip = zipfile.ZipFile(themeArchive) except ( zipfile.BadZipfile, zipfile.LargeZipFile, ): logger.exception("Could not read zip file") self.errors['themeArchive'] = _( 'error_invalid_zip', default=u"The uploaded file is not a valid Zip archive") if themeZip: try: themeData = extractThemeInfo(themeZip, checkRules=False) except ( ValueError, KeyError, ), e: logger.warn(str(e)) self.errors['themeArchive'] = _( 'error_no_rules_file', u"The uploaded file does not contain a valid theme " u"archive.") else: themeContainer = getOrCreatePersistentResourceDirectory() themeExists = themeData.__name__ in themeContainer if themeExists: if not replaceExisting: self.errors['themeArchive'] = _( 'error_already_installed', u"This theme is already installed. Select " u"'Replace existing theme' and re-upload to " u"replace it.") else: del themeContainer[themeData.__name__] performImport = True else: performImport = True if performImport: themeContainer.importZip(themeZip) themeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, themeData.__name__) if themeDirectory is not None: # If we don't have a rules file, use the template if themeData.rules == u"/++{0:s}++{1:s}/{2:s}".format( THEME_RESOURCE_NAME, themeData.__name__, RULE_FILENAME, ) and not themeDirectory.isFile(RULE_FILENAME): templateThemeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, TEMPLATE_THEME) themeDirectory.writeFile( RULE_FILENAME, templateThemeDirectory.readFile(RULE_FILENAME)) if not themeDirectory.isFile(DEFAULT_THEME_FILENAME): IStatusMessage(self.request).add( _(u"A boilerplate rules.xml was added to " u"your theme, but no index.html file " u"found. Update rules.xml to reference " u"the current theme file."), 'warning', ) plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if pluginSettings is not None: for name, plugin in plugins: plugin.onCreated(themeData.__name__, pluginSettings[name], pluginSettings) if enableNewTheme: applyTheme(themeData) self.theme_settings.enabled = True if not self.errors: portalUrl = getToolByName(self.context, 'portal_url')() self.redirect( "{0}/++theme++{1}/@@theming-controlpanel-mapper".format( portalUrl, themeData.__name__)) return False else: IStatusMessage(self.request).add(_(u"There were errors"), "error") self.renderOverlay('upload') return True
def update(self): decode.processInputs(self.request) decode.setPageEncoding(self.request) orig(self)
def update( self ): if not getattr( self.request, '__inputs_processed', False ): decode.processInputs( self.request ) decode.setPageEncoding( self.request ) self.request.__inputs_processed = True super( FiveFormlibMixin, self).update()
def getFrame(self): """AJAX method to load a frame's contents Expects two query string parameters: ``path`` - the path to fetch - and ``theme``, which can be 'off', to disable the theme and 'apply' to apply the current theme to the response. Additionally: - a query string parameter ``links`` can be set to one of ``disable`` or ``replace``. The former will disable hyperlinks; the latter will replace them with links using the ``@@themeing-controlpanel-getframe`` view. - a query string parameter ``forms`` can be set to one of ``disable`` or ``replace``. The former will disable forms ; the latter will replace them with links using the ``@@themeing-controlpanel-getframe`` view. - a query string parameter ``title`` can be set to give a new page title """ processInputs(self.request) path = self.request.form.get('path', None) theme = self.request.form.get('theme', 'off') links = self.request.form.get('links', None) forms = self.request.form.get('forms', None) title = self.request.form.get('title', None) if not path: return "<html><head></head><body></body></html>" portal = getPortal() portal_url = portal.absolute_url() response = subrequest(path, root=portal) result = response.getBody() content_type = response.headers.get('content-type') encoding = None if content_type is not None and ';' in content_type: content_type, encoding = content_type.split(';', 1) if encoding is None: encoding = 'utf-8' else: # e.g. charset=utf-8 encoding = encoding.split('=', 1)[1].strip() # Not HTML? Return as-is if content_type is None or not content_type.startswith('text/html'): if len(result) == 0: result = ' ' # Zope does not deal well with empty responses return result result = result.decode(encoding).encode('ascii', 'xmlcharrefreplace') if len(result) == 0: result = ' ' # Zope does not deal well with empty responses if theme == 'off': self.request.response.setHeader('X-Theme-Disabled', '1') elif theme == 'apply': self.request.response.setHeader('X-Theme-Disabled', '1') themeInfo = getThemeFromResourceDirectory(self.context) policy = theming_policy(self.request) settings = policy.getSettings() context = self.context try: context = findContext(portal.restrictedTraverse(path)) except (KeyError, NotFound,): pass serializer = getHTMLSerializer([result], pretty_print=False) try: transform = compileThemeTransform( themeInfo.rules, themeInfo.absolutePrefix, settings.readNetwork, themeInfo.parameterExpressions or {}) except lxml.etree.XMLSyntaxError as e: return self.theme_error_template(error=e.msg) params = prepareThemeParameters( context, self.request, themeInfo.parameterExpressions or {}) # Fix url and path since the request gave us this view params['url'] = quote_param(''.join((portal_url, path,))) params['path'] = quote_param( ''.join((portal.absolute_url_path(), path,)) ) if themeInfo.doctype: serializer.doctype = themeInfo.doctype if not serializer.doctype.endswith('\n'): serializer.doctype += '\n' serializer.tree = transform(serializer.tree, **params) result = ''.join(serializer) if title or links or forms: tree = lxml.html.fromstring(result) def encodeUrl(orig): origUrl = urllib.parse.urlparse(orig) newPath = origUrl.path newQuery = urllib.parse.parse_qs(origUrl.query) # relative? if not origUrl.netloc: newPath = urllib.parse.urljoin( path.rstrip("/") + "/", newPath.lstrip("/")) elif not orig.lower().startswith(portal_url.lower()): # Not an internal URL - ignore return orig newQuery['path'] = newPath newQuery['theme'] = theme if links: newQuery['links'] = links if forms: newQuery['forms'] = forms if title: if isinstance(title, six.text_type): newQuery['title'] = title.encode('utf-8', 'replace') else: newQuery['title'] = title return self.request.getURL() + '?' + urllib.parse.urlencode(newQuery) if title: titleElement = tree.cssselect("html head title") if titleElement: titleElement[0].text = title else: headElement = tree.cssselect("html head") if headElement: headElement[0].append(lxml.html.builder.TITLE(title)) if links: for n in tree.cssselect("a[href]"): if links == 'disable': n.attrib['href'] = '#' elif links == 'replace': n.attrib['href'] = encodeUrl(n.attrib['href']) if forms: for n in tree.cssselect("form[action]"): if forms == 'disable': n.attrib['action'] = '#' n.attrib['onsubmit'] = 'javascript:return false;' elif forms == 'replace': n.attrib['action'] = encodeUrl(n.attrib['action']) result = lxml.html.tostring(tree) return result