def setupIcon(klass, icon, repository): """Load icon into Zope image object and put it in Zope's repository for use by the ZMI, for a particular class. klass -- the class of the field we're adding icon -- the icon """ # set up misc_ respository if not existing yet if not hasattr(OFS.misc_.misc_, repository): setattr(OFS.misc_.misc_, repository, OFS.misc_.Misc_(repository, {})) # get name of icon in the misc_ directory icon_name = os.path.split(icon)[1] # set up image object from icon file icon_image = ImageFile(icon, globals()) icon_image.__roles__ = None # put icon image object in misc_/Formulator/ getattr(OFS.misc_.misc_, repository)[icon_name] = icon_image # set icon attribute in field_class to point to this image obj setattr(klass, 'icon', 'misc_/%s/%s' % (repository, icon_name))
def registerImage(filepath, s): """ manual icon registration """ icon = ImageFile(filepath, globals()) icon.__roles__ = None OFS.misc_.misc_.zms[s] = icon
def createIcon(iconspec, _prefix, pid): name = os.path.split(iconspec)[1] res = 'misc_/%s/%s' % (pid, name) icon = ImageFile(iconspec, _prefix) icon.__roles__ = None if not hasattr(OFS.misc_.misc_, pid): setattr(OFS.misc_.misc_, pid, OFS.misc_.Misc_(pid, {})) getattr(OFS.misc_.misc_, pid)[name] = icon return res
def createIcon(iconspec, _prefix, pid=_prodname): name = os.path.split(iconspec)[1] res = 'misc_/%s/%s' % (pid, name) icon = ImageFile(iconspec, _prefix) icon.__roles__=None if not hasattr(OFS.misc_.misc_, pid): setattr(OFS.misc_.misc_, pid, OFS.misc_.Misc_(pid, {})) getattr(OFS.misc_.misc_, pid)[name]=icon return res
def __init__(self, id, title, file, categories=None, permissions=None): self.id=id self.title=title self.file = file self.obj=open(file).read() self._set_last_read(file) dir, file=os.path.split(file) self.image=ImageFile(file, dir) if permissions is not None: self.permissions=permissions if categories is not None: self.categories=categories
class ImageTopic(HelpTopic): """ A image Help Topic. Holds an ImageFile object. """ meta_type='Help Image' def __init__(self, id, title, file, categories=None, permissions=None): self.id=id self.title=title self.file = file self.obj=open(file).read() self._set_last_read(file) dir, file=os.path.split(file) self.image=ImageFile(file, dir) if permissions is not None: self.permissions=permissions if categories is not None: self.categories=categories def index_html(self, REQUEST, RESPONSE): "View the Help Topic" self._check_for_update() return self.image.index_html(REQUEST, RESPONSE) def SearchableText(self): "The full text of the Help Topic, for indexing purposes" return ''
def view(self, REQUEST, display='', **kwargs): """ """ if not self.displays.has_key(display): if not LISTING_DISPLAYS.has_key(display): if self.check_view_photo_permission('Original'): display = 'Original' elif display == 'Original': raise Unauthorized else: display = 'Medium' if self.aq_parent.watermark_text: watermark = True else: watermark = False try: photo = self._getDisplay(display, watermark) except: self.log_current_error() return ImageFile('www/broken_image.gif', globals()).index_html(REQUEST, REQUEST.RESPONSE) result = photo.index_html(REQUEST=REQUEST) if hasattr(photo, '_blob'): # compatibility with non-migrated extfile storage # The next two lines are used to avoid a "blob file is opened" error # at the end of the transaction for fr in photo._blob.readers: photo._blob.readers.remove(fr) return result
def registerIcon(klass, iconspec, _prefix=None): """ Make an icon available for a given class. o 'klass' is the class being decorated. o 'iconspec' is the path within the product where the icon lives. """ modname = klass.__module__ pid = modname.split('.')[1] name = os_path.split(iconspec)[1] klass.icon = 'misc_/%s/%s' % (pid, name) icon = ImageFile(iconspec, _prefix) icon.__roles__ = None if not hasattr(misc_images, pid): setattr(misc_images, pid, MiscImage(pid, {})) getattr(misc_images, pid)[name] = icon
class p_: "Shared system information" security = ClassSecurityInfo() security.declareObjectPublic() app_dir = dirname(App.__file__) zopelogo_png = ImageFile('www/zopelogo.png', app_dir)
class ImageTopic(HelpTopic): """ A image Help Topic. Holds an ImageFile object. """ meta_type = "Help Image" def __init__(self, id, title, file, categories=None, permissions=None): self.id = id self.title = title self.file = file self.obj = open(file).read() self._set_last_read(file) dir, file = os.path.split(file) self.image = ImageFile(file, dir) if permissions is not None: self.permissions = permissions if categories is not None: self.categories = categories def index_html(self, REQUEST, RESPONSE): "View the Help Topic" self._check_for_update() return self.image.index_html(REQUEST, RESPONSE) def SearchableText(self): "The full text of the Help Topic, for indexing purposes" return ""
class _(PatchClass(PythonScript)): security = ClassSecurityInfo() # Add proxy role icon in ZMI def om_icons(self): """Return a list of icon URLs to be displayed by an ObjectManager""" if self._proxy_roles: return { 'path': 'p_/PythonScript_ProxyRole_icon', 'alt': 'Proxy Roled Python Script', 'title': 'This script has proxy role.' }, return { 'path': 'misc_/PythonScripts/pyscript.gif', 'alt': self.meta_type, 'title': self.meta_type }, p_.PythonScript_ProxyRole_icon = \ ImageFile('pyscript_proxyrole.gif', globals()) # Patch for displaying textearea in full window instead of # remembering a quantity of lines to display in a cookie manage = manage_editDocument = manage_main = ZPythonScriptHTML_editForm = \ manage_editForm = DTMLFile("pyScriptEdit", _dtmldir) manage_editForm._setName('manage_editForm') # Guards def __call__(self, *args, **kw): '''Calls the script.''' self.checkGuard(True) # patch return self._orig_bindAndExec(args, kw, None) security.declarePublic("render") render = __call__ # For __render_with_namespace__ (we prefer to monkey-patch __call__ # because it's called more often, and this makes debugging easier) _orig_bindAndExec = PythonScript._bindAndExec def _bindAndExec(self, args, kw, caller_namespace): return self(*args, **kw) # caller_namespace not used by PythonScript ## WITH_LEGACY_WORKFLOW def getReference(self): return self.id # Following methods are necessary for Workflow showAsXML() function def getBody(self): return self._body def getParams(self): return self._params def getProxyRole(self): return self._proxy_roles
def registerIcon(filename): from OFS import misc_ try: info = misc_.misc_.ZopeVersionControl except AttributeError: # Zope trunk return setattr(info, filename, ImageFile('www/%s' % filename, globals()))
def registerIcon(klass, iconspec, _prefix=None): """ Make an icon available for a given class. o 'klass' is the class being decorated. o 'iconspec' is the path within the product where the icon lives. """ modname = klass.__module__ pid = modname.split('.')[1] name = os_path.split(iconspec)[1] klass.icon = 'misc_/%s/%s' % (pid, name) icon = ImageFile(iconspec, _prefix) icon.__roles__=None if not hasattr(misc_images, pid): setattr(misc_images, pid, MiscImage(pid, {})) getattr(misc_images, pid)[name]=icon
class GoogleMapEngine(SimpleItem): """ Google maps plugin for Naaya GeoMapTool """ name = "google" title = u"Google maps" security = ClassSecurityInfo() def __init__(self, id): super(GoogleMapEngine, self).__init__() self._setId(id) self.api_keys = DEFAULT_API_KEY self.base_layer = 'map' self.allow_mouse_scroll = True self.portal_map_zoom = None _html_setup = PageTemplateFile('setup', globals()) security.declarePrivate('html_setup') def html_setup(self, request, global_config): js_config = { 'base_layer': self.base_layer, 'allow_mouse_scroll': self.allow_mouse_scroll, 'portal_map_zoom': self.portal_map_zoom, } js_config.update(global_config) options = { 'apikey': pick_api_key(self.api_keys, request), 'js_config': json.dumps(js_config), } return self._html_setup(**options) _config_html = PageTemplateFile('configure', globals()) security.declarePrivate('config_html') def config_html(self): return self._config_html(all_layers=[ {'name': 'map', 'label': "Streets"}, {'name': 'hybrid', 'label': "Hybrid"}, {'name': 'physical', 'label': "Physical"}, {'name': 'satellite', 'label': "Satellite"}]) security.declarePrivate('save_config') def save_config(self, form_data): self.api_keys = form_data['google_api_keys'] self.allow_mouse_scroll = form_data.get( 'google_allow_mouse_scroll', False) self.base_layer = form_data['google_base_layer'] try: zoom = int(form_data.get('google_portal_map_zoom', None)) except: zoom = None self.portal_map_zoom = zoom security.declareProtected(view, 'naaya_google_js') naaya_google_js = ImageFile('naaya_google.js', globals())
def getIcon(self, context, path): pack = self.getPack(context) icon = None # This variable is just used for the log message icon_path = path try: icon = ImageFile(path, pack.__dict__) except (IOError, OSError): # Fallback: # Assume path is relative to CMFPlone directory path = abspath(join(PACKAGE_HOME, path)) try: icon = ImageFile(path, pack.__dict__) except (IOError, OSError): # if there is some problem loading the fancy image # from the tool then tell someone about it log(('The icon for the product: %s which was set to: %s, ' 'was not found. Using the default.' % (self.product_name, icon_path))) return icon
class YahooMapEngine(SimpleItem): """ Yahoo maps plugin for Naaya GeoMapTool """ name = "yahoo" title = u"Yahoo maps" security = ClassSecurityInfo() def __init__(self, id): super(YahooMapEngine, self).__init__() self._setId(id) self.api_keys = ("m.6kzBLV34FOaYaMCfIKBRHIIYE8zCf6c6" "yxcc5rZCWkCilWFPzAhcyQEcRTgYKy5g--") self.base_layer = 'map' _html_setup = PageTemplateFile('setup', globals()) security.declarePrivate('html_setup') def html_setup(self, request, global_config): js_config = { 'base_layer': self.base_layer, } js_config.update(global_config) options = { 'apikey': pick_api_key(self.api_keys, request), 'js_config': json.dumps(js_config), } return self._html_setup(**options) _config_html = PageTemplateFile('configure', globals()) security.declarePrivate('config_html') def config_html(self): return self._config_html(all_layers=[{ 'name': 'map', 'label': "Streets" }, { 'name': 'hybrid', 'label': "Hybrid" }, { 'name': 'satellite', 'label': "Satellite" }]) security.declarePrivate('save_config') def save_config(self, form_data): self.base_layer = form_data['yahoo_base_layer'] self.api_keys = form_data['yahoo_api_keys'] security.declareProtected(view, 'naaya_yahoo_js') naaya_yahoo_js = ImageFile('naaya_yahoo.js', globals())
def __init__(self, id, title, file, categories=None, permissions=None): self.id = id self.title = title self.file = file self.obj = open(file).read() self._set_last_read(file) dir, file = os.path.split(file) self.image = ImageFile(file, dir) if permissions is not None: self.permissions = permissions if categories is not None: self.categories = categories
class BingMapEngine(SimpleItem): """ Bing maps plugin for Naaya GeoMapTool """ name = "bing" title = u"Bing maps" security = ClassSecurityInfo() # default values base_layer = 'Road' def __init__(self, id): super(BingMapEngine, self).__init__() self._setId(id) _html_setup = PageTemplateFile('setup', globals()) security.declarePrivate('html_setup') def html_setup(self, request, global_config): js_config = { 'base_layer': self.base_layer, } js_config.update(global_config) options = { 'js_config': json.dumps(js_config), } return self._html_setup(**options) _config_html = PageTemplateFile('configure', globals()) security.declarePrivate('config_html') def config_html(self): return self._config_html(all_layers=[{ 'name': 'Road', 'label': "Road" }, { 'name': 'Hybrid', 'label': "Hybrid" }, { 'name': 'Aerial', 'label': "Aerial" }]) security.declarePrivate('save_config') def save_config(self, form_data): self.base_layer = form_data['bing_base_layer'] security.declareProtected(view, 'naaya_bing_js') naaya_bing_js = ImageFile('naaya_bing.js', globals())
def view(self, REQUEST, display='', **kwargs): """ """ if not self.displays.has_key(display): if not LISTING_DISPLAYS.has_key(display): if self.check_view_photo_permission('Original'): display = 'Original' elif display == 'Original': raise Unauthorized else: display = 'Medium' if self.aq_parent.watermark_text: watermark = True else: watermark = False try: photo = self._getDisplay(display, watermark) except: self.log_current_error() return ImageFile('www/broken_image.gif', globals()).index_html(REQUEST, REQUEST.RESPONSE) return photo.index_html(REQUEST=REQUEST)
class PluginRegistry(SimpleItem): """ Implement IPluginRegistry as an independent, ZMI-manageable object. o Each plugin type holds an ordered list of (id, wrapper) tuples. """ implements(IPluginRegistry, IWriteLock) security = ClassSecurityInfo() meta_type = 'Plugin Registry' _plugins = None def __init__(self, plugin_type_info=()): if isinstance(plugin_type_info, basestring): # some tool is passing us our ID. raise ValueError('Must pass a sequence of plugin info dicts!') self._plugin_types = [x[0] for x in plugin_type_info] self._plugin_type_info = PersistentMapping() for interface in plugin_type_info: self._plugin_type_info[interface[0]] = { 'id': interface[1], 'title': interface[2], 'description': interface[3] } # # IPluginRegistry implementation # security.declareProtected(ManageUsers, 'listPluginTypeInfo') def listPluginTypeInfo(self): """ See IPluginRegistry. """ result = [] for ptype in self._plugin_types: info = self._plugin_type_info[ptype].copy() info['interface'] = ptype info['methods'] = ptype.names() result.append(info) return result security.declareProtected(ManageUsers, 'listPlugins') def listPlugins(self, plugin_type): """ See IPluginRegistry. """ result = [] parent = aq_parent(aq_inner(self)) for plugin_id in self._getPlugins(plugin_type): plugin = parent._getOb(plugin_id) if not _satisfies(plugin, plugin_type): logger.debug('Active plugin %s no longer implements %s' % (plugin_id, plugin_type)) else: result.append((plugin_id, plugin)) return result security.declareProtected(ManageUsers, 'getPluginInfo') def getPluginInfo(self, plugin_type): """ See IPluginRegistry. """ plugin_type = self._getInterfaceFromName(plugin_type) return self._plugin_type_info[plugin_type] security.declareProtected(ManageUsers, 'listPluginIds') def listPluginIds(self, plugin_type): """ See IPluginRegistry. """ return self._getPlugins(plugin_type) security.declareProtected(ManageUsers, 'activatePlugin') def activatePlugin(self, plugin_type, plugin_id): """ See IPluginRegistry. """ plugins = list(self._getPlugins(plugin_type)) if plugin_id in plugins: raise KeyError, 'Duplicate plugin id: %s' % plugin_id parent = aq_parent(aq_inner(self)) plugin = parent._getOb(plugin_id) if not _satisfies(plugin, plugin_type): raise ValueError, 'Plugin does not implement %s' % plugin_type plugins.append(plugin_id) self._plugins[plugin_type] = tuple(plugins) security.declareProtected(ManageUsers, 'deactivatePlugin') def deactivatePlugin(self, plugin_type, plugin_id): """ See IPluginRegistry. """ plugins = list(self._getPlugins(plugin_type)) if not plugin_id in plugins: raise KeyError, 'Invalid plugin id: %s' % plugin_id plugins = [x for x in plugins if x != plugin_id] self._plugins[plugin_type] = tuple(plugins) security.declareProtected(ManageUsers, 'movePluginsUp') def movePluginsUp(self, plugin_type, ids_to_move): """ See IPluginRegistry. """ ids = list(self._getPlugins(plugin_type)) count = len(ids) indexes = list(map(ids.index, ids_to_move)) indexes.sort() for i1 in indexes: if i1 < 0 or i1 >= count: raise IndexError, i1 i2 = i1 - 1 if i2 < 0: # i1 is already on top continue ids[i2], ids[i1] = ids[i1], ids[i2] self._plugins[plugin_type] = tuple(ids) security.declareProtected(ManageUsers, 'movePluginsDown') def movePluginsDown(self, plugin_type, ids_to_move): """ See IPluginRegistry. """ ids = list(self._getPlugins(plugin_type)) count = len(ids) indexes = list(map(ids.index, ids_to_move)) indexes.sort() indexes.reverse() for i1 in indexes: if i1 < 0 or i1 >= count: raise IndexError, i1 i2 = i1 + 1 if i2 == len(ids): # i1 is already on the bottom continue ids[i2], ids[i1] = ids[i1], ids[i2] self._plugins[plugin_type] = tuple(ids) # # ZMI # arrow_right_gif = ImageFile('www/arrow-right.gif', globals()) arrow_left_gif = ImageFile('www/arrow-left.gif', globals()) arrow_up_gif = ImageFile('www/arrow-up.gif', globals()) arrow_down_gif = ImageFile('www/arrow-down.gif', globals()) security.declareProtected(ManageUsers, 'manage_activatePlugins') def manage_activatePlugins(self, plugin_type, plugin_ids, RESPONSE): """ Shim into ZMI. """ interface = self._getInterfaceFromName(plugin_type) for id in plugin_ids: self.activatePlugin(interface, id) RESPONSE.redirect('%s/manage_plugins?plugin_type=%s' % (self.absolute_url(), plugin_type)) security.declareProtected(ManageUsers, 'manage_deactivatePlugins') def manage_deactivatePlugins(self, plugin_type, plugin_ids, RESPONSE): """ Shim into ZMI. """ interface = self._getInterfaceFromName(plugin_type) for id in plugin_ids: self.deactivatePlugin(interface, id) RESPONSE.redirect('%s/manage_plugins?plugin_type=%s' % (self.absolute_url(), plugin_type)) security.declareProtected(ManageUsers, 'manage_movePluginsUp') def manage_movePluginsUp(self, plugin_type, plugin_ids, RESPONSE): """ Shim into ZMI. """ interface = self._getInterfaceFromName(plugin_type) self.movePluginsUp(interface, plugin_ids) RESPONSE.redirect('%s/manage_plugins?plugin_type=%s' % (self.absolute_url(), plugin_type)) security.declareProtected(ManageUsers, 'manage_movePluginsDown') def manage_movePluginsDown(self, plugin_type, plugin_ids, RESPONSE): """ Shim into ZMI. """ interface = self._getInterfaceFromName(plugin_type) self.movePluginsDown(interface, plugin_ids) RESPONSE.redirect('%s/manage_plugins?plugin_type=%s' % (self.absolute_url(), plugin_type)) security.declareProtected(ManageUsers, 'getAllPlugins') def getAllPlugins(self, plugin_type): """ Return a mapping segregating active / available plugins. 'plugin_type' is the __name__ of the interface. """ interface = self._getInterfaceFromName(plugin_type) active = self._getPlugins(interface) available = [] for id, value in aq_parent(aq_inner(self)).objectItems(): if _satisfies(value, interface): if id not in active: available.append(id) return {'active': active, 'available': available} security.declareProtected(ManageUsers, 'removePluginById') def removePluginById(self, plugin_id): """ Remove a plugin from any plugin types which have it configured. """ for plugin_type in self._plugin_types: if plugin_id in self._getPlugins(plugin_type): self.deactivatePlugin(plugin_type, plugin_id) security.declareProtected(ManageUsers, 'manage_plugins') manage_plugins = PageTemplateFile('plugins', _wwwdir) security.declareProtected(ManageUsers, 'manage_active') manage_active = PageTemplateFile('active_plugins', _wwwdir) manage_twoLists = PageTemplateFile('two_lists', _wwwdir) manage_options = (( { 'label': 'Plugins', 'action': 'manage_plugins' # , 'help' : ('PluggableAuthService' # , 'plugins.stx') }, { 'label': 'Active', 'action': 'manage_active' }) + SimpleItem.manage_options) if _HAS_GENERIC_SETUP: security.declareProtected(ManageUsers, 'manage_exportImportForm') manage_exportImportForm = PageTemplateFile('export_import', _wwwdir) security.declareProtected(ManageUsers, 'getConfigAsXML') def getConfigAsXML(self): """ Return XML representing the registry's configuration. """ from exportimport import PluginRegistryExporter pre = PluginRegistryExporter(self).__of__(self) return pre.generateXML() security.declareProtected(ManageUsers, 'manage_exportImport') def manage_exportImport(self, updated_xml, should_purge, RESPONSE): """ Parse XML and update the registry. """ #XXX encoding? _updatePluginRegistry(self, updated_xml, should_purge) RESPONSE.redirect('%s/manage_exportImportForm' '?manage_tabs_message=Registry+updated.' % self.absolute_url()) security.declareProtected(ManageUsers, 'manage_FTPget') def manage_FTPget(self, REQUEST, RESPONSE): """ """ return self.getConfigAsXML() security.declareProtected(ManageUsers, 'PUT') def PUT(self, REQUEST, RESPONSE): """ """ xml = REQUEST['BODYFILE'].read() _updatePluginRegistry(self, xml, True) manage_options = (manage_options[:2] + ({ 'label': 'Export / Import', 'action': 'manage_exportImportForm' }, ) + manage_options[2:]) # # Helper methods # security.declarePrivate('_getPlugins') def _getPlugins(self, plugin_type): parent = aq_parent(aq_inner(self)) if plugin_type not in self._plugin_types: raise KeyError, plugin_type if self._plugins is None: self._plugins = PersistentMapping() return self._plugins.setdefault(plugin_type, ()) security.declarePrivate('_getInterfaceFromName') def _getInterfaceFromName(self, plugin_type_name): """ Convert the string name to an interface. o Raise KeyError is no such interface is known. """ found = [ x[0] for x in self._plugin_type_info.items() if x[1]['id'] == plugin_type_name ] if not found: raise KeyError, plugin_type_name if len(found) > 1: raise KeyError, 'Waaa!: %s' % plugin_type_name return found[0]
config = { 'product': 'NaayaContent', 'module': 'NyNetwork', 'package_path': os.path.abspath(os.path.dirname(__file__)), 'meta_type': METATYPE_OBJECT, 'label': LABEL_OBJECT, 'permission': PERMISSION_ADD_INFO, 'forms': OBJECT_FORMS, 'add_form': OBJECT_ADD_FORM, 'description': DESCRIPTION_OBJECT, 'default_schema': DEFAULT_SCHEMA, 'schema_name': 'NyNetwork', '_module': sys.modules[__name__], 'icon': os.path.join(os.path.dirname(__file__), 'www', 'NyInfo.gif'), '_misc': { 'NyInfo.gif': ImageFile('www/NyInfo.gif', globals()), 'NyInfo_marked.gif': ImageFile('www/NyInfo_marked.gif', globals()), }, } def network_add_html(self, REQUEST=None, RESPONSE=None): """ """ form_helper = get_schema_helper_for_metatype(self, METATYPE_OBJECT) return self.getFormsTool().getContent({'here': self, 'kind': METATYPE_OBJECT, 'action': 'addNyNetwork', 'form_helper': form_helper}, 'sdo_info_add') def _create_object(parent, id, title, contributor): ob = NyNetwork(id, title, contributor) parent.gl_add_languages(ob) parent._setObject(id, ob) ob = parent._getOb(id)
class p_: "Shared system information" security = ClassSecurityInfo() security.declareObjectPublic() broken = ImageFile('www/broken.gif', globals()) User_icon = ImageFile('AccessControl/www/User_icon.gif') locked = ImageFile('www/modified.gif', globals()) lockedo = ImageFile('www/locked.gif', globals()) davlocked = ImageFile('webdav/www/davlock.gif') pl = ImageFile('TreeDisplay/www/Plus_icon.gif') mi = ImageFile('TreeDisplay/www/Minus_icon.gif') rtab = ImageFile('App/www/rtab.gif') ltab = ImageFile('App/www/ltab.gif') sp = ImageFile('App/www/sp.gif') r_arrow_gif = ImageFile('www/r_arrow.gif', globals()) l_arrow_gif = ImageFile('www/l_arrow.gif', globals()) ControlPanel_icon = ImageFile('OFS/www/ControlPanel_icon.gif') ApplicationManagement_icon = ImageFile('App/www/cpSystem.gif') DatabaseManagement_icon = ImageFile('App/www/dbManage.gif') VersionManagement_icon = ImageFile('App/www/vManage.gif') DebugManager_icon = ImageFile('App/www/DebugManager_icon.gif') InstalledProduct_icon = ImageFile('App/www/installedProduct.gif') BrokenProduct_icon = ImageFile('App/www/brokenProduct.gif') Product_icon = ImageFile('App/www/product.gif') Factory_icon = ImageFile('App/www/factory.gif') Permission_icon = ImageFile('App/www/permission.gif') ProductFolder_icon = ImageFile('App/www/productFolder.gif') PyPoweredSmall_Gif = ImageFile('App/www/PythonPoweredSmall.gif') ZopeButton = ImageFile('App/www/zope_button.jpg') ZButton = ImageFile('App/www/z_button.jpg') zopelogo_jpg = ImageFile('App/www/zopelogo.jpg') Properties_icon = ImageFile('OFS/www/Properties_icon.gif') Methods_icon = ImageFile('ZClasses/methods.gif') Propertysheets_icon = ImageFile('ZClasses/propertysheets.gif') ProductHelp_icon = ImageFile('HelpSys/images/productHelp.gif') HelpTopic_icon = ImageFile('HelpSys/images/helpTopic.gif')
class MegaSurvey(SurveyQuestionnaire, BaseSurveyTemplate): """ """ meta_type = 'Naaya Mega Survey' meta_label = 'Survey' _constructors = (manage_addMegaSurvey, ) security = ClassSecurityInfo() edit_access = NyAccess( 'edit_access', { PERMISSION_ADD_ANSWER: "Submit answer", PERMISSION_ADD_REPORT: "Create report", PERMISSION_ADD_ATTACHMENT: "Attach file", PERMISSION_VIEW_ANSWERS: "View answers", PERMISSION_EDIT_ANSWERS: "Edit answers", PERMISSION_VIEW_REPORTS: "View reports", }) def __init__(self, id, **kwargs): """ """ # BaseSurveyTemplate.__init__(self, id, **kwargs) SurveyQuestionnaire.__init__(self, id, None, **kwargs) self.contributor = kwargs.get('contributor') self.approved = 1 def can_be_seen(self): """ Indicates if the current user has access to the current folder. """ return self.checkPermission(view) def all_meta_types(self, interfaces=None): """What can you put inside me?""" return BaseSurveyTemplate.all_meta_types(self, interfaces) def getSurveyTemplate(self): """ """ return self security.declareProtected(view, 'download') def download(self, REQUEST=None, RESPONSE=None): """returns all the answers in a csv file""" def stringify(value): if not isinstance(value, basestring): value = unicode(value) if isinstance(value, str): return unicode(value, 'utf-8') return value def all_stringify(row): return [stringify(value) for value in row] answers = self.getAnswers() widgets = self.getSortedWidgets() header = ['Respondent'] for widget in widgets: header += [widget.title_or_id()] if widget.meta_type == 'Naaya Radio Matrix Widget': header += widget.rows rows = [answer.answer_values() for answer in answers] rows = [all_stringify(item) for item in rows] file_type = REQUEST.get('file_type', 'CSV') if file_type == 'CSV': RESPONSE.setHeader('Content-Type', 'text/csv') RESPONSE.setHeader('Content-Disposition', 'attachment; filename=%s.csv' % self.id) return generate_csv(header, rows) if file_type == 'Excel' and self.rstk.we_provide('Excel export'): RESPONSE.setHeader('Content-Type', 'application/vnd.ms-excel') RESPONSE.setHeader('Content-Disposition', 'attachment; filename=%s.xls' % self.id) return generate_excel(header, rows) else: raise ValueError('unknown file format %r' % file_type) # # Site pages # security.declareProtected(view, 'index_html') def index_html(self): """ """ if (not self.checkPermissionSkipCaptcha() and not self.recaptcha_is_present()): raise ValueError("Invalid recaptcha keys") return self._index_html() _index_html = NaayaPageTemplateFile('zpt/megasurvey_index', globals(), 'NaayaSurvey.megasurvey_index') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html') edit_html = NaayaPageTemplateFile('zpt/megasurvey_edit', globals(), 'NaayaSurvey.megasurvey_edit') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_attachments_html') edit_attachments_html = NaayaPageTemplateFile( 'zpt/megasurvey_edit_attachments', globals(), 'NaayaSurvey.megasurvey_edit_attachments') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_questions_html') edit_questions_html = NaayaPageTemplateFile( 'zpt/megasurvey_edit_questions', globals(), 'NaayaSurvey.megasurvey_edit_questions') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_reports_html') edit_reports_html = NaayaPageTemplateFile( 'zpt/megasurvey_edit_reports', globals(), 'NaayaSurvey.megasurvey_edit_reports') # # change the security of the inherited methods # security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'addWidget') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteItems') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'setSortOrder') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'addReport') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'generateFullReport') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'addAttachment') # static files css_survey_common = DTMLFile('www/survey_common.css', globals()) css_survey_print = DTMLFile('www/survey_print.css', globals()) fancy_checkmark = ImageFile('www/fancy_checkmark.gif', globals()) survey_js = ImageFile('www/survey.js', globals()) security.declareProtected(PERMISSION_EDIT_ANSWERS, 'bogus') def bogus(self): """ Needed in Naaya Access. It is mandatory that a permission must be declared so it can be used in Naaya Access. This should be removed once this issue is solved """ pass security.declarePublic('display_admin_warning') def display_admin_warning(self): return self.checkPermissionPublishObjects()\ and self.anonymous_has_access()\ and not self.recaptcha_is_present()\ and not self.anonymous_skips_captcha() security.declarePublic('anonymous_has_access') def anonymous_has_access(self): return 'Anonymous' in self.edit_access.getPermissionMapping( )['Naaya - Add Naaya Survey Answer'] security.declarePublic('anonymous_skips_captcha') def anonymous_skips_captcha(self): permission = 'Naaya - Skip Captcha' permission_object = Permission(permission, (), self) return 'Anonymous' in permission_object.getRoles() security.declarePrivate('dont_inherit_view_permission') def dont_inherit_view_permission(self): permission = Permission(view, (), self) roles = permission.getRoles() roles = tuple(set(roles) | set(['Manager', 'Administrator', 'Owner'])) permission.setRoles(roles) security.declarePrivate('inherit_view_permission') def inherit_view_permission(self): permission = Permission(view, (), self) roles = permission.getRoles() roles = list(roles) permission.setRoles(roles)
# ############################################################################## # Zope External Editor Product by Casey Duncan from App.ImageFile import ImageFile from App.special_dtml import DTMLFile from OFS.ObjectManager import ObjectManager from OFS.FindSupport import FindSupport from OFS.Folder import Folder from App.Management import Tabs from ExternalEditor import ExternalEditor, EditLink # Add the icon and the edit method to the misc_ namespace misc_ = {'edit_icon': ImageFile('edit_icon.gif', globals())} # Insert the global external editor resources Folder.externalEdit_ = ExternalEditor() Folder.externalEditLink_ = EditLink # Monkey patch in our manage_main for Object Manager ObjectManager.manage_main = DTMLFile('manage_main', globals()) # Add our patch for the find results template FindSupport.manage_findResult = DTMLFile('findResult', globals(), management_view='Find') # Add external editor icon in breadcrumbs under tabs Tabs.manage_tabs = DTMLFile('manage_tabs', globals())
class PluggableAuthService(Folder, Cacheable): """ All-singing, all-dancing user folder. """ security = ClassSecurityInfo() meta_type = 'Pluggable Auth Service' _id = id = 'acl_users' _emergency_user = emergency_user _nobody = nobody maxlistusers = -1 # Don't allow local role form to try to list us! def getId(self): return self._id # # IUserFolder implementation # security.declareProtected(ManageUsers, 'getUser') def getUser(self, name): """ See IUserFolder. """ plugins = self._getOb('plugins') user_info = self._verifyUser(plugins, login=name) if not user_info: return None return self._findUser(plugins, user_info['id'], user_info['login']) security.declareProtected(ManageUsers, 'getUserById') def getUserById(self, id, default=None): """ See IUserFolder. """ plugins = self._getOb('plugins') user_info = self._verifyUser(plugins, user_id=id) if not user_info: return default return self._findUser(plugins, user_info['id'], user_info['login']) security.declarePublic('validate') # XXX: public? def validate(self, request, auth='', roles=_noroles): """ See IUserFolder. """ plugins = self._getOb('plugins') is_top = self._isTop() user_ids = self._extractUserIds(request, plugins) (accessed, container, name, value) = self._getObjectContext(request['PUBLISHED'], request) for user_id, login in user_ids: user = self._findUser(plugins, user_id, login, request=request) if aq_base(user) is emergency_user: if is_top: return user else: return None if self._authorizeUser(user, accessed, container, name, value, roles): return user if not is_top: return None # # No other user folder above us can satisfy, and we have no user; # return a constructed anonymous only if anonymous is authorized. # anonymous = self._createAnonymousUser(plugins) if self._authorizeUser(anonymous, accessed, container, name, value, roles): return anonymous return None security.declareProtected(SearchPrincipals, 'searchUsers') def searchUsers(self, **kw): """ Search for users """ search_id = kw.get('id', None) search_name = kw.get('name', None) result = [] max_results = kw.get('max_results', '') sort_by = kw.get('sort_by', '') # We apply sorting and slicing here across all sets, so don't # make the plugin do it if sort_by: del kw['sort_by'] if max_results: del kw['max_results'] if search_name: if kw.get('id') is not None: del kw['id'] # don't even bother searching by id kw['login'] = kw['name'] plugins = self._getOb('plugins') enumerators = plugins.listPlugins(IUserEnumerationPlugin) for enumerator_id, enum in enumerators: try: user_list = enum.enumerateUsers(**kw) for user_info in user_list: info = {} info.update(user_info) info['userid'] = info['id'] info['principal_type'] = 'user' if not info.has_key('title'): info['title'] = info['login'] result.append(info) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('UserEnumerationPlugin %s error' % enumerator_id, exc_info=True) if sort_by: result.sort(lambda a, b: cmp( a.get(sort_by, '').lower(), b.get(sort_by, '').lower())) if max_results: try: max_results = int(max_results) result = result[:max_results] except ValueError: pass return tuple(result) security.declareProtected(SearchPrincipals, 'searchGroups') def searchGroups(self, **kw): """ Search for groups """ search_id = kw.get('id', None) search_name = kw.get('name', None) result = [] max_results = kw.get('max_results', '') sort_by = kw.get('sort_by', '') # We apply sorting and slicing here across all sets, so don't # make the plugin do it if sort_by: del kw['sort_by'] if max_results: del kw['max_results'] if search_name: if kw.get('id') is not None: del kw['id'] if not kw.has_key('title'): kw['title'] = kw['name'] plugins = self._getOb('plugins') enumerators = plugins.listPlugins(IGroupEnumerationPlugin) for enumerator_id, enum in enumerators: try: group_list = enum.enumerateGroups(**kw) for group_info in group_list: info = {} info.update(group_info) info['groupid'] = info['id'] info['principal_type'] = 'group' if not info.has_key('title'): info['title'] = "(Group) %s" % info['groupid'] result.append(info) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('GroupEnumerationPlugin %s error' % enumerator_id, exc_info=True) if sort_by: result.sort(lambda a, b: cmp( a.get(sort_by, '').lower(), b.get(sort_by, '').lower())) if max_results: try: max_results = int(max_results) result = result[:max_results + 1] except ValueError: pass return tuple(result) security.declareProtected(SearchPrincipals, 'searchPrincipals') def searchPrincipals(self, groups_first=False, **kw): """ Search for principals (users, groups, or both) """ max_results = kw.get('max_results', '') search_id = kw.get('id', None) search_name = kw.get('name', None) if search_name: if not kw.has_key('title'): kw['title'] = search_name kw['login'] = search_name users = [d.copy() for d in self.searchUsers(**kw)] groups = [d.copy() for d in self.searchGroups(**kw)] if groups_first: result = groups + users else: result = users + groups if max_results: try: max_results = int(max_results) result = result[:max_results + 1] except ValueError: pass return tuple(result) security.declarePrivate('__creatable_by_emergency_user__') def __creatable_by_emergency_user__(self): return 1 security.declarePrivate('_setObject') def _setObject(self, id, object, roles=None, user=None, set_owner=0): # # Override ObjectManager's version to change the default for # 'set_owner' (we don't want to enforce ownership on contained # objects). Folder._setObject(self, id, object, roles, user, set_owner) security.declarePrivate('_delOb') def _delOb(self, id): # # Override ObjectManager's version to clean up any plugin # registrations for the deleted object # plugins = self._getOb('plugins', None) if plugins is not None: plugins.removePluginById(id) Folder._delOb(self, id) # # ZMI stuff # arrow_right_gif = ImageFile('www/arrow-right.gif', globals()) arrow_left_gif = ImageFile('www/arrow-left.gif', globals()) arrow_up_gif = ImageFile('www/arrow-up.gif', globals()) arrow_down_gif = ImageFile('www/arrow-down.gif', globals()) security.declareProtected(ManageUsers, 'manage_search') manage_search = PageTemplateFile('www/pasSearch', globals()) manage_options = (Folder.manage_options[:1] + ({ 'label': 'Search', 'action': 'manage_search' }, ) + Folder.manage_options[2:] + Cacheable.manage_options) security.declareProtected(ManageUsers, 'resultsBatch') def resultsBatch(self, results, REQUEST, size=20, orphan=2, overlap=0): """ ZMI helper for getting batching for displaying search results """ try: start_val = REQUEST.get('batch_start', '0') start = int(start_val) size = int(REQUEST.get('batch_size', size)) except ValueError: start = 0 batch = Batch(results, size, start, 0, orphan, overlap) if batch.end < len(results): qs = self._getBatchLink(REQUEST.get('QUERY_STRING', ''), start, batch.end) REQUEST.set('next_batch_url', '%s?%s' % (REQUEST.get('URL'), qs)) if start > 0: new_start = start - size - 1 if new_start < 0: new_start = 0 qs = self._getBatchLink(REQUEST.get('QUERY_STRING', ''), start, new_start) REQUEST.set('previous_batch_url', '%s?%s' % (REQUEST.get('URL'), qs)) return batch security.declarePrivate('_getBatchLink') def _getBatchLink(self, qs, old_start, new_start): """ Internal helper to generate correct query strings """ if new_start is not None: if not qs: qs = 'batch_start=%d' % new_start elif qs.startswith('batch_start='): qs = qs.replace('batch_start=%d' % old_start, 'batch_start=%d' % new_start) elif qs.find('&batch_start=') != -1: qs = qs.replace('&batch_start=%d' % old_start, '&batch_start=%d' % new_start) else: qs = '%s&batch_start=%d' % (qs, new_start) return qs # # Helper methods # security.declarePrivate('_extractUserIds') def _extractUserIds(self, request, plugins): """ request -> [ validated_user_id ] o For each set of extracted credentials, try to authenticate a user; accumulate a list of the IDs of such users over all our authentication and extraction plugins. """ result = [] user_ids = [] try: extractors = plugins.listPlugins(IExtractionPlugin) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('Extractor plugin listing error', exc_info=True) extractors = () if not extractors: extractors = (('default', DumbHTTPExtractor()), ) try: authenticators = plugins.listPlugins(IAuthenticationPlugin) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('Authenticator plugin listing error', exc_info=True) authenticators = () for extractor_id, extractor in extractors: try: credentials = extractor.extractCredentials(request) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('ExtractionPlugin %s error' % extractor_id, exc_info=True) continue if credentials: try: credentials['extractor'] = extractor_id # XXX: in key? items = credentials.items() items.sort() except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('Credentials error: %s' % credentials, exc_info=True) else: user_ids = [] if not user_ids: # first try to authenticate against the emergency # user, and return immediately if authenticated user_id, name = self._tryEmergencyUserAuthentication( credentials) if user_id is not None: return [(user_id, name)] for authenticator_id, auth in authenticators: try: uid_and_info = auth.authenticateCredentials( credentials) if uid_and_info is None: continue user_id, info = uid_and_info except _SWALLOWABLE_PLUGIN_EXCEPTIONS: msg = 'AuthenticationPlugin %s error' % ( authenticator_id, ) logger.debug(msg, exc_info=True) continue if user_id is not None: user_ids.append((user_id, info)) result.extend(user_ids) if not user_ids: user_id, name = self._tryEmergencyUserAuthentication( DumbHTTPExtractor().extractCredentials(request)) if user_id is not None: result.append((user_id, name)) return result security.declarePrivate('_tryEmergencyUserAuthentication') def _tryEmergencyUserAuthentication(self, credentials): """ credentials -> emergency_user or None """ try: eua = EmergencyUserAuthenticator() user_id, name = eua.authenticateCredentials(credentials) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('Credentials error: %s' % credentials, exc_info=True) user_id, name = (None, None) return (user_id, name) security.declarePrivate('_getGroupsForPrincipal') def _getGroupsForPrincipal(self, principal, request=None, plugins=None, ignore_plugins=None): all_groups = {} if ignore_plugins is None: ignore_plugins = () if plugins is None: plugins = self._getOb('plugins') groupmakers = plugins.listPlugins(IGroupsPlugin) for groupmaker_id, groupmaker in groupmakers: if groupmaker_id in ignore_plugins: continue groups = groupmaker.getGroupsForPrincipal(principal, request) for group in groups: principal._addGroups([group]) all_groups[group] = 1 return all_groups.keys() security.declarePrivate('_createAnonymousUser') def _createAnonymousUser(self, plugins): """ Allow IAnonymousUserFactoryPlugins to create or fall back. """ factories = plugins.listPlugins(IAnonymousUserFactoryPlugin) for factory_id, factory in factories: anon = factory.createAnonymousUser() if anon is not None: return anon.__of__(self) return nobody.__of__(self) security.declarePrivate('_createUser') def _createUser(self, plugins, user_id, name): """ Allow IUserFactoryPlugins to create, or fall back to default. """ factories = plugins.listPlugins(IUserFactoryPlugin) for factory_id, factory in factories: user = factory.createUser(user_id, name) if user is not None: return user.__of__(self) return PropertiedUser(user_id, name).__of__(self) security.declarePrivate('_findUser') def _findUser(self, plugins, user_id, name=None, request=None): """ user_id -> decorated_user """ if user_id == self._emergency_user.getUserName(): return self._emergency_user # See if the user can be retrieved from the cache view_name = '_findUser-%s' % user_id keywords = {'user_id': user_id, 'name': name} user = self.ZCacheable_get(view_name=view_name, keywords=keywords, default=None) if user is None: user = self._createUser(plugins, user_id, name) propfinders = plugins.listPlugins(IPropertiesPlugin) for propfinder_id, propfinder in propfinders: data = propfinder.getPropertiesForUser(user, request) if data: user.addPropertysheet(propfinder_id, data) groups = self._getGroupsForPrincipal(user, request, plugins=plugins) user._addGroups(groups) rolemakers = plugins.listPlugins(IRolesPlugin) for rolemaker_id, rolemaker in rolemakers: roles = rolemaker.getRolesForPrincipal(user, request) if roles: user._addRoles(roles) user._addRoles(['Authenticated']) # Cache the user if caching is enabled base_user = aq_base(user) if getattr(base_user, '_p_jar', None) is None: self.ZCacheable_set(base_user, view_name=view_name, keywords=keywords) return user.__of__(self) security.declarePrivate('_verifyUser') def _verifyUser(self, plugins, user_id=None, login=None): """ user_id -> info_dict or None """ criteria = {} if user_id is not None: criteria['id'] = user_id criteria['exact_match'] = True if login is not None: criteria['login'] = login if criteria: view_name = createViewName('_verifyUser', user_id or login) cached_info = self.ZCacheable_get(view_name=view_name, keywords=criteria, default=None) if cached_info is not None: return cached_info enumerators = plugins.listPlugins(IUserEnumerationPlugin) for enumerator_id, enumerator in enumerators: try: info = enumerator.enumerateUsers(**criteria) if info: # Put the computed value into the cache self.ZCacheable_set(info[0], view_name=view_name, keywords=criteria) return info[0] except _SWALLOWABLE_PLUGIN_EXCEPTIONS: msg = 'UserEnumerationPlugin %s error' % enumerator_id logger.debug(msg, exc_info=True) return None security.declarePrivate('_authorizeUser') def _authorizeUser(self, user, accessed, container, name, value, roles=_noroles): """ -> boolean (whether user has roles). o Add the user to the SM's stack, if successful. o Return """ user = aq_base(user).__of__(self) newSecurityManager(None, user) security = getSecurityManager() try: try: if roles is _noroles: if security.validate(accessed, container, name, value): return 1 else: if security.validate(accessed, container, name, value, roles): return 1 except: noSecurityManager() raise except Unauthorized: pass return 0 security.declarePrivate('_isTop') def _isTop(self): """ Are we the user folder in the root object? """ try: parent = aq_base(aq_parent(self)) if parent is None: return 0 return parent.isTopLevelPrincipiaApplicationObject except AttributeError: return 0 security.declarePrivate('_getObjectContext') def _getObjectContext(self, v, request): """ request -> ( a, c, n, v ) o 'a 'is the object the object was accessed through o 'c 'is the physical container of the object o 'n 'is the name used to access the object o 'v' is the object (value) we're validating access to o XXX: Lifted from AccessControl.User.BasicUserFolder._getobcontext """ if len(request.steps) == 0: # someone deleted root index_html request['RESPONSE'].notFoundError( 'no default view (root default view was probably deleted)') root = request['PARENTS'][-1] request_container = aq_parent(root) n = request.steps[-1] # default to accessed and container as v.aq_parent a = c = request['PARENTS'][0] # try to find actual container inner = aq_inner(v) innerparent = aq_parent(inner) if innerparent is not None: # this is not a method, we needn't treat it specially c = innerparent elif hasattr(v, 'im_self'): # this is a method, we need to treat it specially c = v.im_self c = aq_inner(v) # if pub's aq_parent or container is the request container, it # means pub was accessed from the root if a is request_container: a = root if c is request_container: c = root return a, c, n, v security.declarePrivate('_getEmergencyUser') def _getEmergencyUser(self): return emergency_user.__of__(self) security.declarePrivate('_doAddUser') def _doAddUser(self, login, password, roles, domains, **kw): """ Create a user with login, password and roles if, and only if, we have a registered user manager and role manager that will accept specific plugin interfaces. """ plugins = self._getOb('plugins') useradders = plugins.listPlugins(IUserAdderPlugin) roleassigners = plugins.listPlugins(IRoleAssignerPlugin) user = None if not (useradders and roleassigners): raise NotImplementedError("There are no plugins" " that can create" " users and assign roles to them.") for useradder_id, useradder in useradders: if useradder.doAddUser(login, password): user = self.getUser(login) break for roleassigner_id, roleassigner in roleassigners: for role in roles: try: roleassigner.doAssignRoleToPrincipal(user.getId(), role) except _SWALLOWABLE_PLUGIN_EXCEPTIONS: logger.debug('RoleAssigner %s error' % roleassigner_id, exc_info=True) pass security.declarePublic('all_meta_types') def all_meta_types(self): """ What objects can be put in here? """ allowed_types = tuple(MultiPlugins) + (RAMCacheManager.meta_type, ) return [x for x in Products.meta_types if x['name'] in allowed_types] security.declarePrivate('manage_beforeDelete') def manage_beforeDelete(self, item, container): if item is self: try: del container.__allow_groups__ except: pass handle = self.meta_type + '/' + self.getId() BeforeTraverse.unregisterBeforeTraverse(container, handle) security.declarePrivate('manage_afterAdd') def manage_afterAdd(self, item, container): if item is self: container.__allow_groups__ = aq_base(self) handle = self.meta_type + '/' + self.getId() container = container.this() nc = BeforeTraverse.NameCaller(self.getId()) BeforeTraverse.registerBeforeTraverse(container, nc, handle) def __call__(self, container, req): """ The __before_publishing_traverse__ hook. """ resp = req['RESPONSE'] req._hold(ResponseCleanup(resp)) stack = getattr(resp, '_unauthorized_stack', []) stack.append(resp._unauthorized) resp._unauthorized_stack = stack resp._unauthorized = self._unauthorized resp._has_challenged = False # # Response override # def _unauthorized(self): req = self.REQUEST resp = req['RESPONSE'] if resp._has_challenged: # Been here already return if not self.challenge(req, resp): # Need to fall back here resp = self._cleanupResponse() resp._unauthorized() else: resp._has_challenged = True def challenge(self, request, response): plugins = self._getOb('plugins') # Find valid protocols for this request type valid_protocols = [] choosers = [] try: choosers = plugins.listPlugins(IChallengeProtocolChooser) except KeyError: # Work around the fact that old instances might not have # IChallengeProtocolChooser registered with the # PluginRegistry. pass for chooser_id, chooser in choosers: choosen = chooser.chooseProtocols(request) if choosen is None: continue valid_protocols.extend(choosen) # Go through all challenge plugins challengers = plugins.listPlugins(IChallengePlugin) protocol = None for challenger_id, challenger in challengers: challenger_protocol = getattr(challenger, 'protocol', challenger_id) if valid_protocols and challenger_protocol not in valid_protocols: # Skip invalid protocol for this request type. continue if protocol is None or protocol == challenger_protocol: if challenger.challenge(request, response): protocol = challenger_protocol if protocol is not None: # something fired, so it was a successful PAS challenge return True # nothing fired, so trigger the fallback return False def _cleanupResponse(self): resp = self.REQUEST['RESPONSE'] # No errors of any sort may propagate, and we don't care *what* # they are, even to log them. stack = getattr(resp, '_unauthorized_stack', []) if stack: resp._unauthorized = stack.pop() else: try: del resp._unauthorized except: pass return resp security.declarePublic('hasUsers') def hasUsers(self): """Zope quick start sacrifice. The quick start page expects a hasUsers() method. """ return True security.declarePublic('updateCredentials') def updateCredentials(self, request, response, login, new_password): """Central updateCredentials method This method is needed for cases where the credentials storage and the credentials extraction is handled by different plugins. Example case would be if the CookieAuthHelper is used as a Challenge and Extraction plugin only to take advantage of the login page feature but the credentials are not stored in the CookieAuthHelper cookie but somewhere else, like in a Session. """ plugins = self._getOb('plugins') cred_updaters = plugins.listPlugins(ICredentialsUpdatePlugin) for updater_id, updater in cred_updaters: updater.updateCredentials(request, response, login, new_password) security.declarePublic('logout') def logout(self, REQUEST): """Publicly accessible method to log out a user """ self.resetCredentials(REQUEST, REQUEST['RESPONSE']) # Little bit of a hack: Issuing a redirect to the same place # where the user was so that in the second request the now-destroyed # credentials can be acted upon to e.g. go back to the login page referrer = REQUEST.get( 'HTTP_REFERER') # HTTP_REFERER is optional header if referrer: REQUEST['RESPONSE'].redirect(referrer) security.declarePublic('resetCredentials') def resetCredentials(self, request, response): """Reset credentials by informing all active resetCredentials plugins """ user = getSecurityManager().getUser() if aq_base(user) is not nobody: plugins = self._getOb('plugins') cred_resetters = plugins.listPlugins(ICredentialsResetPlugin) for resetter_id, resetter in cred_resetters: resetter.resetCredentials(request, response)
class EditorTool(Folder): """ **EditorTool** installs itself into the portal and provides rich text editing capabilities attachable via to HTML input elements such as textarea. It uses *TinyMCE* (http://tinymce.moxiecode.com/) editor. Please see README.txt located into this module for notes """ meta_type = METATYPE_EDITORTOOL icon = 'misc_/NaayaCore/EditorTool.gif' manage_options = (Folder.manage_options) security = ClassSecurityInfo() def __init__(self, id, title): """ Initialize variables""" self.id = id self.title = title def getConfiguration(self): """ Return current default configuration """ return configuration def includeLibs(self, lang=None): """ Returns HTML code that includes required JavaScript libraries. Parameters: `lang` **Not used** """ return ( '<script type="text/javascript" language="javascript" ' 'src="%(parent_url)s/tinymce/jscripts/tiny_mce/jquery.tinymce.js">' '</script>') % { 'parent_url': self.absolute_url() } security.declarePublic('additional_styles') def additional_styles(self): """ Returns the additional naaya styles to be displayed in tinymce """ ret = '' # insert other styles here styleselect = self._get_styleselect_styles() if styleselect is not None: ret += styleselect # custom local syles. Add a DTML Document called "custom_css" inside # portal_editor to benefit from this. custom = self.get('custom_css') if custom: ret += custom(self.REQUEST) self.REQUEST.RESPONSE.setHeader('Content-Type', 'text/css') return ret def _get_styleselect_styles(self): """ Returns the styles to use for styleselect listing inside tinymce Searches the current style objects for the specific format /*BEGIN-TINYMCE-STYLESELECT*/ ... selector { style } ... /*END-TINYMCE-STYLESELECT*/ """ style_objects = self.getLayoutTool().getCurrentStyleObjects() for so in style_objects: text = so() match = re.search( '/\\*BEGIN-TINYMCE-STYLESELECT\\*/(.*?)' '/\\*END-TINYMCE-STYLESELECT\\*/', text, re.S) if match is not None: return match.group(1) return None def _add_styleselect_to_cfg(self, cfg): """ Adds a style select box to the front of the first row of buttons if it can find the styles file it needs if not it does nothing the format for the styles is /*BEGIN-TINYMCE-STYLESELECT*/ ... selector { style } ... /*END-TINYMCE-STYLESELECT*/ """ # get the styles text = self._get_styleselect_styles() if text is None: return # find class selectors selectors_text = re.sub('{(.|\n)*?}', '', text) selectors = re.findall('\\.\w+(?=\s|[,{])', selectors_text) selectors = [sel[1:] for sel in selectors] # add the button and selectors to it cfg['theme_advanced_styles'] = ';'.join( ['%s=%s' % (sel.capitalize(), sel) for sel in selectors]) def render(self, element, lang=None, image_support=False, extra_options={}): """Return the HTML necessary to run the TinyMCE. Parameters: `element` `id` of HTML element that editor will is attached to. `lang` **Not used** `image_support` **No longer used** In order to disable images. Use extra_options, see below. `extra_options` Extra options you can pass to tinyMCE editor. See `config.ini` for further reference. You can pass any option from there to override default one. `extra_options['config_template']` Loads one of the defined templates from `config.ini`. Default is 'tinymce'. Also you can use 'tinymce_noimage' to disable image insertion. """ if not lang: lang = self.gl_get_selected_language() doc_url = "/".join(self.aq_parent.getPhysicalPath()) if 'config_template' in extra_options: template = extra_options['config_template'] cfg = loadConfig(template) else: cfg = copy.copy(configuration) cfg.update({ 'language': lang, 'select_image_url': '%s/select_image?document=%s' % (self.absolute_url(), doc_url), 'edit_image_url': '%s/prepare_image?mode=edit&document=%s' % (self.absolute_url(), doc_url), 'link_popup_url': '%s/select_link' % self.absolute_url(), 'element_id': element, 'script_url': '%s/tinymce/jscripts/tiny_mce/tiny_mce.js' % self.absolute_url(), 'site_url': self.getSite().absolute_url(), 'language': self.gl_get_selected_language(), }) cfg.update(extra_options) # romancri 20100420: # When using dialects, clobber the dialect. Otherwise, TinyMCE fails # because it doesn't have these translation files. if 'language' in cfg.keys() and cfg['language']: cfg['language'] = cfg['language'].split('-')[0] self._add_styleselect_to_cfg(cfg) css_url = '/'.join(self.getPhysicalPath()) + '/additional_styles' old_css = cfg.get('content_css', '') cfg['content_css'] = css_url if old_css != '': cfg['content_css'] += ',' + old_css return "<script type=\"text/javascript\">\ $().ready(function() {$('textarea#%s').tinymce(%s);})\ </script>" % (element, json.dumps(cfg, indent=2)) def get_preview_img(self, REQUEST=None): """ Compute src attribute for the preview image. Uploads image if requested. Returns the URL to the image. """ url = '' if 'url' in REQUEST.form: url = REQUEST.form['url'] if 'mode' in REQUEST.form: mode = REQUEST.form['mode'] if mode == 'upload': url = self._upload_image(REQUEST) if not url.startswith('http') and not url.startswith('/'): document = self.getEnclosingDocument(REQUEST) if document is not None: url = '%s/%s' % (document.absolute_url(), url) return url def _upload_image(self, REQUEST=None): """ Upload an image into the document container. """ if REQUEST: if 'file' in REQUEST.form: file = REQUEST.form['file'] document = self.getEnclosingDocument(REQUEST) if document: imageContainer = document.imageContainer uploaded = imageContainer.uploadImage(file, None) return uploaded.absolute_url() else: print 'no image to upload' def enumerateImages(self, source, page=0, query=None, REQUEST=None): """ Retrieve the list of images depending on the source. Return a list of ``Image`` objects """ def get_image_info(source, image): image_object = { 'url': image.absolute_url(), 'title': url_quote(image.title_or_id()), 'source': '', 'author': '' } if source == 'album': image_object['source'] = url_quote(image.source) image_object['author'] = url_quote(image.author) return image_object ret = [] if source == 'document': document = self.getEnclosingDocument(REQUEST) if document: ret = document.imageContainer.getImages() if source == 'website': site = self.getSite() ret = site.imageContainer.getImages() if source == 'album': album_url = REQUEST.form['album'] if query is None: album = self.restrictedTraverse(album_url) ret = album.getObjects() else: ctool = self.getCatalogTool() filter_index = ('objectkeywords_' + self.gl_get_selected_language()) ret_brains = ctool.search({ 'path': album_url, 'meta_type': 'Naaya Photo', filter_index: query }) ret = [x.getObject() for x in ret_brains] total_images = len(ret) images = ret[(int(page) * 12):((int(page) + 1) * 12)] options = { 'total_images': total_images, 'images': [get_image_info(source, image) for image in images] } return json.dumps(options) def enumeratePhotoAlbums(self, REQUEST=None): """ Lookup photo galleries from the site. Return a list with all photo galleries available within the site. """ ctool = self.getCatalogTool() return [ x.getObject() for x in ctool.search({'meta_type': 'Naaya Photo Folder'}) ] def getEnclosingDocument(self, REQUEST): """ Return the enclosing document where this editor tool instance is located. `REQUEST` Http request that **must** contain the 'document' parameter Return enclosing document object """ if 'document' in REQUEST.form: document_url = REQUEST.form['document'] return self.restrictedTraverse(document_url) return None def prepare_image_styles(self, REQUEST=None): """ Parse `REQUEST` and retrieve image attributes to set them into preview. This method is called when user selects the image into editor and then presses image button to adjust its settings. Return a dictionary with found attributes such as border, margin etc. """ ret = { 'title': self.get_request_param(REQUEST, 'title'), 'alignment': self.get_request_param(REQUEST, 'left'), 'css_alignment': '', 'margin': '', 'border_preview': '', 'width_preview': '', 'height_preview': '', 'border': '', 'width': '', 'height': '', 'h_margin': '', 'v_margin': '', } if 'alignment' in REQUEST.form: alignment = REQUEST.form['alignment'] if alignment: if alignment == 'left' or alignment == 'right': ret['css_alignment'] = 'float: %s' % alignment else: ret['css_alignment'] = 'vertical-align: %s' % alignment if 'margin' in REQUEST.form: ret['margin'] = 'margin: %s' % REQUEST.form['margin'] if 'border' in REQUEST.form: ret['border_preview'] = 'border: %s' % REQUEST.form['border'] ret['border'] = parse_css_border_width(REQUEST.form['border']) if 'width' in REQUEST.form: ret['width_preview'] = 'width: %s' % REQUEST.form['width'] ret['width'] = strip_unit(REQUEST.form['width']) if 'height' in REQUEST.form: ret['height_preview'] = 'height: %s' % REQUEST.form['height'] ret['height'] = strip_unit(REQUEST.form['height']) if REQUEST and 'margin' in REQUEST.form: margins = parse_css_margin(REQUEST.form['margin']) ret['h_margin'] = margins[0] ret['v_margin'] = margins[1] return ret def get_request_param(self, REQUEST, name, default=''): """ Safely retrieve a parameter from request Parameters: `REQUEST` Http request `name` Name of the parameter `default` Default value to return if parameter not found. If not specified is empty string. Return the parameter or default if none found. """ if name in self.REQUEST: return self.REQUEST.form[name] return default def isImageContainer(self, document): """ Verifies document if is image container or inherits the imageContainer of NySite. Parameters: `document` Document to be checked. Return ``true`` if document has its own instance of `imageContainer` """ return self.getSite().imageContainer != document.imageContainer image_js = ImageFile('www/image.js', globals()) link_js = ImageFile('www/link.js', globals()) image_css = ImageFile('www/image.css', globals()) tinymce = StaticServeFromZip('tinymce', 'www/tinymce_3_4_7_jquery_naaya.zip', globals()) tinymce_naaya = StaticServeFromZip('Naaya', 'www/tinymce_naaya.zip', globals()) select_image = PageTemplateFile('zpt/select_image', globals()) select_image_size = PageTemplateFile('zpt/select_image_size', globals()) prepare_image = PageTemplateFile('zpt/prepare_image', globals()) select_link = PageTemplateFile('zpt/select_link', globals())
# Dragos Chirila, Finsiel Romania # # #$Id: __init__.py 2582 2004-11-15 14:07:57Z finrocvs $ #Python imports #Zope imports from App.ImageFile import ImageFile #Product imports import EWInstaller def initialize(context): """ initialize the EWInstaller object """ #register classes context.registerClass( EWInstaller.EWInstaller, permission = 'Add EWInstaller object', constructors = ( EWInstaller.addEWInstaller, ), icon = 'images/EWInstaller.gif' ) misc_ = { 'EWInstaller.gif':ImageFile('images/EWInstaller.gif', globals()), 'logo.gif':ImageFile('images/logo.gif', globals()), }
def registerClass(self, instance_class=None, meta_type='', permission=None, constructors=(), icon=None, permissions=None, legacy=(), visibility="Global", interfaces=_marker, container_filter=None ): """Register a constructor Keyword arguments are used to provide meta data: instance_class -- The class of the object that will be created. This is not currently used, but may be used in the future to increase object mobility. meta_type -- The kind of object being created This appears in add lists. If not specified, then the class meta_type will be used. permission -- The permission name for the constructors. If not specified, then a permission name based on the meta type will be used. constructors -- A list of constructor methods A method can me a callable object with a __name__ attribute giving the name the method should have in the product, or the method may be a tuple consisting of a name and a callable object. The method must be picklable. The first method will be used as the initial method called when creating an object. icon -- The name of an image file in the package to be used for instances. Note that the class icon attribute will be set automagically if an icon is provided. permissions -- Additional permissions to be registered If not provided, then permissions defined in the class will be registered. legacy -- A list of legacy methods to be added to ObjectManager for backward compatibility visibility -- "Global" if the object is globally visible, None else interfaces -- a list of the interfaces the object supports container_filter -- function that is called with an ObjectManager object as the only parameter, which should return a true object if the object is happy to be created in that container. The filter is called before showing ObjectManager's Add list, and before pasting (after object copy or cut), but not before calling an object's constructor. """ pack=self.__pack initial=constructors[0] productObject=self.__prod pid=productObject.id if icon and instance_class is not None: setattr(instance_class, 'icon', 'misc_/%s/%s' % (pid, os.path.split(icon)[1])) if permissions: if isinstance(permissions, basestring): # You goofed it! raise TypeError, ('Product context permissions should be a ' 'list of permissions not a string', permissions) for p in permissions: if isinstance(p, tuple): p, default= p registerPermissions(((p, (), default),)) else: registerPermissions(((p, ()),)) ############################################################ # Constructor permission setup if permission is None: permission="Add %ss" % (meta_type or instance_class.meta_type) if isinstance(permission, tuple): permission, default = permission else: default = ('Manager',) pr = PermissionRole(permission,default) registerPermissions(((permission, (), default),)) ############################################################ OM = ObjectManager for method in legacy: if isinstance(method, tuple): name, method = method aliased = 1 else: name=method.__name__ aliased = 0 if name not in OM.__dict__: setattr(OM, name, method) setattr(OM, name+'__roles__', pr) if aliased: # Set the unaliased method name and its roles # to avoid security holes. XXX: All "legacy" # methods need to be eliminated. setattr(OM, method.__name__, method) setattr(OM, method.__name__+'__roles__', pr) if isinstance(initial, tuple): name, initial = initial else: name = initial.__name__ fd = getattr(pack, '__FactoryDispatcher__', None) if fd is None: class __FactoryDispatcher__(FactoryDispatcher): "Factory Dispatcher for a Specific Product" fd = pack.__FactoryDispatcher__ = __FactoryDispatcher__ if not hasattr(pack, '_m'): pack._m = AttrDict(fd) m = pack._m if interfaces is _marker: if instance_class is None: interfaces = () else: interfaces = tuple(implementedBy(instance_class)) Products.meta_types = Products.meta_types + ( { 'name': meta_type or instance_class.meta_type, # 'action': The action in the add drop down in the ZMI. This is # currently also required by the _verifyObjectPaste # method of CopyContainers like Folders. 'action': ('manage_addProduct/%s/%s' % (pid, name)), # 'product': Used by ProductRegistry for TTW products and by # OFS.Application for refreshing products. # This key might not be available. 'product': pid, # 'permission': Guards the add action. 'permission': permission, # 'visibility': A silly name. Doesn't have much to do with # visibility. Allowed values: 'Global', None 'visibility': visibility, # 'interfaces': A tuple of oldstyle and/or newstyle interfaces. 'interfaces': interfaces, 'instance': instance_class, 'container_filter': container_filter },) m[name]=initial m[name+'__roles__']=pr for method in constructors[1:]: if isinstance(method, tuple): name, method = method else: name=os.path.split(method.__name__)[-1] if name not in productObject.__dict__: m[name]=method m[name+'__roles__']=pr if icon: name = os.path.split(icon)[1] icon = ImageFile(icon, self.__pack.__dict__) icon.__roles__=None if not hasattr(misc_, pid): setattr(misc_, pid, Misc_(pid, {})) getattr(misc_, pid)[name]=icon
'meta_type': 'Naaya InfoFolder', 'label': 'InfoFolder', 'permission': PERMISSION_ADD_INFOFOLDER, 'forms': ['infofolder_add', 'infofolder_edit', 'infofolder_index'], 'add_form': 'infofolder_add_html', 'description': 'This is Naaya InfoFolder type.', 'properties': {}, #TODO: REMOVE 'default_schema': DEFAULT_SCHEMA, 'schema_name': 'NyInfoFolder', '_module': sys.modules[__name__], 'additional_style': AdditionalStyle('www/InfoFolder.css', globals()), 'icon': os.path.join(os.path.dirname(__file__), 'www', 'NyInfoFolder.gif'), 'on_install': setupContentType, '_misc': { 'NyInfoFolder.gif': ImageFile('www/NyInfoFolder.gif', globals()), 'NyInfoFolder_marked.gif': ImageFile('www/NyInfoFolder_marked.gif', globals()), }, } #Portal portlets NaayaPageTemplateFile('zpt/latest_uploads_portlet', globals(), 'naaya.content-sdo.infofolder.latest_uploads_portlet') NaayaPageTemplateFile( 'zpt/infofolder_search_portlet', globals(), 'naaya.content-sdo.infofolder.infofolder_search_portlet') NaayaPageTemplateFile('zpt/events_filter', globals(), 'naaya.content-sdo.infofolder.events_filter') NaayaPageTemplateFile('zpt/submit_site_portlet', globals(), 'naaya.content-sdo.infofolder.submit_site_portlet')
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## __doc__ = """Blend product module - Last Updated 8.12.2007""" __version__ = '1.0'[11:-2] import BlendSite, AdminNews, Page, iPage, Homepage, News, Event, Promo, Person, Article, Cluster from App.ImageFile import ImageFile misc_ = { 'logo': ImageFile('images/blend_powered.gif', globals()), 'edit': ImageFile('images/edit.png', globals()), 'viewit': ImageFile('images/view.png', globals()), 'bigview': ImageFile('images/big_view.png', globals()), 'delete': ImageFile('images/garbage.png', globals()), 'publish': ImageFile('images/magic-wand2.png', globals()), 'ipage': ImageFile('images/ipage.gif', globals()), 'page': ImageFile('images/page.gif', globals()), 'image':
def registerIcon(filename): setattr(OFS.misc_.misc_.ZopeVersionControl, filename, ImageFile('www/%s' % filename, globals()) )
import CountryProfile from App.ImageFile import ImageFile def initialize(context): """ """ context.registerClass(CountryProfile.CountryProfile, constructors=(CountryProfile.manage_add_html, CountryProfile.manage_add_object), icon='www/meta_type.gif') misc_ = { 'country-profile.css': ImageFile('www/css/country-profile.css', globals()), # 'meta_type.gif':ImageFile('www/meta_type.gif', globals()), }
if not isinstance(text, unicode): text = unicode(text, encoding) zpt = ZopePageTemplate(id, text, content_type, output_encoding=encoding) zpt.pt_setTitle(title, encoding) self._setObject(id, zpt) zpt = getattr(self, id) if RESPONSE: if submit == " Add and Edit ": RESPONSE.redirect(zpt.absolute_url() + '/pt_editForm') else: RESPONSE.redirect(self.absolute_url() + '/manage_main') else: return zpt from Products.PageTemplates import misc_ misc_['exclamation.gif'] = ImageFile('www/exclamation.gif', globals()) def initialize(context): context.registerClass( ZopePageTemplate, permission='Add Page Templates', constructors=(manage_addPageTemplateForm, manage_addPageTemplate), icon='www/zpt.gif', ) context.registerHelp() context.registerHelpTitle('Zope Help')
# Copyright (C) European Environment Agency. All # Rights Reserved. # # Contributor(s): # Dragos Chirila, Finsiel Romania from HelpDesk import HelpDesk, manage_addHelpDeskForm, manage_addHelpDesk from App.ImageFile import ImageFile def initialize(context): """ Initialize the HelpDesk product""" context.registerClass(HelpDesk, constructors=(manage_addHelpDeskForm, manage_addHelpDesk), permission='Add HelpDesk', icon='www/HelpDesk.gif') misc_ = { 'HelpDesk': ImageFile('www/HelpDesk.gif', globals()), 'Issue': ImageFile('www/Issue.gif', globals()), 'spacer': ImageFile('www/spacer.gif', globals()), 'sortup.gif': ImageFile('www/sortup.gif', globals()), 'sortdown.gif': ImageFile('www/sortdown.gif', globals()), 'sortnot.gif': ImageFile('www/sortnot.gif', globals()), 'new': ImageFile('www/new.gif', globals()), 'menu_top_left': ImageFile('www/menu_top_left.gif', globals()), 'menu_top_right': ImageFile('www/menu_top_right.gif', globals()) }
'product': 'NaayaContent', 'module': 'NySemNews', 'package_path': os.path.abspath(os.path.dirname(__file__)), 'meta_type': METATYPE_OBJECT, 'label': LABEL_OBJECT, 'permission': PERMISSION_ADD_OBJECT, 'forms': OBJECT_FORMS, 'add_form': OBJECT_ADD_FORM, 'description': DESCRIPTION_OBJECT, 'default_schema': DEFAULT_SCHEMA, 'properties': PROPERTIES_OBJECT, 'schema_name': 'NySemNews', '_module': sys.modules[__name__], 'icon': os.path.join(os.path.dirname(__file__), 'www', 'NySemNews.gif'), '_misc': { 'NySemNews.gif': ImageFile('www/NySemNews.gif', globals()), 'NySemNews_marked.gif': ImageFile('www/NySemNews_marked.gif', globals()), }, } manage_addNySemNews_html = PageTemplateFile('zpt/semnews_manage_add', globals()) manage_addNySemNews_html.kind = METATYPE_OBJECT manage_addNySemNews_html.action = 'addNySemNews' def semnews_add_html(self, REQUEST=None, RESPONSE=None): """ """ from Products.NaayaBase.NyContentType import get_schema_helper_for_metatype form_helper = get_schema_helper_for_metatype(self, config['meta_type'])