def get_held_positions(self): """Returns the held position that have been linked to this position """ intids = getUtility(IIntIds) catalog = getUtility(ICatalog) position_intid = intids.getId(self) contact_relations = catalog.findRelations( {'to_id': position_intid, 'from_interfaces_flattened': IHeldPosition, 'from_attribute': 'position'}) return [c.from_object for c in contact_relations]
def get_held_positions(self): """Returns the held position that have been linked to this position """ intids = getUtility(IIntIds) catalog = getUtility(ICatalog) position_intid = intids.getId(self) contact_relations = catalog.findRelations({ 'to_id': position_intid, 'from_interfaces_flattened': IHeldPosition, 'from_attribute': 'position' }) return [c.from_object for c in contact_relations]
def __call__( self, fieldname=None, direction='thumbnail', height=None, width=None, scale=None, **parameters ): storage = Storage(self.context) self.box = storage.read(fieldname, scale) if self.box: direction = 'down' else: registry = getUtility(IRegistry) settings = registry.forInterface(ISettings) if scale in settings.cropping_for: direction = 'down' return super(CroppingImageScalingFactory, self).__call__( fieldname=fieldname, direction=direction, height=height, width=width, scale=scale, **parameters )
def _get_vocabulary_value(self, obj, value): if not value: return value vocabulary = self.field.vocabulary if not vocabulary: vocabularyName = self.field.vocabularyName if vocabularyName: vocabulary = getUtility(IVocabularyFactory, name=vocabularyName)(obj) if vocabulary: try: term = vocabulary.getTermByToken(value) except LookupError: term = None else: term = None if term: title = term.title if not title: return value else: return title else: return value
def _autocrop_scales(context): cropping_registry = getUtility(IRegistry) settings = cropping_registry.forInterface(ISettings) scale_names = settings.cropping_for request = getRequest() cropper = getMultiAdapter((context, request), name="crop-image") for fname in FIELDNAMES: field = getattr(context, fname, None) if not field: continue real_width, real_height = map(float, field.getImageSize()) # some images are not initialized properly, in which case they # get -1 for width and height. In this case, don't crop if real_width == -1 or real_height == -1: continue allowed = getAllowedSizes() for scale_name in scale_names: if scale_name not in allowed: continue width, height = map(float, allowed[scale_name]) coords = _initial_size(real_width, real_height, width, height) cropper._crop(fname, scale_name, coords)
def _get_vocabulary_value(self, obj, value): if not value: return value vocabulary = self.field.vocabulary if not vocabulary: vocabularyName = self.field.vocabularyName if vocabularyName: vocabulary = getUtility(IVocabularyFactory, name=vocabularyName)(obj) if vocabulary: try: term = vocabulary.getTermByToken(value) except LookupError: term = None else: term = None if term: title = term.title if not title: return value else: return title else: return value
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() sm.getUtility(INameChooserConfiglet).short_url_enabled = True # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) setattr(root, 'principalId', 'zope.mgr') # space space = ContentSpace(title=u'Space') event.notify(ObjectCreatedEvent(space)) root['space'] = space setattr(root, 'principal', getUtility(IAuthentication).getPrincipal('zope.mgr')) # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) endInteraction()
def test_digestemail_by_folder(self): tool = get_tool() tool.switch_subscription(TEST_USER_ID, self.workspace, 'daily', True) api.content.create(self.folder, 'Document', 'document') notify(ObjectModifiedEvent(self.folder.document)) cb = self.folder.manage_cutObjects(['document']) self.workspace.manage_pasteObjects(cb) storage = tool.get_storage('daily') activity_info = dict(storage.pop()) subscriber = ('member', TEST_USER_ID) message_view = self.portal.unrestrictedTraverse('digestemail-byfolder') message_view.info = activity_info[subscriber] message_view.user_type, message_view.user_value = subscriber from bs4 import BeautifulSoup html = message_view() soup = BeautifulSoup(html) self.assertEqual([e.text.strip() for e in soup.find_all('h3')], [u'Items moved into the folder', u'New items', u'Modified items']) # @TODO: mock mail host to actually test email_action = getUtility(IDigestAction, name='digestemail-byfolder') email_action(self.portal, storage, subscriber, activity_info[subscriber])
def get_media_metadata(self): """ get the media metadata from remote """ pprop = getUtility(IPropertiesTool) mediacore_prop = getattr(pprop, "mediacore_properties", None) SERVE_VIDEO = mediacore_prop and mediacore_prop.base_uri or "/file_url/media_unique_id?slug=%s" if self.data.video_security: SECRET = mediacore_prop and mediacore_prop.secret or "" else: SECRET = "" remoteurl = self.data.video_url url = list(urlparse.urlparse(remoteurl)[:2]) url.extend(4 * [""]) url = urlparse.urlunparse(url) media_slug = remoteurl.split("/")[-1] try: data = urllib2.urlopen(url + SERVE_VIDEO % media_slug, timeout=DEFAULT_TIMEOUT).read() except: logger.exception("Error getting data") data = None if data: data = cjson.decode(data) video_remoteurl = "%s/files/%s" % (url, data["unique_id"]) data["file_remoteurl"] = self.getVideoLink(video_remoteurl, data["file_id"], SECRET) return data
def allCountries(self): """ Method that returns all countries from the vocabulary """ utility = zapi.getUtility(ICountriesStates) results = TitledVocabulary.fromTitles(utility.countries) return results._terms
def applySettings(gscontext): # don't run as a step for other profiles if gscontext.readDataFile('jqueryui.txt') is None: return record = getUtility(IRegistry).forInterface(IJQueryUIPlugins) verify_jsregistry(record)
def validate(self, value): if self.widget.mode == HIDDEN_MODE: return True self.configlet = getUtility(ICaptchaConfiglet) if not self.configlet.verify(self.request): raise WrongCaptchaCode else: return True
def addPortletToContext(context, portlet, columnName="plone.rightcolumn"): if not portlet: return column = getUtility(IPortletManager, columnName) manager = getMultiAdapter((context, column), IPortletAssignmentMapping) chooser = INameChooser(manager) manager[chooser.chooseName(None, portlet)] = portlet
def update(self): includeInplaceSource(jssource) request = self.request context = self.context context = IMembersAware(getSpace(context), None) if context is None: return notifications = [] for name, notification in getAdapters((self.context,), IContentNotification): notifications.append((notification.title, name, notification)) notifications.sort() self.notifications = [notification for title, name, notification in notifications] members = [] spaces = list(getUtility(ICatalog).searchResults( type={'any_of': ('content.space',)}, traversablePath={'any_of': [context]})) spaces.append(context) for space in spaces: for member in space.members.values(): principal = member.principal if principal is None or principal.id=='unknown': continue title = member.title position = -1 for pos, memb in enumerate(members): if member.title in memb: position = pos if position != -1: members[position][1]['spaces'].append(space.title) else: members.append((title, {'id': principal.id, 'title': title, 'spaces': [space.title] })) self.renderDict = self.createRenderDict(sorted(spaces, key=lambda sp: sp.title), members) self.members = [val[1] for val in members] if 'notifications.save' in request: checked = {} for id in request.get('notifications', ()): pid, nid = id.split(':', 1) data = checked.setdefault(nid, []) data.append(pid) for notification in self.notifications: data = checked.get(notification.type, []) for member in self.members: if member['id'] in data: notification.subscribe(member['id']) else: notification.unsubscribe(member['id']) IStatusMessage(request).add( _('Email notification subscriptions have been updated.'))
def _scales(self, fieldname): constrain_cropping = self._editor_settings.constrain_cropping cropping_for = self._editor_settings.cropping_for allowed_sizes = getUtility(IAvailableSizes)() or [] sizes_iterator = sorted(allowed_sizes.iteritems(), key=itemgetter(1)) for scale_id, target_size in sizes_iterator: if constrain_cropping and scale_id not in cropping_for: continue yield scale_id, target_size
def render(self, *args, **kwargs): ''' Processa a lista de feeds ''' member = self._mt.getAuthenticatedMember() self._username = member and member.getUserName() or '' registry = getUtility(IRegistry) settings = registry.forInterface(ISCExternalContentSettings) for feed in settings.rss_sources: self.processa_feed(*feed.split(',')) url = self.context.absolute_url() return self.context.REQUEST.RESPONSE.redirect(url)
def render(self, *args, **kwargs): ''' Processa a lista de feeds ''' member = self._mt.getAuthenticatedMember() self._username = member and member.getUserName() or '' registry = getUtility(IRegistry) settings = registry.forInterface(ISCExternalContentSettings) for feed in settings.rss_sources: self.processa_feed(*feed.split(',')) url = self.context.absolute_url() return self.context.REQUEST.RESPONSE.redirect(url)
def getMenuForReplies(self): self.menu = {} if self.get_replies() is None: return for reply in list(self.get_replies()): self.menu[reply['id']] = getUtility( IBrowserMenu, name='plone_contentmenu_workflow').getMenuItems( reply['comment'], self.request) if len(self.menu[reply['id']]): del self.menu[reply['id']][-1]
def getMenuForReplies(self): self.menu = {} if self.get_replies() is None: return for reply in list(self.get_replies()): self.menu[reply['id']] = getUtility( IBrowserMenu, name='plone_contentmenu_workflow' ).getMenuItems(reply['comment'], self.request) if len(self.menu[reply['id']]): del self.menu[reply['id']][-1]
def check_valid_email(value): '''Check if value is a valid email address''' if not value: return True portal = getUtility(ISiteRoot) reg_tool = getToolByName(portal, 'portal_registration') if value and reg_tool.isValidEmail(value): return True else: raise InvalidEmailAddress
def update(self): self.membership = getToolByName(self.context, 'portal_membership') super(EditBar, self).update() #MENU self.menus = {} for menu in MENUS: self.menus[menu] = getUtility( IBrowserMenu, name=menu, ).getMenuItems(self.context, self.request) #remove advanced workflow action if exists if len(self.menus["plone_contentmenu_workflow"]): del self.menus["plone_contentmenu_workflow"][-1] self.context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state') self.object_actions = self.context_state.actions('object') try: adapter = queryAdapter(self.context, IStringSubstitution, 'review_state_title') if adapter: self.review_state = adapter() else: self.review_state = None except WorkflowException: self.review_state = None self.object_uid = unicode(IUUID(self.context, u"")) self.group = get_group(self.context) self.isGroup = self.context.portal_type in ( "collective.rcse.group", "collective.rcse.proxygroup" ) self.member = self.portal_state.member() if self.member is not None and self.group is not None: self.memberid = self.member.getId() getroles = self.group.manage_getUserRolesAndPermissions # TODO Remove security manage save and reset when # https://github.com/zopefoundation/AccessControl/issues/4 # is fixed sm = getSecurityManager() self.roles = getroles(self.memberid) setSecurityManager(sm) self.isOwner = self.hasRole("Owner") # owner = self.group.getOwner() # if owner: # self.isOwner = self.memberid == owner.getId() self.isManager = self.hasRole("Manager") self.isSiteAdmin = self.hasRole("Site Administrator") self.isContributor = self.hasRole("Contributor")
def _scales(self, fieldname): constrain_cropping = self._editor_settings.constrain_cropping cropping_for = self._editor_settings.cropping_for allowed_sizes = getUtility(IAvailableSizes)() or [] sizes_iterator = sorted( six.iteritems(allowed_sizes), key=itemgetter(1) ) for scale_id, target_size in sizes_iterator: if constrain_cropping and scale_id not in cropping_for: continue yield scale_id, target_size
def __init__(self, context, request, *args, **kwargs): super(Galleria, self).__init__(context, request, *args, **kwargs) context = aq_inner(context) self.context = context self.request = request self.ptype = self.context.portal_type self.registry = getUtility(IRegistry) self.settings = self.registry.forInterface(IGeneralSettings) self.flickrplugin = self.registry.forInterface(IFlickrPlugin) self.picasaplugin = self.registry.forInterface(IPicasaPlugin) self.historyplugin = self.registry.forInterface(IHistoryPlugin) self.isVideo = self.plugins(plname='youtube') or self.plugins(plname='vimeo') or self.plugins(plname='dailymotion')
def kssModifyState(self, country=None, search=0): """ This method is used to update the province drop down when adding a person or organization and also from the advanced search template that's why it has some ugly logic. Perhaps should be divided in two methods, one that gets called from the ct, and another one that gets called from the search template """ context = aq_inner(self.context) ksscore = self.getCommandSet('core') utility = zapi.getUtility(ICountriesStates) if not search and not country: # This is necessary for the inline edition country = context.getCountry() if country and country != '--': # I will be here if the country has -- selected, in which case # i should return all states possible results = TitledVocabulary.fromTitles(utility.states(country=country)) else: # I will be here if the country has something selected, in which # case i should return a filtered state list results = TitledVocabulary.fromTitles(utility.states()) if search: selector = ksscore.getHtmlIdSelector('form.state') result_html = u'<select name="form.state" id="form.state">' else: selector = ksscore.getHtmlIdSelector('state') result_html = u'<select name="state" id="state">' for i in results._terms: aux = _(i.value) value = zope.i18n.translate(aux, context=self.request) aux = _(i.title) title = zope.i18n.translate(aux, context=self.request) if not search and context.state == value: result_html += (u'<option value="%s" selected="True">%s' '</option>' % (value,title)) else: result_html += (u'<option value="%s">%s</option>' % (value,title)) result_html += u'</select>' # I replace the existing drop down ksscore.replaceHTML(selector, result_html) # and finally we render return self.render()
def update(self): self.membership = getToolByName(self.context, 'portal_membership') super(EditBar, self).update() #MENU self.menus = {} for menu in MENUS: self.menus[menu] = getUtility( IBrowserMenu, name=menu, ).getMenuItems(self.context, self.request) #remove advanced workflow action if exists if len(self.menus["plone_contentmenu_workflow"]): del self.menus["plone_contentmenu_workflow"][-1] self.context_state = getMultiAdapter((self.context, self.request), name=u'plone_context_state') self.object_actions = self.context_state.actions('object') try: adapter = queryAdapter(self.context, IStringSubstitution, 'review_state_title') if adapter: self.review_state = adapter() else: self.review_state = None except WorkflowException: self.review_state = None self.object_uid = unicode(IUUID(self.context, u"")) self.group = get_group(self.context) self.isGroup = self.context.portal_type in ( "collective.rcse.group", "collective.rcse.proxygroup") self.member = self.portal_state.member() if self.member is not None and self.group is not None: self.memberid = self.member.getId() getroles = self.group.manage_getUserRolesAndPermissions # TODO Remove security manage save and reset when # https://github.com/zopefoundation/AccessControl/issues/4 # is fixed sm = getSecurityManager() self.roles = getroles(self.memberid) setSecurityManager(sm) self.isOwner = self.hasRole("Owner") # owner = self.group.getOwner() # if owner: # self.isOwner = self.memberid == owner.getId() self.isManager = self.hasRole("Manager") self.isSiteAdmin = self.hasRole("Site Administrator") self.isContributor = self.hasRole("Contributor")
def validatevideo(data): if data.file is None and data.remoteUrl is None: msg = _(u"You must provide at least a file or a link") raise InvalidVideo(msg) if data.file: registry = getUtility(IRegistry) mime_types = registry[SETTING_MIME_TYPES] mime_type = data.file.contentType if mime_type not in mime_types: msg = _( u"The file must be a video. You are trying to use a " u"'${mime_type}'", mapping={"mime_type": mime_type}) raise InvalidVideo(msg)
def __init__(self, context, request, *args, **kwargs): super(Galleria, self).__init__(context, request, *args, **kwargs) context = aq_inner(context) self.context = context self.request = request self.ptype = self.context.portal_type self.registry = getUtility(IRegistry) self.settings = self.registry.forInterface(IGeneralSettings) self.facebookplugin = self.registry.forInterface(IFaceBookPlugin) self.flickrplugin = self.registry.forInterface(IFlickrPlugin) self.picasaplugin = self.registry.forInterface(IPicasaPlugin) self.historyplugin = self.registry.forInterface(IHistoryPlugin) self.isVideo = self.plugins(plname='youtube') or self.plugins( plname='vimeo') or self.plugins(plname='dailymotion')
def patches(self): ztc.utils.setupCoreSessions(self.app) # Show every exception except redirects self.portal.error_log._ignored_exceptions = ('Redirect',) # Use MockMailHost mockhost = MockMailHost('MailHost') self.portal._delObject('MailHost') self.portal._setObject('MailHost', mockhost) sm = self.portal.getSiteManager() sm.registerUtility(mockhost, provided=IMailHost) # Be sure we use MockMailHost self.failUnless(isinstance(self.portal.MailHost, MockMailHost)) self.failUnless(isinstance(getUtility(IMailHost), MockMailHost)) self.failUnless(isinstance(getToolByName(self.portal, 'MailHost'), MockMailHost)) self.portal.MailHost.reset()
def generateUniqueId (self, type_name, batch_size = None): """Generate a unique ID for sub objects of the client """ IdServer = getUtility(interfaces.IIdServer)() # get prefix prefixes = self.bika_setup.getPrefixes() type_name.replace(' ', '') for d in prefixes: if type_name != d['portal_type']: continue prefix, padding = d['prefix'], d['padding'] if batch_size: next_id = str(IdServer.generate_id(prefix, batch_size = batch_size)) else: next_id = str(IdServer.generate_id(prefix)) if padding: next_id = next_id.zfill(int(padding)) return '%s%s' % (prefix, next_id) if batch_size: next_id = str(IdServer.generate_id(type_name, batch_size = batch_size)) else: next_id = str(IdServer.generate_id(type_name)) return '%s_%s' % (type_name.lower(), next_id)
def _callFUT(self, *args, **kw): from zope.component._api import getUtility return getUtility(*args, **kw)
def _editor_settings(self): registry = getUtility(IRegistry) settings = registry.forInterface(ISettings) return settings
def _editor_settings(self): registry = getUtility(IRegistry) settings = registry.forInterface(ISettings) return settings
def States( context ): utility = zapi.getUtility(ICountriesStates) return TitledVocabulary.fromTitles(utility.allStateValues())
def sendNotification( order, event ): """ sends out email notifications to merchants and clients based on settings. We may not raise or pass exceptions: the payment has already happened and everything else is our, not the customer's fault. """ portal = getPortal() mailer = getToolByName(portal, 'MailHost') settings = interfaces.IGetPaidManagementOptions( portal ) formatter = getUtility(ICurrencyFormatter) currency = formatter.currency(portal) store_url = portal.absolute_url() order_contents = u'\n'.join([u' '.join((str(cart_item.quantity), safe_unicode(cart_item.name), u"@%0.2f" % (cart_item.cost,), 'total: %s %0.2f' % (currency, cart_item.cost*cart_item.quantity,), )) for cart_item in order.shopping_cart.values()]) # Auth if event.destination == workflow_states.order.finance.CHARGEABLE and \ event.source in ( workflow_states.order.finance.REVIEWING, workflow_states.order.finance.PAYMENT_DECLINED ): if settings.send_merchant_auth_notification and \ settings.contact_email: sendMerchantEmail("merchant-new-order", settings.merchant_auth_email_notification_template, settings, order, store_url, order_contents, mailer) if settings.send_customer_auth_notification: sendCustomerEmail("customer-new-order", settings.customer_auth_email_notification_template, settings, order, store_url, order_contents, mailer) # Charged if event.destination == workflow_states.order.finance.CHARGED and \ event.source == workflow_states.order.finance.CHARGING: if settings.send_merchant_charge_notification and \ settings.contact_email: sendMerchantEmail("merchant-charge-order", settings.merchant_charge_email_notification_template, settings, order, store_url, order_contents, mailer) if settings.send_customer_charge_notification: sendCustomerEmail("customer-charge-order", settings.customer_charge_email_notification_template, settings, order, store_url, order_contents, mailer) # Decline if event.destination == workflow_states.order.finance.PAYMENT_DECLINED and \ event.source in ( workflow_states.order.finance.CHARGING, workflow_states.order.finance.REVIEWING ): if settings.send_merchant_decline_notification and \ settings.contact_email: sendMerchantEmail("merchant-decline-order", settings.merchant_decline_email_notification_template, settings, order, store_url, order_contents, mailer) if settings.send_customer_decline_notification: sendCustomerEmail("customer-decline-order", settings.customer_decline_email_notification_template, settings, order, store_url, order_contents, mailer)
def _callFUT(self, *args, **kw): from zope.component._api import getUtility return getUtility(*args, **kw)
def Countries( context ): utility = zapi.getUtility(ICountriesStates) return TitledVocabulary.fromTitles(utility.countries)
def __init__(self, schema): state = self.__dict__ state["__registry__"] = getUtility(IRegistry) state["__proxies__"] = {} state["__schema__"] = schema alsoProvides(self, schema)
def allStates(self): """ Method that returns all states from the vocabulary """ utility = zapi.getUtility(ICountriesStates) return utility.allStateValues()
def socialLinksProduct(self): portal = getUtility(ISiteRoot) quickinstaller_tool = getToolByName(portal, 'portal_quickinstaller') return quickinstaller_tool.isProductInstalled('sc.social.bookmarks')
def __init__(self, schema): state = self.__dict__ state["__registry__"] = getUtility(IRegistry) state["__proxies__"] = {} state["__schema__"] = schema alsoProvides(self, schema)