class ContentAddFormBase(_EditFormMixin, PageAddForm): adapts(IFolderish, ICMFDefaultSkin, ITypeInformation) implementsOnly(IPageForm) security = ClassSecurityInfo() security.declareObjectPrivate() actions = form.Actions( form.Action(name='add', label=form._('Add'), condition=form.haveInputWidgets, success='handle_add', failure='handle_failure'), form.Action(name='cancel', label=_(u'Cancel'), success='handle_cancel_success', failure='handle_cancel_failure')) def __init__(self, context, request, ti): self.context = context self.request = request self.ti = ti security.declareProtected(AddPortalContent, '__call__') def __call__(self): container = self.context portal_type = self.ti.getId() # check allowed (sometimes redundant, but better safe than sorry) if not self.ti.isConstructionAllowed(container): raise AccessControl_Unauthorized('Cannot create %s' % portal_type) # check container constraints ttool = self._getTool('portal_types') container_ti = ttool.getTypeInfo(container) if container_ti is not None and \ not container_ti.allowType(portal_type): raise ValueError('Disallowed subobject type: %s' % portal_type) return super(ContentAddFormBase, self).__call__() @property def label(self): obj_type = translate(self.ti.Title(), self.context) return _(u'Add ${obj_type}', mapping={'obj_type': obj_type}) @property def description(self): return self.ti.Description() #same as in form.AddFormBase but without action decorator def handle_add(self, action, data): self.createAndAdd(data) def handle_cancel_success(self, action, data): return self._setRedirect('portal_types', ('object/folderContents', 'object/view')) def handle_cancel_failure(self, action, data, errors): self.status = None return self._setRedirect('portal_types', ('object/folderContents', 'object/view')) def create(self, data): id = data.pop('id', '') or '' factory = getUtility(IFactory, self.ti.factory) obj = factory(id=id, **data) obj._setPortalTypeName(self.ti.getId()) return obj def add(self, obj): container = self.context name = INameChooser(container).chooseName(obj.getId(), obj) obj.id = name container._setObject(name, obj) obj = container._getOb(name) obj_type = translate(obj.Type(), container) self.status = _(u'${obj_type} added.', mapping={'obj_type': obj_type}) self._finished_add = True self._added_obj = obj return obj def nextURL(self): obj = self._added_obj message = translate(self.status, self.context) if isinstance(message, unicode): message = message.encode(self._getBrowserCharset()) return '%s/%s?%s' % (obj.absolute_url(), self.ti.immediate_view, make_query(portal_status_message=message))
class StoryBookingTraverser(ProjectBookingTraverser): """Traversal adapter for bookings on projects """ adapts(IStory, IRequest)
class DashboardPortletManagerRenderer(ColumnPortletManagerRenderer): """Render a column of the dashboard """ adapts(Interface, IDefaultBrowserLayer, IBrowserView, IDashboard) template = ViewPageTemplateFile('browser/templates/dashboard-column.pt')
class DeviceSearchProvider(object): """ Provider which searches Zenoss's global catalog for matching devices """ implements(ISearchProvider) adapts(DataRoot) def __init__(self, dmd): self._dmd = dmd def getCategoryCounts(self, parsedQuery, filterFn=None): return self.getSearchResults(parsedQuery, countOnly=True, filterFn=filterFn) def getSearchResults(self, parsedQuery, sorter=None, category=None, countOnly=False, unrestricted=False, filterFn=None): """ Queries the catalog. Searches the searchKeywords index using *keyword1* AND *keyword2* AND so on. If there are preferred categories, find maxResults # of instances before searching other categories. @rtype generator of BrainSearchResult objects """ operators = parsedQuery.operators keywords = parsedQuery.keywords if not keywords: return def listMatchGlob(op, index, list): return op(*[MatchGlob(index, '*%s*' % i) for i in list]) dmd = self._dmd kw_query = Or(listMatchGlob(And, 'titleOrId', keywords), listMatchGlob(And, 'getDeviceIp', keywords)) # Rank devices whose name match the query higher than other stuff ranker = RankByQueries_Sum( (listMatchGlob(Or, 'titleOrId', keywords), 10), ) full_query = kw_query cat = dmd.Devices.deviceSearch querySet = full_query catalogItems = cat.evalAdvancedQuery(querySet, (ranker, )) brainResults = [ DeviceSearchResult(catalogItem) for catalogItem in catalogItems if checkPermission("View", catalogItem.getObject()) ] if filterFn: brainResults = filter(filterFn, brainResults) if countOnly: return dict(Device=len(brainResults)) results = brainResults if sorter is not None: results = sorter.limitSort(results) return results def getQuickSearchResults(self, parsedQuery, maxResults=None): """ Currently just calls getSearchResults """ return self.getSearchResults(parsedQuery, maxResults)
class Snmptrapd(BaseSnmptrapd): """Ticker-Adapter.""" implements(ISnmptrapd) adapts(IHostMgeUps) def __init__(self, context): print "Snmptrapd.__init__ mge_ups" self.context = context def triggered(self, reqPDU, msgVer, pMod): """ got snmp event from snmp thread """ print "Snmptrapd %s triggered (reqPDU:%s)!!" % (self.context, reqPDU) print '-' * 80 if reqPDU.isSameTypeWith(pMod.TrapPDU()): if msgVer == api.protoVersion1: #print 'Enterprise: %s' % ( #pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint() #) #print 'Agent Address: %s' % ( #pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint() #) #print 'Generic Trap: %s' % ( #pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint() #) #print 'Specific Trap: %s' % ( #pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint() #) #print 'Uptime: %s' % ( #pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint() #) varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU) # AT #if pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint() == \ #u'1.3.6.1.4.1.207.1.4.29': # TODO remove this big fake if pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint() == \ u'1.3.6.1.4.1.705.1.11': #print "MGE UPS <----" #import pdb; pdb.set_trace() #self.context.trigger_offline() specificTrap = pMod.apiTrapPDU.getSpecificTrap(reqPDU) if specificTrap == 1: self.context.eventOut_upsBatteryFault() elif specificTrap == 2: self.context.eventOut_upsBatteryOK() elif specificTrap == 3: self.context.eventOut_upsBatteryReplacementIndicated() elif specificTrap == 4: self.context.eventOut_upsBatteryReplacementNotIndicated( ) elif specificTrap == 5: self.context.eventOut_upsAtLowBattery() elif specificTrap == 6: self.context.eventOut_upsFromLowBattery() elif specificTrap == 7: self.context.eventOut_upsChargerFault() elif specificTrap == 8: self.context.eventOut_upsChargerOK() elif specificTrap == 9: self.context.eventOut_upsAtLowCondition() elif specificTrap == 10: self.context.eventOut_upsFromLowCondition() elif specificTrap == 11: self.context.eventOut_upsOnBattery() elif specificTrap == 12: self.context.eventOut_upsReturnFromBattery() elif specificTrap == 13: self.context.eventOut_upsOnByPass() elif specificTrap == 14: self.context.eventOut_upsReturnFromByPass() elif specificTrap == 15: self.context.eventOut_upsByPassUnavailable() elif specificTrap == 16: self.context.eventOut_upsByPassAvailable() elif specificTrap == 17: self.context.eventOut_upsUtilityFailure() elif specificTrap == 18: self.context.eventOut_upsUtilityRestored() elif specificTrap == 19: self.context.eventOut_upsOnBoost() elif specificTrap == 20: self.context.eventOut_upsReturnFromBoost() elif specificTrap == 21: self.context.eventOut_upsOverLoad() elif specificTrap == 22: self.context.eventOut_upsLoadOK() elif specificTrap == 23: self.context.eventOut_upsOverTemperature() elif specificTrap == 24: self.context.eventOut_upsTemperatureOK() elif specificTrap == 37: self.context.eventOut_upsCommunicationFailure() elif specificTrap == 38: self.context.eventOut_upsCommunicationRestored() elif specificTrap == 39: self.context.eventOut_upsInputBad() elif specificTrap == 40: self.context.eventOut_upsInputOK() elif specificTrap == 41: self.context.eventOut_upsBatteryUnavailable() elif specificTrap == 42: self.context.eventOut_upsBatteryAvailable() elif specificTrap == 43: self.context.eventOut_upsAtLowRecharge() elif specificTrap == 44: self.context.eventOut_upsFromLowRecharge() elif specificTrap == 45: self.context.eventOut_upsDiagnosticTestFail() elif specificTrap == 46: self.context.eventOut_upsDiagnosticTestOK() elif specificTrap == 47: self.context.eventOut_upsBatteryTestOK() elif specificTrap == 48: self.context.eventOut_upsBatteryTestFail() elif specificTrap == 49: self.context.eventOut_upsExternalAlarmActive() elif specificTrap == 50: self.context.eventOut_upsExternalAlarmInactive() elif specificTrap == 51: self.context.eventOut_upsOnBuck() elif specificTrap == 52: self.context.eventOut_upsReturnFromBuck() elif specificTrap == 53: self.context.eventOut_upsmgEnvironmentComFailure() elif specificTrap == 54: self.context.eventOut_upsmgEnvironmentComOK() elif specificTrap == 55: self.context.eventOut_upsmgEnvironmentTemperatureLow() elif specificTrap == 56: self.context.eventOut_upsmgEnvironmentTemperatureHigh() elif specificTrap == 57: self.context.eventOut_upsmgEnvironmentTemperatureOK() elif specificTrap == 58: self.context.eventOut_upsmgEnvironmentHumidityLow() elif specificTrap == 59: self.context.eventOut_upsmgEnvironmentHumidityHigh() elif specificTrap == 60: self.context.eventOut_upsmgEnvironmentHumidityOK() elif specificTrap == 61: self.context.eventOut_upsmgEnvironmentInput1Closed() elif specificTrap == 62: self.context.eventOut_upsmgEnvironmentInput1Open() elif specificTrap == 63: self.context.eventOut_upsmgEnvironmentInput2Closed() elif specificTrap == 64: self.context.eventOut_upsmgEnvironmentInput2Open() if pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint() == \ u'1.3.6.1.4.1.9.1.516': print "Cisco - Switch!!!" if pMod.apiTrapPDU.getGenericTrap( reqPDU).prettyPrint() == 'linkUp(3)': #print "UP" self.context.eventOut_powerReturned() if pMod.apiTrapPDU.getGenericTrap( reqPDU).prettyPrint() == 'linkDown(2)': #print "DOWN" self.context.eventOut_onBattery() else: varBinds = pMod.apiPDU.getVarBindList(reqPDU)
class HadoopNodeManagerInfo(HadoopServiceNodeInfo): ''' API Info adapter factory for HadoopNodeManager. ''' implements(IHadoopNodeManagerInfo) adapts(HadoopNodeManager)
class JSONReadExtender(object): """- Adds fields to Analysis Service: ServiceDependencies - services our calculation depends on ServiceDependants - services who's calculation depend on us MethodInstruments - A dictionary of instruments: keys: Method UID values: list of instrument UIDs """ implements(IJSONReadExtender) adapts(IAnalysisService) def __init__(self, context): self.context = context def service_info(self, service): ret = { "Category": service.getCategory().Title(), "Category_uid": service.getCategory().UID(), "Service": service.Title(), "Service_uid": service.UID(), "Keyword": service.getKeyword(), "PointOfCapture": service.getPointOfCapture(), "PointOfCapture_title": POINTS_OF_CAPTURE.getValue(service.getPointOfCapture()), } return ret def __call__(self, request, data): include_fields = get_include_fields(request) if not include_fields or "ServiceDependencies" in include_fields: data["ServiceDependencies"] = [] calc = self.context.getCalculation() if calc: services = [ self.service_info(service) for service in calc.getCalculationDependencies(flat=True) if service.UID() != self.context.UID() ] data["ServiceDependencies"] = services if not include_fields or "ServiceDependants" in include_fields: data["ServiceDependants"] = [] calcs = self.context.getBackReferences( 'CalculationAnalysisService') if calcs: for calc in calcs: services = [ self.service_info(service) for service in calc.getCalculationDependants() if service.UID() != self.context.UID() ] data["ServiceDependants"].extend(services) if not include_fields or "MethodInstruments" in include_fields: data["MethodInstruments"] = {} for method in self.context.getAvailableMethods(): for instrument in method.getInstruments(): if method.UID() not in data["MethodInstruments"]: data["MethodInstruments"][method.UID()] = [] data["MethodInstruments"][method.UID()].append( load_field_values(instrument, include_fields=[]))
class NationalStory2Surf(Soer2Surf): """ Adapter from eea.soer report AT types to surf resource and RDF """ implements(IArchetype2Surf) adapts(ISOERReport, ISurfSession) portalType = 'NationalStory' def __init__(self, context, session): super(NationalStory2Surf, self).__init__(context, session) self.field_map = dict([('text', 'assessment'), ('subject', 'keyword'), ('modification_date', 'modified'), ('effectiveDate', 'pubDate'), ('description', 'description'), ]) @property def blacklist_map(self): """ Blacklist map """ return super(NationalStory2Surf, self).blacklist_map + \ ['relatedItems', 'question', 'geoCoverage', 'id'] def write(self, subReport=False, **kwargs): """ AT to surf """ resource = self.resource context = self.context language = context.Language() question = context.getQuestion() if context.portal_type == 'DiversityReport': question = vocab.long_diversity_questions.get(question, question) elif context.portal_type == 'CommonalityReport': question = vocab.long_questions.get(question, question) resource.soer_question = (question, language) resource.soer_geoCoverage = rdflib.URIRef(context.getGeoCoverage()) resource.soer_hasFigure = [] if subReport: resource.soer_sortOrder = \ context.aq_parent.getObjectPosition(context.getId()) + 1 for obj in context.objectValues(): surfObj = queryMultiAdapter((obj, self.session), interface=IObject2Surf) if surfObj is not None: if obj.portal_type == 'Image': resource.soer_hasFigure.append(surfObj.resource) elif obj.portal_type in ['DataSourceLink', 'Link']: # We allowed normal links as data source pre 0.5 resource.soer_dataSource.append(surfObj.resource) elif obj.portal_type == 'RelatedIndicatorLink': resource.soer_relatedEuropeanIndicator.append( (rdflib.URIRef(obj.getRemoteUrl()), language)) else: # Current resource has the sort order 0 since it is # parent to the other reports resource.soer_sortOrder = 0 surfObj.write(subReport=True) resource.save() return resource
class ImageZipRepresentation(FileZipRepresentation): adapts(IATImage, Interface)
class TypeInformationXMLAdapter(XMLAdapterBase, PropertyManagerHelpers): """XML im- and exporter for TypeInformation. """ adapts(ITypeInformation, ISetupEnviron) _LOGGER_ID = 'types' def _exportNode(self): """Export the object as a DOM node. """ node = self._getObjectNode('object') node.setAttribute('xmlns:i18n', I18NURI) node.appendChild(self._extractProperties()) node.appendChild(self._extractAliases()) node.appendChild(self._extractActions()) self._logger.info('%r type info exported.' % self.context.getId()) return node def _importNode(self, node): """Import the object from the DOM node. """ if self.environ.shouldPurge(): self._purgeProperties() self._purgeAliases() self._purgeActions() self._migrateProperties(node) self._initProperties(node) self._initAliases(node) self._initActions(node) obj_id = str(node.getAttribute('name')) self._logger.info('%r type info imported.' % obj_id) def _migrateProperties(self, node): # BBB: for CMF 2.1 icon settings for child in node.childNodes: if child.nodeName != 'property': continue if child.getAttribute('name') == 'icon_expr': return for child in node.childNodes: if child.nodeName != 'property': continue if child.getAttribute('name') != 'content_icon': continue text = self._getNodeText(child) icon = 'string:${portal_url}/%s' % text if text else '' new_child = self._doc.createElement('property') new_child.setAttribute('name', 'icon_expr') new_child.appendChild(self._doc.createTextNode(icon)) node.replaceChild(new_child, child) def _extractAliases(self): fragment = self._doc.createDocumentFragment() aliases = sorted(self.context.getMethodAliases().items()) for k, v in aliases: child = self._doc.createElement('alias') child.setAttribute('from', k) child.setAttribute('to', v) fragment.appendChild(child) return fragment def _purgeAliases(self): self.context.setMethodAliases({}) def _initAliases(self, node): aliases = self.context.getMethodAliases() for child in node.childNodes: if child.nodeName != 'alias': continue k = str(child.getAttribute('from')) v = str(child.getAttribute('to')) aliases[k] = v self.context.setMethodAliases(aliases) def _extractActions(self): fragment = self._doc.createDocumentFragment() actions = self.context.listActions() for ai in actions: ai_info = ai.getMapping() child = self._doc.createElement('action') child.setAttribute('title', ai_info['title']) child.setAttribute('action_id', ai_info['id']) child.setAttribute('category', ai_info['category']) child.setAttribute('condition_expr', ai_info['condition']) child.setAttribute('url_expr', ai_info['action']) child.setAttribute('icon_expr', ai_info['icon_expr']) child.setAttribute('link_target', ai_info['link_target']) child.setAttribute('visible', str(bool(ai_info['visible']))) for permission in ai_info['permissions']: sub = self._doc.createElement('permission') sub.setAttribute('value', permission) child.appendChild(sub) fragment.appendChild(child) return fragment def _purgeActions(self): self.context._actions = () def _initActions(self, node): for child in node.childNodes: if child.nodeName != 'action': continue title = str(child.getAttribute('title')) id = str(child.getAttribute('action_id')) category = str(child.getAttribute('category')) condition = str(child.getAttribute('condition_expr')) action = str(child.getAttribute('url_expr')) icon_expr = str(child.getAttribute('icon_expr')) if child.hasAttribute('link_target'): link_target = str(child.getAttribute('link_target')) else: link_target = '' visible = self._convertToBoolean(child.getAttribute('visible')) remove = child.hasAttribute('remove') and True or False permissions = [] for sub in child.childNodes: if sub.nodeName != 'permission': continue permission = sub.getAttribute('value') permissions.append(permission) action_obj = self.context.getActionObject(category + '/' + id) if remove: if action_obj is not None: # Find the index for the action to remove it actions = self.context.listActions() indexes = [(a.category, a.id) for a in actions] index = indexes.index((category, id)) self.context.deleteActions((index, )) else: if action_obj is None: self.context.addAction(id, title, action, condition, tuple(permissions), category, visible, icon_expr=icon_expr, link_target=link_target) else: action_obj.edit(title=title, action=action, icon_expr=icon_expr, condition=condition, permissions=tuple(permissions), visible=visible, link_target=link_target)
class CachingPolicyNodeAdapter(NodeAdapterBase): """Node im- and exporter for CachingPolicy. """ adapts(ICachingPolicy, ISetupEnviron) def _exportNode(self): """Export the object as a DOM node. """ obj = self.context node = self._doc.createElement('caching-policy') node.setAttribute('name', obj.getPolicyId()) node.setAttribute('predicate', obj.getPredicate()) node.setAttribute('mtime_func', obj.getMTimeFunc()) node.setAttribute('max_age_secs', str(obj.getMaxAgeSecs())) node.setAttribute('no_cache', str(bool(obj.getNoCache()))) node.setAttribute('no_store', str(bool(obj.getNoStore()))) node.setAttribute('must_revalidate', str(bool(obj.getMustRevalidate()))) node.setAttribute('vary', obj.getVary()) node.setAttribute('etag_func', obj.getETagFunc()) s_max_age_secs = obj.getSMaxAgeSecs() if s_max_age_secs is not None: node.setAttribute('s_max_age_secs', str(s_max_age_secs)) node.setAttribute('proxy_revalidate', str(bool(obj.getProxyRevalidate()))) node.setAttribute('public', str(bool(obj.getPublic()))) node.setAttribute('private', str(bool(obj.getPrivate()))) node.setAttribute('no_transform', str(bool(obj.getNoTransform()))) node.setAttribute('enable_304s', str(bool(obj.getEnable304s()))) node.setAttribute('last_modified', str(bool(obj.getLastModified()))) pre_check = obj.getPreCheck() if pre_check is not None: node.setAttribute('pre_check', str(pre_check)) post_check = obj.getPostCheck() if post_check is not None: node.setAttribute('post_check', str(post_check)) return node def _importNode(self, node): """Import the object from the DOM node. """ info = {} policy_id = node.getAttribute('name') info['policy_id'] = str(policy_id) info['predicate'] = str(node.getAttribute('predicate')) info['mtime_func'] = str(node.getAttribute('mtime_func')) info['max_age_secs'] = int(node.getAttribute('max_age_secs')) no_cache = node.getAttribute('no_cache') info['no_cache'] = self._convertToBoolean(no_cache) no_store = node.getAttribute('no_store') info['no_store'] = self._convertToBoolean(no_store) must_revalidate = node.getAttribute('must_revalidate') info['must_revalidate'] = self._convertToBoolean(must_revalidate) info['vary'] = str(node.getAttribute('vary')) info['etag_func'] = str(node.getAttribute('etag_func')) s_max_age_secs = node.getAttribute('s_max_age_secs') if s_max_age_secs != '': info['s_max_age_secs'] = int(s_max_age_secs) proxy_revalidate = node.getAttribute('proxy_revalidate') info['proxy_revalidate'] = self._convertToBoolean(proxy_revalidate) info['public'] = self._convertToBoolean(node.getAttribute('public')) info['private'] = self._convertToBoolean(node.getAttribute('private')) no_transform = node.getAttribute('no_transform') info['no_transform'] = self._convertToBoolean(no_transform) enable_304s = node.getAttribute('enable_304s') info['enable_304s'] = self._convertToBoolean(enable_304s) last_modified = node.getAttribute('last_modified') info['last_modified'] = self._convertToBoolean(last_modified) pre_check = node.getAttribute('pre_check') if pre_check != '': info['pre_check'] = int(pre_check) post_check = node.getAttribute('post_check') if post_check != '': info['post_check'] = int(post_check) self.context.__init__(**info) node = property(_exportNode, _importNode)
class SampleSchemaExtender(object): adapts(ISample) implements(IOrderableSchemaExtender) fields = [ BestBeforeDateField( 'BestBeforeDate', widget=bikaDateTimeWidget(label="Best Before Date", visible={ 'view': 'visible', 'edit': 'visible', 'header_table': 'visible' }, modes=('view', 'edit')), ), ExtStringField( 'Vintage', required=False, widget=StringWidget( label="Vintage", render_own_label=True, size=20, visible={ 'edit': 'visible', 'view': 'visible', 'header_table': 'visible', 'sample_registered': { 'view': 'visible', 'edit': 'visible', 'add': 'edit' }, 'to_be_sampled': { 'view': 'visible', 'edit': 'visible' }, 'sampled': { 'view': 'visible', 'edit': 'visible' }, 'to_be_preserved': { 'view': 'visible', 'edit': 'visible' }, 'sample_due': { 'view': 'visible', 'edit': 'visible' }, 'sample_received': { 'view': 'visible', 'edit': 'visible' }, 'published': { 'view': 'visible', 'edit': 'invisible' }, 'invalid': { 'view': 'visible', 'edit': 'invisible' }, }, ), ), ExtReferenceField( 'Cultivar', required=0, allowed_types=('Cultivar'), relationship='SampleTypeCultivar', format='select', widget=bikaReferenceWidget( label="Cultivar", render_own_label=True, size=20, catalog_name='bika_setup_catalog', base_query={'inactive_state': 'active'}, showOn=True, visible={ 'edit': 'visible', 'view': 'visible', 'header_table': 'visible', 'sample_registered': { 'view': 'visible', 'edit': 'visible', 'add': 'edit' }, 'to_be_sampled': { 'view': 'visible', 'edit': 'visible' }, 'sampled': { 'view': 'visible', 'edit': 'visible' }, 'to_be_preserved': { 'view': 'visible', 'edit': 'visible' }, 'sample_due': { 'view': 'visible', 'edit': 'visible' }, 'sample_received': { 'view': 'visible', 'edit': 'visible' }, 'published': { 'view': 'visible', 'edit': 'invisible' }, 'invalid': { 'view': 'visible', 'edit': 'invisible' }, }, ), ), ] def __init__(self, context): self.context = context def getOrder(self, schematas): default = schematas['default'] # after SamplingDate if 'BestBeforeDate' in default: default.remove('BestBeforeDate') default.insert(default.index('SamplingDate'), 'BestBeforeDate') # after SampleID pos = default.index('SampleID') default.insert(pos, 'Vintage') default.insert(pos, 'Cultivar') return schematas def getFields(self): return self.fields
class MallShippingMethodManagement(BaseShippingMethodManagement): """An adapter which provides IShippingMethodManagement for shop content objects. """ implements(IShippingMethodManagement) adapts(IMall)
class FilterControlPanelAdapter(object): adapts(IPloneSiteRoot) implements(IFilterSchema) def __init__(self, context): registry = getUtility(IRegistry) self.settings = registry.forInterface(IFilterSchema, prefix='plone') def get_disable_filtering(self): return self.settings.disable_filtering def set_disable_filtering(self, value): self.settings.disable_filtering = value def get_nasty_tags(self): return self.settings.nasty_tags def set_nasty_tags(self, value): self.settings.nasty_tags = value def get_stripped_tags(self): return self.settings.stripped_tags def set_stripped_tags(self, value): self.settings.stripped_tags = value def get_custom_tags(self): return self.settings.custom_tags def set_custom_tags(self, value): self.settings.custom_tags = value def get_stripped_attributes(self): return self.settings.stripped_attributes def set_stripped_attributes(self, value): self.settings.stripped_attributes = value def get_stripped_combinations(self): return self.settings.stripped_combinations def set_stripped_combinations(self, value): self.settings.stripped_combinations = value def get_style_whitelist(self): return self.settings.style_whitelist def set_style_whitelist(self, value): self.settings.style_whitelist = value def get_class_blacklist(self): return self.settings.class_blacklist def set_class_blacklist(self, value): self.settings.class_blacklist = value class_blacklist = property(get_class_blacklist, set_class_blacklist) style_whitelist = property(get_style_whitelist, set_style_whitelist) stripped_combinations = property(get_stripped_combinations, set_stripped_combinations) stripped_attributes = property(get_stripped_attributes, set_stripped_attributes) custom_tags = property(get_custom_tags, set_custom_tags) stripped_tags = property(get_stripped_tags, set_stripped_tags) nasty_tags = property(get_nasty_tags, set_nasty_tags) disable_filtering = property(get_disable_filtering, set_disable_filtering)
class MetroMap(object): implements(IMetroMap) adapts(IFolderish) def __init__(self, context): self.context = context @property def _metromap_workflow(self): """All Case Workspaces should have a placeful workflow. In order to render the metromap, this workflow needs to have a metromap_transitions variable which determines the order of the milestones (states) and the transitions between them. Return the workflow required to render the metromap. """ policy_conf = self.context.get(WorkflowPolicyConfig_id) if policy_conf is None: return policy = policy_conf.getPolicyIn() policy_id = policy.getId() wft = api.portal.get_tool('portal_workflow') workflow = wft.getWorkflowById(policy_id) if workflow and workflow.variables.get("metromap_transitions", False): return workflow def get_available_metromap_workflows(self): """Return all globally available workflows with the metromap_transitions variable. """ wft = api.portal.get_tool('portal_workflow') metromap_workflows = [ i for i in wft.objectValues() if i.variables.get("metromap_transitions", False) ] if metromap_workflows == []: return None return metromap_workflows @property def _metromap_transitions(self): """A data structure is stored as a TAL expression on a workflow which determines the sequence of workflow states/milestones used to render the metromap. We need to evaluate the expression and returns the data structure. It consists of a list of dicts each with the workflow state, the transition to the next milestone in the metromap, and the transition required to return to the milestone: [{ 'state': 'new', 'next_transition': 'finalise', 'reopen_transition': 'reset' }, { 'state': 'complete', 'next_transition': 'archive', 'reopen_transition': 'finalise' }, { 'state': 'archived'} ] """ metromap_workflow = self._metromap_workflow if metromap_workflow is None: return [] wfstep = metromap_workflow.variables["metromap_transitions"] tal_expr = wfstep.default_expr expr_context = getExprContext(self.context) metromap_transitions = tal_expr(expr_context) return metromap_transitions @property def metromap_sequence(self): """Return the data structure required for displaying the metromap, derived from the configuration in the metromap_transitions variable of the associated workflow. An OrderedDict is used to provide details such as whether a milestone has already been finished, the transition required to close the current milestone, and the transition required to reopen the previous milestone. In the 'complete' workflow state / milestone it returns the following: OrderedDict([( 'new', { 'transition_title': u'Transfer To Department', 'title': u'New', 'finished': True, # This milestone has been finished 'is_current': False, # Not the current milestone 'reopen_transition': 'reset', # For [Reopen milestone] 'transition_id': 'transfer_to_department' }), ( 'complete', { 'transition_title': u'Submit', 'title': u'Content Complete', 'finished': False, # This milestone isn't finished yet 'is_current': True, # Current milestone: Show [Close milestone] 'reopen_transition': False, 'transition_id': 'submit' }), ( 'archived', { 'transition_title': '', 'title': u'Archived', 'is_current': False, 'finished': False, 'reopen_transition': False, 'transition_id': None }) ]) """ cwf = self._metromap_workflow wft = api.portal.get_tool("portal_workflow") metromap_list = self._metromap_transitions if not metromap_list: return {} try: can_manage = api.user.has_permission( 'ploneintranet.workspace: Manage workspace', user=api.user.get_current(), obj=self.context) except api.exc.UserNotFoundError: raise api.exc.UserNotFoundError( "Unknown user. Do not use Zope rescue user.") current_state = wft.getInfoFor(self.context, "review_state") finished = True sequence = OrderedDict() tasks = self.context.tasks() for index, wfstep in enumerate(metromap_list): state = wfstep['state'] if state == current_state: is_current = True finished = False # keep this for the rest of the loop open_tasks = [x for x in tasks[state] if not x['checked']] else: is_current = False open_tasks = [] # we don't care so performance optimize # last workflow step: consider done if no open tasks left if (state == current_state and index > len(metromap_list) and not open_tasks): finished = True # only current state can be closed if (state == current_state and can_manage and not open_tasks): next_transition = wfstep.get('next_transition', None) else: next_transition = None if next_transition: transition_title = _( cwf.transitions.get(next_transition).title) else: transition_title = '' # reopen only the before-current step, only for admins reopen_transition = None try: next_state = metromap_list[index + 1]["state"] # if this step precedes the current state, it can be reopened if next_state == current_state and can_manage: reopen_transition = wfstep.get('reopen_transition', None) except IndexError: # last step, no next pass sequence[state] = { 'title': _(cwf.states.get(state).title), 'transition_id': next_transition, 'transition_title': transition_title, 'reopen_transition': reopen_transition, 'is_current': is_current, 'finished': finished, } return sequence
class ContentTypeRegistryXMLAdapter(XMLAdapterBase): """XML im- and exporter for ContentTypeRegistry. """ adapts(IContentTypeRegistry, ISetupEnviron) _LOGGER_ID = 'contenttypes' name = 'contenttyperegistry' def _exportNode(self): """Export the object as a DOM node. """ node = self._getObjectNode('object') node.appendChild(self._extractPredicates()) self._logger.info('Content type registry exported.') return node def _importNode(self, node): """Import the object from the DOM node. """ if self.environ.shouldPurge(): self._purgePredicates() self._initPredicates(node) self._logger.info('Content type registry imported.') def _extractPredicates(self): fragment = self._doc.createDocumentFragment() for predicate_id, info in self.context.listPredicates(): child = self._doc.createElement('predicate') child.setAttribute('name', predicate_id) child.setAttribute('predicate_type', info[0].PREDICATE_TYPE) child.setAttribute('content_type_name', info[1]) for argument in self._crackArgs(info[0]): sub = self._doc.createElement('argument') sub.setAttribute('value', argument) child.appendChild(sub) fragment.appendChild(child) return fragment def _purgePredicates(self): self.context.__init__() def _initPredicates(self, node): for child in node.childNodes: if child.nodeName != 'predicate': continue parent = self.context predicate_id = str(child.getAttribute('name')) predicate_type = str(child.getAttribute('predicate_type')) content_type_name = str(child.getAttribute('content_type_name')) if predicate_id not in parent.predicate_ids: parent.addPredicate(predicate_id, predicate_type) arguments = [] for sub in child.childNodes: if sub.nodeName != 'argument': continue arguments.append(str(sub.getAttribute('value'))) parent.getPredicate(predicate_id).edit(*arguments) parent.assignTypeName(predicate_id, content_type_name) _KNOWN_PREDICATE_TYPES = { 'major_minor': lambda x: (','.join(x.major or ()), ','.join(x.minor or ())), 'extension': lambda x: (','.join(x.extensions or ()), ), 'mimetype_regex': lambda x: (x.pattern and x.pattern.pattern or '', ), 'name_regex': lambda x: (x.pattern and x.pattern.pattern or '', ), } def _crackArgs(self, predicate): cracker = self._KNOWN_PREDICATE_TYPES.get(predicate.PREDICATE_TYPE) if cracker is not None: return cracker(predicate) return () # XXX: raise?
class GenericObject2Surf(object): """Generic implementation of IObject2Surf This is meant to be subclassed and not used directly. """ implements(IGenericObject2Surf) adapts(Interface, ISurfSession) _resource = None # stores the surf resource _namespace = None # stores the namespace for this resource _prefix = None def __init__(self, context, session): self.context = context self.session = session @property def prefix(self): """ prefix """ if self._prefix is None: raise NotImplementedError return self._prefix @property def portalType(self): """ portal type """ return self.context.__class__.__name__ @property def namespace(self): """ namespace """ if self._namespace is not None: return self._namespace ttool = getToolByName(self.context, 'portal_types') ptype = self.context.portal_type ns = {self.prefix: '%s#' % ttool[ptype].absolute_url()} surf.ns.register(**ns) self._namespace = getattr(surf.ns, self.prefix.upper()) return self._namespace @property def subject(self): """ subject; will be inserted as rdf:about """ return '%s#%s' % (self.context.absolute_url(), self.rdfId) @property def rdfId(self): """ rdf id; will be inserted as rdf:id """ return self.context.getId().replace(' ', '') @property def resource(self, **kwds): """ Factory for a new Surf resource """ if self._resource is not None: return self._resource try: # pull a new resource from the surf session resource = self.session.get_class(self.namespace[self.portalType])( self.subject) except Exception: if DEBUG: raise logger.exception('RDF marshaller error:') return None resource.bind_namespaces([self.prefix]) resource.session = self.session self._resource = resource return resource def modify_resource(self, resource, *args, **kwds): """We allow modification of resource here """ return resource def write(self, *args, **kwds): """Write its resource into the session """ if self.resource is None: raise ValueError # we modify the resource and then allow subscriber plugins to modify it resource = self.modify_resource(self.resource, *args, **kwds) for modifier in subscribers([self.context], ISurfResourceModifier): modifier.run(resource, self, self.session, *args, **kwds) resource.update() resource.save() return resource
class CourseRequirementEditorsCrowd(LeaderCrowd): """People who can edit requirements of a course""" adapts(ICourse) implements(IRequirementParentCrowd)
class PaypalPayment(object): implements(IPaymentMethod, IPaypalPayment) adapts(Interface) title = _(u'Paypal') description = _('Payment using Paypal') icon = u'++resource++pcommerce_payment_paypal_icon.gif' logo = u'++resource++pcommerce_payment_paypal_logo.gif' def __init__(self, context): self.context = context self.props = getToolByName(self.context, 'portal_properties').paypal_properties def __getattr__(self, name): if self.props.hasProperty(name): return self.props.getProperty(name) raise AttributeError def mailInfo(self, order, lang=None, customer=False): return _('paypal_mailinfo', default=u"Payment processed over Paypal") def verifyPayment(self, order): """""" # TODO: Done before, not yet needed return True def get_paypal_interface_obj(self): context = self.context props = getToolByName(context, 'portal_properties').paypal_properties #TODO: Need to be moved in configlet with description # Enter your test account's API details here. You'll need the 3-token # credentials, not the certificate stuff. #CONFIG = PayPalConfig(API_USERNAME = "******", # API_PASSWORD = "******", # API_SIGNATURE = "AuyTYUFGIfqpMeM0seVte", # DEBUG_LEVEL=0) CONFIG = PayPalConfig(API_USERNAME=props.api_username, API_PASSWORD=props.api_password, API_SIGNATURE=props.api_signature, API_ENVIRONMENT=props.test and 'SANDBOX' or 'PRODUCTION', DEBUG_LEVEL=0) return PayPalInterface(config=CONFIG) def action(self, order): """""" url = '%s/' % (self.context.absolute_url()) props = getToolByName(self.context, 'portal_properties').pcommerce_properties props_paypal = getToolByName(self.context, 'portal_properties').paypal_properties portal_state = getMultiAdapter((self.context, self.context.REQUEST), name=u'plone_portal_state') lang = self.context.REQUEST.get('LANGUAGE', portal_state.default_language()) price = CurrencyAware(order.totalincl) interface = self.get_paypal_interface_obj() cart = IShoppingCart(self.context) cart_products = cart.getProducts() product_titles = [] for product in cart_products: product_titles.append(product['title'] + ' ') button_params = { 'BUTTONCODE': 'ENCRYPTED', 'BUTTONTYPE': 'BUYNOW', 'BUTTONSUBTYPE': 'SERVICES', 'BUYNOWTEXT': 'PAYNOW', 'L_BUTTONVAR0': 'notify_url=%s' % props_paypal.ipn_notify_url, 'L_BUTTONVAR1': 'amount=%.2f' % float(price.getRoundedValue()), 'L_BUTTONVAR2': 'item_name=%s' % "".join(product_titles), 'L_BUTTONVAR3': 'item_number=%s' % order.orderid, 'L_BUTTONVAR4': 'return=%s' % url + 'payment.success', 'L_BUTTONVAR5': 'cancel_return=%s' % url + 'payment.cancel', 'L_BUTTONVAR6': 'no_shipping=1', 'L_BUTTONVAR7': 'no_note=1', 'L_BUTTONVAR8': 'rm=1', 'L_BUTTONVAR11': 'currency_code=EUR' } response = interface.bm_create_button(**button_params) return response.EMAILLINK
class CourseRequirementViewersCrowd(EverybodyCrowd): """People who can view requirements of a course""" adapts(ICourse) implements(IRequirementParentCrowd)
class CommentLineElementConnect(AbstractConnect): """ Connect a comment line to any element item. """ component.adapts(items.ElementItem, items.CommentLineItem) def allow(self, handle, port): """ In addition to the normal check, both line ends may not be connected to the same element. Same goes for subjects. One of the ends should be connected to a UML.Comment element. """ opposite = self.line.opposite(handle) connected_to = self.get_connected(opposite) element = self.element if connected_to is element: return None # Same goes for subjects: if connected_to and \ (not (connected_to.subject or element.subject)) \ and connected_to.subject is element.subject: return None # One end should be connected to a CommentItem: cls = items.CommentItem glue_ok = isinstance(connected_to, cls) ^ isinstance(self.element, cls) if connected_to and not glue_ok: return None # Do not allow to links between the comment and the element if connected_to and element and \ ((isinstance(connected_to.subject, uml2.Comment) and \ self.element.subject in connected_to.subject.annotatedElement) or \ (isinstance(self.element.subject, uml2.Comment) and \ connected_to.subject in self.element.subject.annotatedElement)): return None return super(CommentLineElementConnect, self).allow(handle, port) def connect(self, handle, port): if super(CommentLineElementConnect, self).connect(handle, port): opposite = self.line.opposite(handle) connected_to = self.get_connected(opposite) if connected_to: if isinstance(connected_to.subject, uml2.Comment): connected_to.subject.annotatedElement = self.element.subject else: self.element.subject.annotatedElement = connected_to.subject def disconnect(self, handle): opposite = self.line.opposite(handle) oct = self.get_connected(opposite) hct = self.get_connected(handle) if hct and oct: logger.debug('Disconnecting %s and %s' % (hct, oct)) try: if hct.subject and isinstance(oct.subject, uml2.Comment): del oct.subject.annotatedElement[hct.subject] elif hct.subject and oct.subject: del hct.subject.annotatedElement[oct.subject] except ValueError: logger.debug( 'Invoked CommentLineElementConnect.disconnect() for nonexistant relationship' ) super(CommentLineElementConnect, self).disconnect(handle)
class SectionRequirementEditorsCrowd(InstructorsCrowd): """People who can edit requirements of a section""" adapts(ISection) implements(IRequirementParentCrowd)
class MailControlPanelAdapter(object): adapts(IPloneSiteRoot) implements(IMailSchema) def __init__(self, context): self.context = context self.portal = getSite() registry = getUtility(IRegistry) pprop = getToolByName(self.portal, 'portal_properties') self.encoding = pprop.site_properties.default_charset self.mail_settings = registry.forInterface(IMailSchema, prefix="plone") def get_smtp_host(self): return self.mail_settings.smtp_host def set_smtp_host(self, value): if safe_hasattr(self.mail_settings, 'smtp_host'): self.mail_settings.smtp_host = value smtp_host = property(get_smtp_host, set_smtp_host) def get_smtp_port(self): return getattr(self.mail_settings, 'smtp_port', None) def set_smtp_port(self, value): if safe_hasattr(self.mail_settings, 'smtp_port'): self.mail_settings.smtp_port = value smtp_port = property(get_smtp_port, set_smtp_port) def get_smtp_userid(self): return getattr(self.mail_settings, 'smtp_userid', getattr(self.mail_settings, 'smtp_userid', None)) def set_smtp_userid(self, value): if safe_hasattr(self.mail_settings, 'smtp_userid'): self.mail_settings.smtp_userid = value #SecureMailhost 1.x also uses this: if safe_hasattr(self.mail_settings, '_smtp_userid'): self.mail_settings._smtp_userid = value elif safe_hasattr(self.mail_settings, 'smtp_userid'): self.mail_settings.smtp_uid = value smtp_userid = property(get_smtp_userid, set_smtp_userid) def get_smtp_pass(self): return getattr(self.mail_settings, 'smtp_pass', getattr(self.mail_settings, 'smtp_pwd', None)) def set_smtp_pass(self, value): # Don't update the value, if we don't get a new one if value is not None: if safe_hasattr(self.mail_settings, 'smtp_pass'): self.mail_settings.smtp_pass = value #SecureMailhost 1.x also uses this: if safe_hasattr(self.mail_settings, '_smtp_pass'): self.mail_settings._smtp_pass = value elif safe_hasattr(self.mail_settings, 'smtp_pwd'): self.mail_settings.smtp_pwd = value smtp_pass = property(get_smtp_pass, set_smtp_pass) def get_email_from_name(self): return self.mail_settings.email_from_name def set_email_from_name(self, value): self.mail_settings.email_from_name = value email_from_name = property(get_email_from_name, set_email_from_name) def get_email_from_address(self): return self.mail_settings.email_from_address def set_email_from_address(self, value): self.mail_settings.email_from_address = value email_from_address = property(get_email_from_address, set_email_from_address)
class SkinsToolXMLAdapter(XMLAdapterBase, ObjectManagerHelpers): """XML im- and exporter for SkinsTool. """ adapts(ISkinsTool, ISetupEnviron) _LOGGER_ID = 'skins' name = 'skins' def _exportNode(self): """Export the object as a DOM node. """ node = self._getObjectNode('object') node.setAttribute('default_skin', self.context.default_skin) node.setAttribute('request_varname', self.context.request_varname) node.setAttribute('allow_any', str(bool(self.context.allow_any))) node.setAttribute('cookie_persistence', str(bool(self.context.cookie_persistence))) node.appendChild(self._extractObjects()) node.appendChild(self._extractSkinPaths()) self._logger.info('Skins tool exported.') return node def _importNode(self, node): """Import the object from the DOM node. """ obj = self.context if self.environ.shouldPurge(): obj.default_skin = '' obj.request_varname = 'portal_skin' obj.allow_any = 0 obj.cookie_persistence = 0 self._purgeObjects() self._purgeSkinPaths() if node.hasAttribute('default_skin'): obj.default_skin = str(node.getAttribute('default_skin')) if node.hasAttribute('request_varname'): obj.request_varname = str(node.getAttribute('request_varname')) if node.hasAttribute('allow_any'): allow_any = node.getAttribute('allow_any') obj.allow_any = int(self._convertToBoolean(allow_any)) if node.hasAttribute('cookie_persistence'): persistence = node.getAttribute('cookie_persistence') obj.cookie_persistence = int(self._convertToBoolean(persistence)) self._initObjects(node) self._initSkinPaths(node) self._logger.info('Skins tool imported.') def _extractSkinPaths(self): fragment = self._doc.createDocumentFragment() for k, v in self.context.getSkinPaths(): node = self._doc.createElement('skin-path') node.setAttribute('name', k) for layer in [l.strip() for l in v.split(',') if l.strip()]: child = self._doc.createElement('layer') child.setAttribute('name', layer) node.appendChild(child) fragment.appendChild(node) return fragment def _purgeSkinPaths(self): self.context._getSelections().clear() def _initSkinPaths(self, node): for child in node.childNodes: if child.nodeName != 'skin-path': continue path_id = str(child.getAttribute('name')) if str(child.getAttribute('remove')): self._removeSkin(skin_name=path_id) continue if path_id == '*': for path_id, path in self.context._getSelections().items(): path = self._updatePath(path, child) self.context.addSkinSelection(path_id, path) else: path = '' if child.hasAttribute('based-on'): try: basename = child.getAttribute('based-on') path = self.context._getSelections()[basename] except KeyError: pass if path_id in self.context._getSelections(): oldpath = self.context._getSelections()[path_id].split(',') newlayerstart = child.firstChild for layer in oldpath: if layer not in path: layernode = self._doc.createElement('layer') layernode.setAttribute('name', layer) if oldpath.index(layer) == 0: layernode.setAttribute('insert-before', '*') else: pos = oldpath[oldpath.index(layer) - 1] layernode.setAttribute('insert-after', pos) child.insertBefore(layernode, newlayerstart) path = self._updatePath(path, child) self.context.addSkinSelection(path_id, path) # # Purge and rebuild the skin path, now that we have added our stuff. # Don't bother if no REQUEST is present, e.g. when running unit tests # request = getattr(self.context, 'REQUEST', None) skinnable = aq_parent(aq_inner(self.context)) if request is not None and skinnable is not None: skinnable.clearCurrentSkin() skinnable.setupCurrentSkin(request) def _updatePath(self, path, node): path = [name.strip() for name in path.split(',') if name.strip()] for child in node.childNodes: if child.nodeName != 'layer': continue layer_name = child.getAttribute('name') if layer_name in path: path.remove(layer_name) if child.hasAttribute('insert-before'): insert_before = child.getAttribute('insert-before') if insert_before == '*': path.insert(0, layer_name) continue else: try: index = path.index(insert_before) path.insert(index, layer_name) continue except ValueError: pass elif child.hasAttribute('insert-after'): insert_after = child.getAttribute('insert-after') if insert_after == '*': pass else: try: index = path.index(insert_after) path.insert(index + 1, layer_name) continue except ValueError: pass if not child.hasAttribute('remove'): path.append(layer_name) return str(','.join(path)) def _removeSkin(self, skin_name=None): """ Remove a skin from the skinstool """ skins = self.context.getSkinSelections() if skin_name in skins: self.context.manage_skinLayers(chosen=[skin_name], del_skin=1)
class ShoppingCartAdapter(object): """Adapter that represents the shopping cart for the current user, defined by the adapted context and request. This adapter is responsible for adding, updating and removing items from the cart and storing that information in the user's session, as well as calculating the current cart total. """ implements(IShoppingCart) adapts(Interface, IBrowserRequest) def __init__(self, context, request): self.context = context self.request = request @property def catalog(self): if not hasattr(self, '_catalog'): self._catalog = getToolByName(self.context, 'portal_catalog') return self._catalog def get_items(self): """Get all items currently contained in shopping cart """ # Avoid creating a session if there doesn't exist one yet. bid_manager = getToolByName(self.context, 'browser_id_manager') browser_id = bid_manager.getBrowserId(create=0) if not browser_id: return {} session = self.request.SESSION items = session.get(CART_KEY, {}) return items def get_vat(self): """Return the cart's total VAT as a string """ items = self.get_items() vat_total = Decimal('0.00') for item in items.values(): vat_total += Decimal(item['vat_amount']) return str(vat_total) def get_total(self): """Return the cart's total as a string """ items = self.get_items() total = Decimal('0.00') for item in items.values(): total += Decimal(item['total']) return str(total) def _get_supplier_info(self, context): supplier = self._get_supplier(context) if supplier: supplier_name = supplier.getField('title').get(supplier) supplier_email = supplier.getField('email').get(supplier) return supplier_name, supplier_email return ('', '') def _get_supplier(self, context): """If available, get supplier name and email address """ supplier = None while not INavigationRoot.providedBy(context): field = context.getField('supplier') if field is not None: supplier = field.get(context) if supplier: break context = aq_parent(aq_inner(context)) return supplier def get_suppliers(self): suppliers = [] for itemkey, itemvalue in self.get_items().items(): if 'variation_code' in itemvalue: # Strip of variation suffix from itemkey to get the uid. variation_suffix = itemvalue['variation_code'].strip('var') uid = itemkey[:-len(variation_suffix)] else: uid = itemkey item = self.catalog(UID=uid)[0].getObject() supplier = self._get_supplier(item) suppliers.append(supplier) return suppliers def get_show_prices(self): for item in self.get_items().values(): if item['show_price']: return True return False def has_single_supplier(self): """Returns true if all the suppliers are the same, or there are no suppliers whatsoever. """ suppliers = self.get_suppliers() return all(x == suppliers[0] for x in suppliers) def update_item(self, key, quantity): """Update the quantity of an item. """ session = self.request.SESSION cart_items = session.get(CART_KEY, {}) if key in cart_items: item = cart_items[key] item['quantity'] = int(quantity) item['total'] = str(Decimal(item['price']) * item['quantity']) item['vat_amount'] = str( calc_vat(item['vat_rate'], item['price'], quantity)) cart_items[key] = item session[CART_KEY] = cart_items def _add_item(self, skuCode=None, quantity=1, var1choice=None, var2choice=None): """ Add item to cart """ context = aq_inner(self.context) varConf = IVariationConfig(self.context) # get current items in cart session = self.request.SESSION cart_items = session.get(CART_KEY, {}) variation_code = varConf.variation_code(var1choice, var2choice) # We got no skuCode, so look it up by variation key if not skuCode: skuCode = varConf.sku_code(var1choice, var2choice) item_key = varConf.key(var1choice, var2choice) item = cart_items.get(item_key, None) item_title = context.Title() quantity = int(quantity) vat_rate = Decimal(context.getField('vat').get(context)) supplier_name, supplier_email = self._get_supplier_info(context) has_variations = varConf.hasVariations() if has_variations: variation_dict = varConf.getVariationDict() if not variation_dict[variation_code]['active']: # Item is disabled return False variation_pretty_name = varConf.getPrettyName(variation_code) item_title = '%s - %s' % (context.Title(), variation_pretty_name) price = Decimal(variation_dict[variation_code]['price']) # add item to cart if item is None: item = { 'title': item_title, 'description': context.Description(), 'skucode': skuCode, 'quantity': quantity, 'price': str(price), 'show_price': context.showPrice, 'total': str(price * quantity), 'url': context.absolute_url(), 'supplier_name': supplier_name, 'supplier_email': supplier_email, 'variation_code': variation_code, 'vat_rate': vat_rate, 'vat_amount': str(calc_vat(vat_rate, price)) } # item already in cart, update quantity else: item['quantity'] = item.get('quantity', 0) + quantity item['total'] = str(item['quantity'] * price) item['vat_amount'] = str(calc_vat(vat_rate, price, quantity)) else: price = Decimal(context.Schema().getField('price').get(context)) # add item to cart if item is None: item = { 'title': item_title, 'description': context.Description(), 'skucode': skuCode, 'quantity': quantity, 'price': str(price), 'show_price': context.showPrice, 'total': str(price * quantity), 'url': context.absolute_url(), 'supplier_name': supplier_name, 'supplier_email': supplier_email, 'vat_rate': vat_rate, 'vat_amount': str(calc_vat(vat_rate, price)) } # item already in cart, update quantitiy else: item['quantity'] = item.get('quantity', 0) + quantity item['total'] = str(item['quantity'] * price) item['vat_amount'] = str(calc_vat(vat_rate, price, quantity)) # store cart in session cart_items[item_key] = item session[CART_KEY] = cart_items return True def add_item(self, skuCode=None, quantity=1, var1choice=None, var2choice=None): """Add item to cart and redirect to referer. The item must be identified by either its skuCode if it is an item without variations, or by its variation key. """ context = aq_inner(self.context) ptool = getToolByName(context, 'plone_utils') # Add item to cart success = self._add_item(skuCode, quantity, var1choice, var2choice) if success: ptool.addPortalMessage( _(u'msg_item_added', default=u'Added item to cart.'), 'info') else: ptool.addPortalMessage( _(u'msg_item_disabled', default=u'Item is disabled and can\'t be added.'), 'error') # redirect to referer referer = self.request.get('HTTP_REFERER', context.absolute_url()) if referer == 'localhost': referer = context.absolute_url() self.request.response.redirect(referer) def _remove_item(self, key): """Remove the item with the given key from the cart. """ session = self.request.SESSION cart_items = session.get(CART_KEY, {}) if key in cart_items: del cart_items[key] session[CART_KEY] = cart_items def remove_item(self): """Remove an item from cart. """ context = aq_inner(self.context) ptool = getToolByName(context, 'plone_utils') # remove_item doesn't expect skuCode but item keys - rename! skuCode = self.request.get('skuCode') if skuCode: self._remove_item(skuCode) ptool.addPortalMessage( _(u'msg_cart_updated', default=u"Cart updated."), 'info') referer = self.request.get('HTTP_REFERER', context.absolute_url()) self.request.response.redirect(referer) return def purge_cart(self): """Remove all items from cart. """ session = self.request.SESSION session[CART_KEY] = {} context = aq_inner(self.context) ptool = getToolByName(context, 'plone_utils') ptool.addPortalMessage( _(u'msg_cart_emptied', default=u"Cart emptied."), 'info') referer = self.request.get('HTTP_REFERER', context.absolute_url()) self.request.response.redirect(referer) return def update_cart(self): """Update cart contents. """ context = aq_inner(self.context) ptool = getToolByName(context, 'plone_utils') # first delete items with quantity 0 del_items = [] # XXX - these are not skuCodes but item keys - rename! for skuCode in self.get_items().keys(): try: qty = int(float(self.request.get('quantity_%s' % skuCode))) if qty == 0: del_items.append(skuCode) except (ValueError, TypeError): ptool.addPortalMessage( _(u'msg_cart_invalidvalue', default=u"Invalid Values specified. Cart not updated."), 'error') referer = self.request.get('HTTP_REFERER', context.absolute_url()) self.request.response.redirect(referer) return for skuCode in del_items: self._remove_item(skuCode) # now update quantities (and VAT amounts, done by update_item) for skuCode, item in self.get_items().items(): quantity = int(float(self.request.get('quantity_%s' % skuCode))) if quantity != item['quantity'] and quantity != 0: self.update_item(skuCode, quantity) ptool.addPortalMessage( _(u'msg_cart_updated', default=u"Cart updated."), 'info') referer = self.request.get('HTTP_REFERER', context.absolute_url()) self.request.response.redirect(referer) return
class LDVideoData(LDAudioData): adapts(IVideo) _type = 'VideoObject'
class EditableSchema(object): """ Zope 3 schema adapter to allow addition/removal of schema fields XXX this needs to be made threadsafe """ implements(IEditableSchema) adapts(IInterface) def __init__(self, schema): self.schema = schema def addField(self, field, name=None): """ Add a field """ if name is None: name = field.__name__ if self.schema._InterfaceClass__attrs.has_key(name): raise ValueError, "%s schema already has a '%s' field" % (self.schema.__identifier__, name) self.schema._InterfaceClass__attrs[name] = field if hasattr(self.schema, '_v_attrs'): self.schema._v_attrs[name] = field field.interface = self.schema def removeField(self, name): """ Remove a field """ try: self.schema[name].interface = None del self.schema._InterfaceClass__attrs[name] if hasattr(self.schema, '_v_attrs'): del self.schema._v_attrs[name] except KeyError: raise ValueError, "%s schema has no '%s' field" % (self.schema.__identifier__, name) def moveField(self, field_id, new_pos): """ Move a field to the (new_pos)th position in the schema's sort order (indexed beginning at 0). Schema fields are assigned an 'order' attribute that increments for each new field instance. We shuffle these around in case it matters anywhere that they're unique. """ moving_field = self.schema[field_id] ordered_field_ids = [name for (name, field) in sortedFields(self.schema)] # make sure this is sane if not isinstance(new_pos, int): raise IndexError, 'The new field position must be an integer.' if new_pos < 0: raise IndexError, 'The new field position must be greater than 0.' if new_pos >= len(ordered_field_ids): raise IndexError, 'The new field position must be less than the number of fields.' # determine which fields we have to update the order attribute on cur_pos = ordered_field_ids.index(field_id) if new_pos == cur_pos: # no change; short circuit return elif new_pos < cur_pos: # walking backwards, we can't use -1 as the endpoint b/c that means # the end of the list slice_end = new_pos - 1 if slice_end == -1: slice_end = None intervening_fields = [self.schema[field_id] for field_id in ordered_field_ids[cur_pos - 1:slice_end:-1]] elif new_pos > cur_pos: intervening_fields = [self.schema[field_id] for field_id in ordered_field_ids[cur_pos + 1:new_pos + 1]] # do a little dance prev_order = moving_field.order for field in intervening_fields: order_buffer = field.order field.order = prev_order prev_order = order_buffer moving_field.order = prev_order
class LDSiteData(object): implements(ILDData) adapts(ISiteRoot) def __init__(self, context): self.context = context def get_data(self): registry = getUtility(IRegistry) btype = registry.get('castle.business_type', None) bname = registry.get('castle.business_name', None) utils = Utils(self.context, getRequest()) if not btype and bname: # return subset that uses site name, org type registry = getUtility(IRegistry) site_settings = registry.forInterface(ISiteSchema, prefix="plone", check=False) return { "@context": "http://schema.org", "@type": 'Organization', "name": site_settings.site_title, "url": utils.get_public_url(), "logo": { "@type": "ImageObject", "url": getSiteLogo() } } data = { "@context": "http://schema.org", "@type": btype, "name": bname, "url": utils.get_public_url(), 'telephone': registry.get('castle.business_telephone', ''), "logo": { "@type": "ImageObject", "url": getSiteLogo() } } address = registry.get('castle.business_address', None) if address: data['address'] = { '@type': 'PostalAddress', 'streetAddress': address, 'addressLocality': registry.get('castle.business_city', ''), 'addressRegion': registry.get('castle.business_state', ''), 'postalCode': registry.get('castle.business_postal_code', ''), 'addressCountry': registry.get('castle.business_country', '') } coordinates = registry.get('castle.business_coordinates', '') if coordinates: try: coordinates = json.loads(coordinates) except: coordinates = None if coordinates: data['geo'] = { '@type': 'GeoCoordinates', 'latitude': coordinates.get('lat', ''), 'longitude': coordinates.get('lng', '') } days = registry.get('castle.business_days_of_week', []) hours = [] if days: hours.append({ '@type': "OpeningHoursSpecification", 'dayOfWeek': days, 'opens': registry.get('castle.business_opens', ''), 'closes': registry.get('castle.business_closes', ''), }) for special in registry.get('castle.business_special_hours', []) or []: if special.count('|') != 2: continue day, opens, closes = special.split('|') hours.append({ '@type': "OpeningHoursSpecification", 'dayOfWeek': day, 'opens': opens, 'closes': closes }) if hours: data['openingHoursSpecification'] = hours menu = registry.get('castle.business_menu_link', None) if menu: data["menu"] = menu if registry.get('castle.business_accepts_reservations', False): data["acceptsReservations"] = "True" try: data.update(json.loads( registry.get('castle.business_additional_configuration', '{}'))) except: pass return data
class BaseItem(BaseFeedData): implements(IFeedItem) adapts(IItem, IFeed) def __init__(self, context, feed): self.context = context self.feed = feed self.pm = self.feed.pm @lazy_property def creator(self): if hasattr(self.context, 'Creator'): return self.context.Creator() @lazy_property def author(self): member = self.pm.getMemberById(self.creator) return member @property def author_name(self): author = self.author if author and hasattr(author, 'getProperty'): return author.getProperty('fullname') @property def author_email(self): author = self.author if author and hasattr(author, 'getProperty'): return author.getProperty('email') @property def body(self): if hasattr(self.context, 'getText'): return self.context.getText() elif hasattr(self.context, 'text'): if isinstance(self.context.text, (str, unicode)): return self.context.text elif hasattr(self.context.text, 'output'): return self.context.text.output return self.description content_core_template = ViewPageTemplateFile("templates/content_core.pt") def render_content_core(self): self.request = self.context.REQUEST return self.content_core_template() @property def link(self): url = self.base_url if self.context.portal_type in self.feed.view_action_types: url = url + '/view' return url guid = link @property def has_enclosure(self): return IFileContent.providedBy(self.context) @lazy_property def file(self): if self.has_enclosure: return self.context.getFile() @property def file_url(self): url = self.base_url fi = self.file if fi is not None: filename = fi.getFilename() if filename: url += '/@@download/file/' + filename return url @property def file_length(self): return self.file.get_size() @property def file_type(self): return self.file.getContentType()
class MilestonesProvider(Explicit): implements(IContentProvider) adapts(Interface, IDefaultBrowserLayer, IBrowserView) def __init__(self, context, request, view): self.__parent__ = view self.view = view self.context = context self.request = request # From IContentProvider def update(self): catalog_tool = getToolByName(self.context, 'portal_catalog') portal_path = getToolByName(self.context, 'portal_url').getPortalPath() path = '/'.join(self.context.getPhysicalPath()) # at portal, so we show only active projects if portal_path == path: pv = getMultiAdapter((self.context, self.request), name=u'projectview') path = pv.getActiveProjectPaths() now = DateTime() self.today = DateTime(now.year(), now.month(), now.day()) self.NameDays = [] day = self.today for i in range(7): self.NameDays.append(day.aDay()) day += 1 query1 = { 'portal_type': 'Milestone', 'end': { "query": [self.today - 1], "range": "max" }, 'review_state': 'active', 'path': path, } self.late_milestones = catalog_tool.searchResults( query1, sort_on='end', ) query2 = { 'portal_type': 'Milestone', 'review_state': 'active', 'end': { "query": [self.today, self.today + 14], "range": "minmax" }, 'path': path, } brains = catalog_tool.searchResults( query2, sort_on='end', ) self.next_14_days_cal = [[None] * 7, [None] * 7] self.next_14_days_milestones = {} day = self.today for i in range(2): for j in range(7): self.next_14_days_cal[i][j] = day.day() day += 1 self.next_14_days_cal[0][0] = "TODAY" day = self.today + 1 self.next_14_days_cal[0][1] = "%s %s" % (day.aMonth(), day.day()) for b in brains: diff = int(b.end - self.today) weekno = diff / 7 if weekno > 1: continue self.next_14_days_milestones.setdefault(weekno, {}).setdefault( diff % 7, []).append(b) render = ZopeTwoPageTemplateFile('milestones.pt')