def get_uid(value): """Takes a brain or object and returns a valid UID. In this case, the object may come from portal_archivist, so we will need to do a catalog query to get the UID of the current version """ if not value: return '' # Is value a brain? if ICatalogBrain.providedBy(value): value = value.getObject() # validate UID uid = value.UID() uc = get_tool('uid_catalog') if uc(UID=uid): # The object is valid return uid # Otherwise the object is an old version brains = uc(portal_type=value.portal_type, Title=value.Title()) if not brains: # Cannot find UID raise RuntimeError('The UID for %s/%s cannot be found!' % (value.portal_type, value.Title())) if len(brains) > 1: # Found multiple objects, this is a failure raise RuntimeError('Searching for %s/%s returned multiple objects.' % (value.portal_type, value.Title())) return brains[0].UID
def getdsmetadata(ds): # TODO: support brain, obj and uuid string (URI as well?) # extract info about files if ICatalogBrain.providedBy(ds): ds = ds.getObject() # TODO: try to use brains only here # url: ds.getURL() # id: ds.UID, # description: ds.Description # start with metadata annotation md = { #'@context': { }, '@id': IUUID(ds), '@type': ds.portal_type, 'url': ds.absolute_url(), 'id': IUUID(ds), 'title': ds.title, 'description': ds.description, } md.update(IBCCVLMetadata(ds)) dlinfo = IDownloadInfo(ds) md.update({ 'mimetype': dlinfo['contenttype'], 'filename': dlinfo['filename'], 'file': dlinfo['url'], }) return md
def linked(item, value, with_tooltip=True): """Takes an item (object or brain) and returns a HTML snippet that contains a link to the item, it's icon and breadcrumbs in the tooltip. """ if isinstance(value, unicode): value = value.encode('utf-8') # Determine URL and UID url = get_url(item) if ICatalogBrain.providedBy(item) or isinstance(item, SolrDocument): uid = item.UID else: uid = IUUID(item) # Construct CSS class css_class = get_css_class(item) # Make sure all data used in the HTML snippet is properly escaped value = escape_html(value) if with_tooltip: css_class = "rollover-breadcrumb " + css_class link = '<a class="%s" href="%s" data-uid="%s"><span>%s</span></a>' % ( css_class, url, uid, value) wrapper = '<span class="linkWrapper">%s</span>' % link return wrapper
def _get_scaled_img(self, item, size): request = getRequest() if ( ICatalogBrain.providedBy(item) or IContentListingObject.providedBy(item) ): obj = item.getObject() else: obj = item info = {} if hasattr(obj, 'image'): scales = getMultiAdapter((obj, request), name='images') if size == 'small': scale = scales.scale('image', width=300, height=300) if size == 'medium': scale = scales.scale('image', width=600, height=600) if size == 'large': scale = scales.scale('image', width=900, height=900) else: scale = scales.scale('image', width=1200, height=1200) if scale is not None: info['url'] = scale.url info['width'] = scale.width info['height'] = scale.height else: info['url'] = IMG info['width'] = '1px' info['height'] = '1px' else: info['url'] = IMG info['width'] = '1px' info['height'] = '1px' return info
def get_email2(self, principal): """Returns the second email address of a `principal`. """ # inbox does not have a email if isinstance(principal, types.StringTypes) and \ self.is_inbox(principal): return None # principal may be a contact brain elif ICatalogBrain.providedBy(principal) and \ brain_is_contact(principal): return principal.email2 # principal may be a user object elif IUser.providedBy(principal) or isinstance(principal, UserDict): return principal.email2 # principal may ba a string contact principal elif self.is_contact(principal): return self.get_contact(principal).email2 # principal may be a string user principal elif self.is_user(principal): return self.get_user(principal).email2 else: raise ValueError('Unknown principal type: %s' % str(principal))
def get_all_news_items(self): local_news = list(self.get_local_news_items()) for news in local_news: news['Date'] = (news['Date'] and DateTime( news['Date'], datefmt="international").strftime("%Y/%m/%d %H:%M") or "") allnews = self.get_remote_news_items() + local_news items = sorted( allnews, key=lambda item: item.__getitem__('Date'), reverse=True ) for i in range(0, len(items)): if ICatalogBrain.providedBy(items[i]): item = items[i] obj = item.getObject() has_image = getattr(obj.image, '_blob', False) image_url = '' if has_image: image_url = obj.absolute_url() + "/@@images/image/preview" items[i] = { 'Title': item.Title, 'Date': DateTime(item.Date).utcdatetime(), 'getURL': item.getURL(), 'Description': item.Description, 'text': obj.text and obj.text.output or "", 'image_url': image_url, 'image_caption': obj.image_caption if has_image else '', 'obj': obj, 'is_local': True, } else: items[i]['Date'] = DateTime(items[i]['Date']).utcdatetime() return items
def _get_scaled_img(self, item, size): request = getRequest() if ICatalogBrain.providedBy(item) or IContentListingObject.providedBy(item): obj = item.getObject() else: obj = item info = {} if hasattr(obj, "image"): scales = getMultiAdapter((obj, request), name="images") if size == "small": scale = scales.scale("image", width=300, height=300) if size == "medium": scale = scales.scale("image", width=600, height=600) if size == "large": scale = scales.scale("image", width=900, height=900) else: scale = scales.scale("image", width=1200, height=1200) if scale is not None: info["url"] = scale.url info["width"] = scale.width info["height"] = scale.height else: info["url"] = IMG info["width"] = "1px" info["height"] = "1px" else: info["url"] = IMG info["width"] = "1px" info["height"] = "1px" return info
def toLocalizedTime(self, time=None, long_format=None, time_only=None, event=None, startend="start"): if not event: return self.context.restrictedTraverse("@@plone").toLocalizedTime( time, long_format, time_only) if ICatalogBrain.providedBy(event): event = event.getObject() if not IEvent.providedBy(event): return self.context.restrictedTraverse("@@plone").toLocalizedTime( time, long_format, time_only) rs = RecurrenceSupport(event) occurences = [ occ for occ in rs.occurrences(datetime.today()) if IEvent.providedBy(occ) ] if len(occurences) >= 1: # do not get object which started in the past if startend == "start": time = getattr(occurences[0], "start") elif startend == "end": time = getattr(occurences[-1], "end") return self.context.restrictedTraverse("@@plone").toLocalizedTime( time, long_format, time_only)
def getContentUri(self, context): #1. determine subject uri for context # FIXME: use property, attribute, context absolute url from Products.ZCatalog.interfaces import ICatalogBrain if ICatalogBrain.providedBy(context): uuid = context.UID else: context = aq_base(context) uuid = IUUID(context, None) if uuid is None: # we probably deal with a new contet object that does not have an # uuid yet let's generate one from plone.uuid.interfaces import IMutableUUID, IUUIDGenerator generator = queryUtility(IUUIDGenerator) if generator is None: return # TODO: raise error uuid = generator() if not uuid: return # TODO: raise error IMutableUUID(context).set(uuid) #url = base_uri + /@@redirect-to-uuid/<uuid> #uri = context.subjecturi # FIXME: shouldn't consult config here, IORDF does this. try: settings = getConfiguration().product_config.get('gu.plone.rdf', dict()) baseuri = settings['baseuri'] except Exception as e: # FIXME: be specific about exceptions baseuri = 'urn:plone:' LOG.warn("No baseuri configured: using %s (%s)", baseuri, e) contenturi = "%s%s" % (baseuri, uuid) return contenturi
def getdsmetadata(ds): # TODO: support brain, obj and uuid string (URI as well?) # extract info about files if ICatalogBrain.providedBy(ds): ds = ds.getObject() # TODO: try to use brains only here # url: ds.getURL() # id: ds.UID, # description: ds.Description # start with metadata annotation md = { #'@context': { }, '@id': IUUID(ds), '@type': ds.portal_type, 'url': ds.absolute_url(), 'id': IUUID(ds), 'title': ds.title, 'description': ds.description, } md.update(IBCCVLMetadata(ds)) dlinfo = IDownloadInfo(ds) md.update({ 'mimetype': dlinfo['contenttype'], 'filename': dlinfo['filename'], 'file': dlinfo['url'], 'vizurl': dlinfo['alturl'][0] }) return md
def linked(item, value): """Takes an item (object or brain) and returns a HTML snippet that contains a link to the item, it's icon and breadcrumbs in the tooltip. """ if isinstance(value, unicode): value = value.encode('utf-8') # Determine URL and UID url = get_url(item) if ICatalogBrain.providedBy(item): uid = item.UID else: uid = IUUID(item) # Construct CSS class css_class = get_css_class(item) # Make sure all data used in the HTML snippet is properly escaped value = escape_html(value) link = '<a class="rollover-breadcrumb %s" href="%s" data-uid="%s">%s</a>' % ( css_class, url, uid, value) wrapper = '<span class="linkWrapper">%s</span>' % link return wrapper
def get_all_news_items(self): local_news = list(self.get_local_news_items()) for news in local_news: news['Date'] = (news['Date'] and DateTime( news['Date'], datefmt="international").strftime("%Y/%m/%d %H:%M") or "") allnews = self.get_remote_news_items() + local_news items = sorted(allnews, key=lambda item: item.__getitem__('Date'), reverse=True) for i in range(0, len(items)): if ICatalogBrain.providedBy(items[i]): item = items[i] obj = item.getObject() has_image = getattr(obj.image, '_blob', False) image_url = '' if has_image: image_url = obj.absolute_url() + "/@@images/image/preview" items[i] = { 'Title': item.Title, 'Date': DateTime(item.Date).utcdatetime(), 'getURL': item.getURL(), 'Description': item.Description, 'text': obj.text and obj.text.output or "", 'image_url': image_url, 'image_caption': obj.image_caption if has_image else '', 'obj': obj, 'is_local': True, } else: items[i]['Date'] = DateTime(items[i]['Date']).utcdatetime() return items
def get_type(self, item): """differ the object typ and return the type as string""" if isinstance(item, dict): return 'dict' elif ICatalogBrain.providedBy(item): return 'brain' else: return 'sqlalchemy_object'
def get_uid(obj): """ get the UID of the brain/object """ if ICatalogBrain.providedBy(obj): return obj.UID if ISiteRoot.providedBy(obj): return "siteroot" return obj.UID()
def construct_icalendar(context, events): """Returns an icalendar.Calendar object. :param context: A content object, which is used for calendar details like Title and Description. Usually a container, collection or the event itself. :param events: The list of event objects, which are included in this calendar. """ cal = icalendar.Calendar() cal.add('prodid', PRODID) cal.add('version', VERSION) cal_tz = default_timezone(context) if cal_tz: cal.add('x-wr-timezone', cal_tz) tzmap = {} if not hasattr(events, '__getslice__'): # LazyMap doesn't have __iter__ events = [events] for event in events: if ICatalogBrain.providedBy(event) or\ IContentListingObject.providedBy(event): event = event.getObject() acc = IEventAccessor(event) tz = acc.timezone # TODO: the standard wants each recurrence to have a valid timezone # definition. sounds decent, but not realizable. if not acc.whole_day: # whole day events are exported as dates without # timezone information tzmap = add_to_zones_map(tzmap, tz, acc.start) tzmap = add_to_zones_map(tzmap, tz, acc.end) cal.add_component(IICalendarEventComponent(event).to_ical()) for (tzid, transitions) in tzmap.items(): cal_tz = icalendar.Timezone() cal_tz.add('tzid', tzid) cal_tz.add('x-lic-location', tzid) for (transition, tzinfo) in transitions.items(): if tzinfo['dst']: cal_tz_sub = icalendar.TimezoneDaylight() else: cal_tz_sub = icalendar.TimezoneStandard() cal_tz_sub.add('tzname', tzinfo['name']) cal_tz_sub.add('dtstart', transition) cal_tz_sub.add('tzoffsetfrom', tzinfo['tzoffsetfrom']) cal_tz_sub.add('tzoffsetto', tzinfo['tzoffsetto']) # TODO: add rrule # tzi.add('rrule', # {'freq': 'yearly', 'bymonth': 10, 'byday': '-1su'}) cal_tz.add_component(cal_tz_sub) cal.add_component(cal_tz) return cal
def is_brain(brain_or_object): """Checks if the passed in object is a portal catalog brain :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: True if the object is a catalog brain :rtype: bool """ return ICatalogBrain.providedBy(brain_or_object)
def is_brain(brain_or_object): """Checks if the passed in object is a portal catalog brain :param brain_or_object: Any object; probably a content object or a brain. :type brain_or_object: Any :return: True if the object is a brain :rtype: bool """ return ICatalogBrain.providedBy(brain_or_object)
def renderCell(self, card): if ICatalogBrain.providedBy(card): searchview = self.table.context categories_display = searchview.getCategoryDisplay(card) categories_display = u','.join([cat.decode('utf-8') for cat in categories_display]) else: categories_display = '' return categories_display
def _get_task_css_class(task): """A task helper function for `get_css_class`, providing some metadata of a task. The task may be a brain, a dexterity object or a sql alchemy globalindex object. """ if ICatalogBrain.providedBy(task) or ISolrDocument.providedBy(task): task = Task.query.by_brain(task) return task.get_css_class()
def _get_task_css_class(task): """A task helper function for `get_css_class`, providing some metadata of a task. The task may be a brain, a dexterity object or a sql alchemy globalindex object. """ if ICatalogBrain.providedBy(task): task = Task.query.by_brain(task) return task.get_css_class()
def renderCell(self, card): if ICatalogBrain.providedBy(card): url = card.getURL() title = card.Title.decode('utf-8') title_display = u'<a href="{url}">{title}</a>'.format(url=url, title=title) else: title = card.get('title', '') title = title.decode('utf-8') title_display = u'<span class="title_delimiter">{title}<span>'.format(title=title) return title_display
def get_container_of_original(self, obj, manual=False): """ If the obj is a working copy, return the container of the original""" if IHomeFolder.providedBy(self.context) or manual: if ICatalogBrain.providedBy(obj): obj = obj.getObject() iterate_control = getMultiAdapter( (obj, self.request), name='iterate_control') original = iterate_control.get_original(obj) if original: return safe_unicode(Acquisition.aq_parent(original).Title()) return ""
def get_parent(obj, catalog_id='portal_catalog'): """ Gets the parent of the obj or brain. The result is of the same type as the parameter given. """ if ICatalogBrain.providedBy(obj): catalog = api.portal.get_tool(catalog_id) brains = catalog( path={'query': '/'.join(obj.getPath().split('/')[:-1])} ) return brains[0] else: return obj.aq_inner.aq_parent
def __call__(self, context, field, options): img = getattr(context, field) if img: if ICatalogBrain.providedBy(context): baseurl = context.getURL() else: baseurl = context.absolute_url() size = options.by(field).get('image_size', 'thumb') url = '/'.join((baseurl, '@@images', field, size)) return self.template.substitute(url=url) else: return u''
def get_state_css(self, itemob=None): itemob = itemob or self.context if ICatalogBrain.providedBy(itemob): itemob = itemob.getObject() css_map = { None: "success", "QUEUED": "info", "RUNNING": "info", "COMPLETED": "success", "FAILED": "error", "REMOVED": "removed", } # check job_state and return either success, error or block job_state = IJobTracker(itemob).state return css_map.get(job_state, "info")
def get_type(self, item): """differ the object typ and return the type as string""" if isinstance(item, dict): return 'dict' elif ICatalogBrain.providedBy(item): return 'brain' elif IContentListingObject.providedBy(item): return 'contentlistingobject' elif IFieldWidget.providedBy(item): return 'widget' elif isinstance(item, Task): return 'globalindex_task' else: raise ValueError("Unknown item type: {!r}".format(item))
def __init__(self, ob, root=None, parent=None): self._root = root or self if getattr(self._root, '_ob_cache', None) is None: self._root._ob_cache = {} if not ICatalogBrain.providedBy(ob): brain = ICatalogTool(ob).getBrain(ob) if brain is None: raise UncataloguedObjectException(ob) # We already have the object - cache it here so _get_object doesn't # have to look it up again. self._root._ob_cache[brain.getPath()] = ob ob = brain self._object = ob self._parent = parent or None self._severity = None
def get_state_css(self, itemob=None): itemob = itemob or self.context if ICatalogBrain.providedBy(itemob): itemob = itemob.getObject() css_map = { None: 'success', 'QUEUED': 'info', 'RUNNING': 'info', 'COMPLETED': 'success', 'FAILED': 'error', 'REMOVED': 'removed' } # check job_state and return either success, error or block job_state = IJobTracker(itemob).state return css_map.get(job_state, 'info')
def get_state_css(self, itemob=None): itemob = itemob or self.context if ICatalogBrain.providedBy(itemob) or IContentListingObject.providedBy(itemob): itemob = itemob.getObject() css_map = { None: 'success', 'QUEUED': 'warning', 'RUNNING': 'warning', 'COMPLETED': 'success', 'FAILED': 'error', 'REMOVED': 'removed', 'FINISHED': 'info' } # check job_state and return either success, error or block job_state = IExperimentJobTracker(itemob).state return css_map.get(job_state, 'info')
def _nonGlobalRole_child_filter(self, child): """ When user does not have global perms, filter children based on if the user has permissions for the especific organizer or a device in the organizer """ include = False obj = self._get_object() if ICatalogBrain.providedBy(child): child = child.getObject() child_uid = "/".join(child.getPrimaryPath()) if obj.checkRemotePerm(ZEN_VIEW, child) or \ child_uid in self.viewable_objects_uid: include = True return include
def get_object(self, val): if ICatalogBrain.providedBy(val): return val.getObject() if not val: return None if isinstance(val, basestring): if val[0] == '/': # it's a path return self.site.restrictedTraverse(val.strip('/'), None) else: # try querying catalog obj = uuidToObject(val) if obj: return obj if isinstance(val, basestring): return None return val
def __init__(self, ob, root=None, parent=None): self._root = root or self if getattr(self._root, '_ob_cache', None) is None: self._root._ob_cache = {} if not ICatalogBrain.providedBy(ob): brain = ICatalogTool(ob).getBrain(ob) if brain is None: raise UncataloguedObjectException(ob) # We already have the object - cache it here so _get_object doesn't # have to look it up again. self._root._ob_cache[brain.getPath()] = ob ob = brain self._object = ob self._parent = parent or None self._severity = None # allow showing the event severity icons to be configurable if not hasattr(self._root, 'showSeverityIcons'): self._root._showSeverityIcons = self._shouldShowSeverityIcons()
def __init__(self, ob, root=None, parent=None): self._root = root or self if getattr(self._root, '_ob_cache', None) is None: self._root._ob_cache = {} if not ICatalogBrain.providedBy(ob): brain = IModelCatalogTool(ob).getBrainFromObject(ob) if brain is None: raise UncataloguedObjectException(ob) # We already have the object - cache it here so _get_object doesn't # have to look it up again. self._root._ob_cache[brain.getPath()] = ob ob = brain self._object = ob self._parent = parent or None self._severity = None # allow showing the event severity icons to be configurable if not hasattr(self._root, '_showSeverityIcons'): self._root._showSeverityIcons = self._shouldShowSeverityIcons()
def get_state_css(self, itemob=None): itemob = itemob or self.context if ICatalogBrain.providedBy( itemob) or IContentListingObject.providedBy(itemob): job_state = itemob.job_state else: job_state = IExperimentJobTracker(itemob).state css_map = { None: 'success', 'QUEUED': 'warning', 'RUNNING': 'warning', 'PARTIAL': 'warning', 'COMPLETED': 'success', 'FAILED': 'error', 'REMOVED': 'removed', 'FINISHED': 'info' } # check job_state and return either success, error or block return css_map.get(job_state, 'info')
def getdsmetadata(ds): # TODO: support brain, obj and uuid string (URI as well?) # extract info about files if ICatalogBrain.providedBy(ds): ds = ds.getObject() # TODO: try to use brains only here # url: ds.getURL() # id: ds.UID, # description: ds.Description # start with metadata annotation md = { #'@context': { }, '@id': IUUID(ds), '@type': ds.portal_type, 'url': ds.absolute_url(), 'id': IUUID(ds), 'title': ds.title, 'description': ds.description, } md.update(IBCCVLMetadata(ds)) # add layer titles layer_vocab = getUtility(IVocabularyFactory, 'layer_source')(ds) for layer in md.get('layers', {}).values(): if layer.has_key('layer'): layer['title'] = layer_vocab.getLayerTitle(layer['layer']) dlinfo = IDownloadInfo(ds) md.update({ 'mimetype': dlinfo['contenttype'], 'filename': dlinfo['filename'], 'file': dlinfo['url'], }) # This is a hack to extract trait name from the filename. # It assumes that filename is traitname_..., or proj_current_traitname_... # Strip off proj_current 1st if any if 'genre' in md and md.get('genre') in ['DataGenreSTResult', 'DataGenreSTModel']: filename = md.get('title', None) if filename: if filename.strip().startswith("proj_current_"): filename = filename.replace("proj_current_", "", 1) md['trait'] = filename.split("_")[0] return md
def get_location(self, obj): try: location = obj.location if location: return location except AttributeError: pass if ICatalogBrain.providedBy(obj): obj = obj.getObject() bdata = ILocation(obj, None) if bdata and bdata.locations: vocab = LocationsVocabulary(self.context) term = vocab.by_token.get(bdata.locations[0]) if term: return term.title else: return bdata.locations[0]
def test_get_parent(self): folder = self.new_temporary_folder(title='parent') new_type = self.new_temporary_type() with self.user('admin'): obj = api.content.create( id='test', type=new_type.id, container=folder ) brain = tools.get_brain_by_object(obj) self.assertEqual(tools.get_parent(brain).Title, 'parent') self.assertEqual(tools.get_parent(obj).title, 'parent') self.assertTrue(ICatalogBrain.providedBy(tools.get_parent(brain))) self.assertTrue(isinstance(tools.get_parent(obj), folder.__class__))
def _get_scaled_img(self, item, image_field, size): request = getRequest() if ( ICatalogBrain.providedBy(item) or IContentListingObject.providedBy(item) ): obj = item.getObject() else: obj = item info = {} if hasattr(obj, image_field): scales = getMultiAdapter((obj, request), name='images') if size == 'lgip': stored_image = getattr(obj, image_field) scale = image_scale.scaleImage( stored_image.data, width=stored_image.getImageSize()[0], height=stored_image.getImageSize()[1], direction='keep', quality=10 ) if size == 'small': scale = scales.scale(image_field, width=300, height=300) if size == 'medium': scale = scales.scale(image_field, width=600, height=600) if size == 'large': scale = scales.scale(image_field, width=900, height=900) else: scale = scales.scale(image_field, width=1200, height=1200) if scale is not None: info['url'] = scale.url info['width'] = scale.width info['height'] = scale.height else: info['url'] = IMG info['width'] = '1px' info['height'] = '1px' else: info['url'] = IMG info['width'] = '1px' info['height'] = '1px' return info
def format_event_date_for_title(event): """ We need to show only the starting time, or in case of an all day event 'All day' in the time tag. Not the date. In case of a multi day event, we can show "2015-08-30 - 2015-08-31" """ # whole_day isn't a metadata field (yet) if ICatalogBrain.providedBy(event) or ISearchResult.providedBy(event): event_obj = event.getObject() else: event_obj = event start = event_obj.start end = event_obj.end if not (start and end) or (start.date() != end.date()): return '{} - {}'.format( start.strftime('%Y-%m-%d') if start else '', end.strftime('%Y-%m-%d') if end else '', ) if event_obj.whole_day: return _(u'All day') return start.strftime('%H:%M')
def __init__(self, context, request): if ICatalogBrain.providedBy(context): self.context = context.getObject() else: self.context = context self.request = request self.membership = None self.wtool = None self.portal_url = None self.tileid = None self.group = None self.group_url = None self.group_title = None self.effective_date = None self.creator_info = None self.actions = None self.actions_icon = None self.typesUseViewActionInListings = None self.rate = None self.fav = None self.icon = None self.icon_status = None
def get_batched_press_releases(self): b_size = int(self.request.get('b_size', 20)) b_start = int(self.request.get('b_start', 0)) items = self.get_all_press_releases() for i in range(b_start, b_size): if i >= len(items): break if ICatalogBrain.providedBy(items[i]): item = items[i] obj = item.getObject() blob = getattr(obj.image, '_blob', None) plain_text = obj.restrictedTraverse('@@text-transform/text/text/plain') items[i] = { 'Title': item.Title, 'Date': DateTime(item.Date).utcdatetime(), 'getURL': item.getURL(), 'Description': item.Description, 'image': blob and base64.encodestring(blob.open().read()) or None, 'obj': obj, 'text': self.make_intro(plain_text), } else: items[i]['Date'] = DateTime(items[i]['Date']).utcdatetime() return Batch(items, b_size, b_start, orphan=1)
def get_all_news_items(self): items = sorted( self.get_remote_news_items() + list(self.get_local_news_items()), key=lambda item: item.__getitem__('Date'), reverse=True ) for i in range(0, len(items)): if ICatalogBrain.providedBy(items[i]): item = items[i] obj = item.getObject() blob = getattr(obj.image, '_blob', None) items[i] = { 'Title': item.Title, 'Date': DateTime(item.Date).utcdatetime(), 'getURL': item.getURL(), 'Description': item.Description, 'text': obj.text and obj.text.output or "", 'image': blob and base64.encodestring(blob.open().read()) or None, 'obj': obj, 'is_local': True, } else: items[i]['Date'] = DateTime(items[i]['Date']).utcdatetime() return items
def is_brain(obj): """ checks if the object is a catalog brain """ return ICatalogBrain.providedBy(obj)
def dict_from_item(item): if hasPloneAppEvent and (IEvent.providedBy(item) or IOccurrence.providedBy(item)): # plone.app.event DX or AT Event is_occurrence = IOccurrence.providedBy(item) acc = IEventAccessor(item) return { "status": "ok", "id": "UID_%s" % (acc.uid), "title": acc.title, "description": acc.description, "start": acc.start.isoformat(), "end": acc.end.isoformat(), "url": acc.url, "editable": editable, "allDay": acc.whole_day, "className": "contextualContentMenuEnabled %s %s %s %s" % ( state and "state-%s" % str(state) or "", editable and "editable" or "", css and css or "", is_occurrence and "occurrence" or ""), "color": color} elif IATEvent.providedBy(item): # Products.ATContentTypes ATEvent allday = (item.end() - item.start()) > 1.0 adapted = interfaces.ISFBaseEventFields(item, None) if adapted: allday = adapted.allDay return { "status": "ok", "id": "UID_%s" % (item.UID()), "title": item.Title(), "description": item.Description(), "start": item.start().ISO8601(), "end": item.end().ISO8601(), "url": item.absolute_url(), "editable": editable, "allDay": allday, "className": "contextualContentMenuEnabled %s %s %s" % ( state and "state-%s" % str(state) or "", editable and "editable" or "", css and css or ""), "color": color} elif ICatalogBrain.providedBy(item): # Event catalog brain if type(item.end) != DateTime: brainend = DateTime(item.end) brainstart = DateTime(item.start) else: brainend = item.end brainstart = item.start allday = (brainend - brainstart) > 1.0 if getattr(item, 'SFAllDay', None) in [False, True]: allday = item.SFAllDay return { "status": "ok", "id": "UID_%s" % (item.UID), "title": item.Title, "description": item.Description, "start": brainstart.ISO8601(), "end": brainend.ISO8601(), "url": item.getURL(), "editable": editable, "allDay": allday, "className": "contextualContentMenuEnabled %s %s %s" % ( state and "state-%s" % str(state) or "", editable and "editable" or "", css and css or ""), "color": color} else: raise ValueError('item type not supported for: %s' % repr(item))
def describe(self, principal, with_email=False, with_email2=False, with_principal=True): """Represent a user / contact / inbox / ... as string. This usually returns the fullname or another label / title. `principal` could also be a user object or a contact brain. """ if not principal: return '' is_string = isinstance(principal, types.StringTypes) brain = None contact = None user = None # is principal a brain? if not is_string and ICatalogBrain.providedBy(principal): brain = principal # ok, lets check what we have... # string inbox if is_string and self.is_inbox(principal): # just do it client = self.get_client_of_inbox(principal) # we need to instantly translate, because otherwise # stuff like the autocomplete widget will not work # properly. label = _(u'inbox_label', default=u'Inbox: ${client}', mapping=dict(client=client.title)) return translate(label, context=getRequest()) # string contact elif is_string and self.is_contact(principal): contact = self.get_contact(principal) # string user elif is_string and self.is_user(principal): user = self.get_user(principal) # contact brain elif brain and brain_is_contact(brain): contact = brain principal = contact.contactid # user object elif IUser.providedBy(principal) or isinstance(principal, UserDict): user = principal principal = user.userid # ok, now lookup the stuff if contact: if not contact: return principal elif contact.lastname and contact.firstname: name = ' '.join((contact.lastname, contact.firstname)) elif contact.lastname: name = contact.lastname elif contact.firstname: name = contact.firstname elif 'userid' in contact: name = contact.userid else: name = contact.id if with_email2 and contact.email2: return '%s (%s)' % (name, contact.email2) elif with_principal and contact.email: return '%s (%s)' % (name, contact.email) else: return name elif user: if user.lastname and user.firstname: name = ' '.join((user.lastname, user.firstname)) elif user.lastname: name = user.lastname elif user.firstname: name = user.firstname else: name = user.userid infos = [] if with_principal: infos.append(user.userid) if with_email and user.email: infos.append(user.email) elif with_email2 and user.email2: infos.append(user.email2) if infos: return '%s (%s)' % (name, ', '.join(infos)) else: return name elif is_string: # fallback for acl_users portal = getSite() portal_membership = getToolByName(portal, 'portal_membership') member = portal_membership.getMemberById(principal) if not member: if isinstance(principal, str): return principal.decode('utf-8') else: return principal name = member.getProperty('fullname', principal) email = member.getProperty('email', None) infos = [] if with_principal: infos.append(principal) if with_email and email: infos.append(email) if infos: return '%s (%s)' % (name, ', '.join(infos)) else: return name else: raise ValueError('Unknown principal type: %s' % str(principal))
def _is_brain(self): return ICatalogBrain.providedBy(self._ob)
def unbrain(item): if ICatalogBrain.providedBy(item): return item.getObject() return item
def __call__(self, *args, **kwargs): """Run a task with a specified id or all upcoming tasks. """ tasks = [] infos = [] warnings = [] now = plone.app.event.base.localized_now(self.context) infos.append( u'Starting workflow task runner on {:%Y-%m-%d %H:%M}'.format(now)) logger.info(infos[-1]) task_id = self.request.form.get('task_id', None) if task_id: tasks = [uuidToObject(task_id)] else: # Get all upcoming tasks query = {} query['portal_type'] = 'WFTask' query['start'] = {'query': now, 'range': 'max'} query['is_active'] = True tasks = plone.api.content.find(**query) if not tasks: warnings.append(u'No tasks found') logger.warn(warnings[-1]) for task in tasks: if ICatalogBrain.providedBy(task): task = task.getObject() if not (task.task_action and task.task_items): warnings.append( u'Task <a href="{0}">{1}</a> (action: {2}, items: {3}) incomplete.' .format( # noqa task.absolute_url(), task.title, task.task_action, task.task_items)) logger.warn(warnings[-1]) continue for ref in task.task_items: ob = ref.to_object if not ob: continue try: plone.api.content.transition(obj=ob, transition=task.task_action) infos.append( u'Task <a href="{0}">{1}</a> successfully run for object <a href="{2}">{3}</a>.' .format( # noqa task.absolute_url(), task.title, ob.absolute_url(), ob.title)) logger.info(infos[-1]) except InvalidParameterError: warnings.append( u'Could not apply task <a href="{0}">{1}</a> with transform {2} for object <a href="{3}">{4}</a>.' .format( # noqa task.absolute_url(), task.title, task.task_action, ob.absolute_url(), ob.title)) logger.warn(warnings[-1]) continue IWFTask(task).task_active = False task.reindexObject(idxs=['is_active']) # Final summary self.infos = infos self.warnings = warnings return super(WFTaskRunnerView, self).__call__(*args, **kwargs)