def validate_og_fallback_image(value): """Check if fallback image follows best practices on MIME type, size, dimensions and aspect ratio. """ if value is None: return True filename, data = b64decode_file(value) image = NamedBlobImage(data=data, filename=filename) if image.contentType not in OG_LEAD_IMAGE_MIME_TYPES: raise Invalid(MSG_INVALID_OG_LEAD_IMAGE_MIME_TYPE) if image.getSize() > OG_LEAD_IMAGE_MAX_SIZE: raise Invalid(MSG_INVALID_OG_LEAD_IMAGE_SIZE) width, height = image.getImageSize() if width < OG_LEAD_IMAGE_MIN_WIDTH or height < OG_LEAD_IMAGE_MIN_HEIGHT: raise Invalid(MSG_INVALID_OG_LEAD_IMAGE_DIMENSIONS) aspect_ratio = width / height if aspect_ratio < OG_LEAD_IMAGE_MIN_ASPECT_RATIO: raise Invalid(MSG_INVALID_OG_LEAD_IMAGE_ASPECT_RATIO) return True
def __call__(self): # TODO: Security check on form view/widget if self.context.ignoreContext: raise NotFound("Cannot get the data file from a widget with no context") if self.context.form is not None: content = aq_inner(self.context.form.getContent()) else: content = aq_inner(self.context.context) field = aq_inner(self.context.field) dm = getMultiAdapter((content, field), IDataManager) file_ = dm.get() if isinstance(file_, basestring) and IASCII.providedBy(field): """Encoded data. """ filename, data = b64decode_file(file_) if INamedImageWidget.providedBy(self.context): file_ = NamedImage(data=data, filename=filename) else: file_ = NamedFile(data=data, filename=filename) if file_ is None: raise NotFound(self, self.filename, self.request) if not self.filename: self.filename = getattr(file_, "filename", None) set_headers(file_, self.request.response, filename=self.filename) return stream_data(file_)
def _make_namedfile(value, field, widget): """Return a NamedImage or NamedFile instance, if it isn't already one - e.g. when it's base64 encoded data. """ if INamed.providedBy(value): return value string_types = (six.binary_type, six.text_type) if isinstance(value, string_types) and IBytes.providedBy(field): filename, data = b64decode_file(value) elif isinstance(value, dict) or isinstance(value, PersistentDict): filename = value['filename'] data = value['data'] if INamedBlobImageField.providedBy(field): value = NamedBlobImage(data=data, filename=filename) elif INamedImageField.providedBy(field): value = NamedImage(data=data, filename=filename) elif INamedBlobFileField.providedBy(field): value = NamedBlobFile(data=data, filename=filename) else: value = NamedFile(data=data, filename=filename) return value
def get_fallback_image(self): fallback_image = self.settings.fallback_image if fallback_image is not None: filename, _ = b64decode_file(fallback_image) return '/@@sociallike-fallback-image/' + filename else: return '/logo.png'
def get_site_logo(site=None): """Return the custom logo or Plone's default.""" if not PLONE_4: try: from Products.CMFPlone.utils import getSiteLogo except ImportError: return None else: return getSiteLogo(site=site) from spirit.plone.theming.interfaces import IPloneThemeSettings from plone.formwidget.namedfile.converter import b64decode_file if site is None: site = api.portal.get() registry = getUtility(IRegistry) settings = registry.forInterface(IPloneThemeSettings, check=False) # noqa site_url = site.absolute_url() if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) return '{0}/@@site-logo-plone4/{1}'.format(site_url, filename) else: return '{0}/logo.png'.format(site_url)
def uwo_logo(self): uwo_logo_data = api.portal.get_registry_record( 'oiestudyabroadstudent.uwo_logo', ) if uwo_logo_data is None or len(uwo_logo_data) == 0: return None filename, data = b64decode_file(uwo_logo_data) image = NamedImage(data=data, filename=filename) return image
def get_data(self): registry = getUtility(IRegistry) try: data = registry['plone.site_icon'] except: data = None if data: filename, data = b64decode_file(data) return data
def is_video(self): """Guess if the mimetype of the file stored in the background_image field, is from a video. """ if self.settings.background_image is None: return False filename, _ = b64decode_file(self.settings.background_image) self.mimetype, _ = mimetypes.guess_type(filename) return 'video' in self.mimetype
def logo(self): """Return a Google News compliant logo if available.""" logo = api.portal.get_registry_record(GoogleNewsSettings.__identifier__ + '.logo') if logo is None: return self._logo # no Google News compliant logo, return portal logo filename, data = b64decode_file(logo) return '{0}/@@googlenews-logo/{1}'.format(api.portal.get().absolute_url(), filename)
def _make_namedfile(value, field, widget): """Return a NamedImage or NamedFile instance, if it isn't already one - e.g. when it's base64 encoded data. """ if isinstance(value, basestring) and IASCII.providedBy(field): filename, data = b64decode_file(value) if INamedImageWidget.providedBy(widget): value = NamedImage(data=data, filename=filename) else: value = NamedFile(data=data, filename=filename) return value
def __init__(self, context, request): super(BannerImage, self).__init__(context, request) self.filename = None self.data = None image = self.config.get('image', None) if image is not None: filename, data = b64decode_file(image) data = NamedImage(data=data, filename=filename) self.data = data self.filename = filename
def logo(self): """Return a Google News compliant logo if available.""" logo = api.portal.get_registry_record( GoogleNewsSettings.__identifier__ + '.logo') if logo is None: return self._logo # no Google News compliant logo, return portal logo filename, data = b64decode_file(logo) return '{0}/@@googlenews-logo/{1}'.format( api.portal.get().absolute_url(), filename)
def __init__(self, context, request): super(SiteLogo, self).__init__(context, request) self.filename = None self.data = None registry = getUtility(IRegistry) settings = registry.forInterface(ISiteSchema, prefix="plone") if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) data = NamedImage(data=data, filename=filename) self.data = data self.filename = filename
def validate_background(value): """Check if file is an image or a video.""" if not value: return True filename, _ = b64decode_file(value) mimetype, _ = mimetypes.guess_type(filename) if mimetype is None: return False return 'image' in mimetype or 'video' in mimetype
def image_url(self): """Return the image URL for the background image.""" image = self.config.get('image', None) if image is not None: filename, data = b64decode_file(image) return '{0}/@@listing-search-banner-image/{1}'.format( self.context.absolute_url(), filename, ) image_url = self.config.get('image_url', None) if image_url is not None and image_url != u'http://': return image_url
def __init__(self, context, request): super(PublisherLogoDownload, self).__init__(context, request) self.filename, self.data = None, None publisher_logo = api.portal.get_registry_record( IAMPSettings.__identifier__ + '.publisher_logo') if publisher_logo is not None: # set publisher logo data for download filename, data = b64decode_file(publisher_logo) data = NamedImage(data=data, filename=filename) self.filename, self.data = filename, data
def __init__(self, context, request): super().__init__(context, request) self.filename = None self.data = None registry = getUtility(IRegistry) settings = registry.forInterface(ISiteSchema, prefix="plone") if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) data = NamedImage(data=data, filename=filename) self.data = data self.filename = filename
def __init__(self, context, request): super(Logo, self).__init__(context, request) self.filename = None self.data = None registry = getUtility(IRegistry) settings = registry.forInterface(IPloneThemeSettings) # noqa if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) data = NamedImage(data=data, filename=filename) self.data = data self.filename = filename
def get_ga_service( ga_scope=['https://www.googleapis.com/auth/analytics.readonly']): registry = getUtility(IRegistry) api_email = registry.get('castle.google_api_email', None) api_key = registry.get('castle.google_api_service_key_file', None) ga_id = registry.get('castle.google_analytics_id', None) if not api_key or not api_email or not ga_id: return # Authenticate and construct service. return get_service('analytics', 'v3', ga_scope, b64decode_file(api_key)[1], api_email)
def setup(self): name = ISettingsPortal.__identifier__ + '.background_image' background_image = api.portal.get_registry_record(name, default=None) if background_image is None: self.data = None return # set background media data for download filename, data = b64decode_file(background_image) self.filename = filename self.data = NamedFile(data=data, filename=filename) self.checksum = hashlib.sha1(data).hexdigest()
def getSiteLogo(site=None): from Products.CMFPlone.interfaces import ISiteSchema from plone.formwidget.namedfile.converter import b64decode_file if site is None: site = getSite() registry = getUtility(IRegistry) settings = registry.forInterface(ISiteSchema, prefix="plone", check=False) site_url = site.absolute_url() if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) return '{}/@@site-logo/{}'.format(site_url, filename) else: return '%s/logo.png' % site_url
def getSiteLogo(site=None): from Products.CMFPlone.interfaces import ISiteSchema from plone.formwidget.namedfile.converter import b64decode_file if site is None: site = getSite() registry = getUtility(IRegistry) settings = registry.forInterface(ISiteSchema, prefix="plone", check=False) site_url = site.absolute_url() if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) return '{}/@@site-logo/{}'.format( site_url, filename) else: return '%s/logo.png' % site_url
def __init__(self, context, request): """Set Google News logo data if available.""" super(GoogleNewsLogo, self).__init__(context, request) self.filename = None self.data = None logo = api.portal.get_registry_record( GoogleNewsSettings.__identifier__ + '.logo') if logo is not None: # set Google News logo data for download filename, data = b64decode_file(logo) data = NamedImage(data=data, filename=filename) self.data = data self.filename = filename
def __init__(self, context, request): super(FallBackImageView, self).__init__(context, request) record = ISocialLikeSettings.__identifier__ + '.fallback_image' fallback_image = api.portal.get_registry_record(record, default=None) if fallback_image is not None: # set fallback image data for download filename, data = b64decode_file(fallback_image) data = NamedImage(data=data, filename=filename) self.filename, self.data = filename, data # enable image caching for 2 minutes self.request.RESPONSE.setHeader('Cache-Control', 'max-age=120, public') else: # resource no longer available self.data = NamedImage(data='') self.request.RESPONSE.setStatus(410) # Gone
def get_site_favicon(site=None): """Return the custom favicon or Plone's default.""" from spirit.plone.theming.interfaces import IPloneThemeSettings from plone.formwidget.namedfile.converter import b64decode_file if site is None: site = api.portal.get() registry = getUtility(IRegistry) settings = registry.forInterface(IPloneThemeSettings, check=False) # noqa site_url = site.absolute_url() if getattr(settings, 'site_favicon', False): filename, data = b64decode_file(settings.site_favicon) return '{0}/@@site-favicon/{1}'.format(site_url, filename) else: return '{0}/favicon.ico'.format(site_url)
def publisher_logo(self): """Return publisher logo information as a dictionary.""" publisher_logo = api.portal.get_registry_record( IAMPSettings.__identifier__ + '.publisher_logo') if publisher_logo is None: return None portal_url = api.portal.get().absolute_url() filename, data = b64decode_file(publisher_logo) width, height = Image.open(StringIO(data)).size return dict( url='{0}/@@amp-publisher-logo/{1}'.format(portal_url, filename), width=width, height=height, )
def update(self): super(LogoViewlet, self).update() # TODO: should this be changed to settings.site_title? self.navigation_root_title = self.portal_state.navigation_root_title() registry = getUtility(IRegistry) settings = registry.forInterface(ISiteSchema, prefix="plone") self.logo_title = settings.site_title if getattr(settings, 'site_logo', False): filename, data = b64decode_file(settings.site_logo) data = NamedImage(data=data, filename=filename) self.img_src = '{}/@@site-logo/{}'.format( self.navigation_root_url, filename) else: self.img_src = '%s/logo.png' % ( self.navigation_root_url)
def validate_logo(value): """Validate the image to be used in the feed. The image must follow these specifications: * Image should be .png format * Image dimensions must match one of two options: * height between 20 and 40px, width of 250px * height of 40px, width between 125 and 250px * Image background should be transparent :param value: Image encoded into base64 to be validated :type value: string :raises: :class:`~zope.interface.Invalid` if the image is not valid """ if not value: return True filename, data = b64decode_file(value) img = Image.open(StringIO(data)) # check format if img.format != 'PNG': raise Invalid(_(u'Image should be in PNG format.')) # Check image size width, height = img.size if not((20 <= height <= 40 and width == 250) or (height == 40 and 125 <= width <= 250)): raise Invalid(_( u'Image should have height beetween 20px and 40px and width equal 250px ' u'or height equal 40px and width beetween 125px and 250px.' )) # Check image transparency. if not((img.mode in ('RGBA', 'LA')) or (img.mode == 'P' and 'transparency' in img.info)): raise Invalid(_(u'Image should have transparency layer.')) return True
def get_url_special_student_form_for_undergraduate_admissions_form(): form = api.portal.get_registry_record( 'oiestudyabroadstudent.special_student_form_for_undergraduate_admissions', # noqa : E501 ) if form is not None: filename, data = b64decode_file(form) file = NamedFile(data=data, filename=filename) url = 'data:{0};base64, {1}'.format( file.contentType, file.data.encode('base64'), ) html = '<a target="_blank" href="{0}">Download this form</a>'.format( url, ) return RichTextValue(html, 'text/html', 'text/html') else: return RichTextValue( '<em>The special student form for undergraduate admissions has not yet been specified by an administrator</em>', # noqa : E501 'text/html', 'text/html', )
def is_valid_logo(value): """Check if the image is a valid logo: * Logos should have a wide aspect ratio, not a square icon * Logos should be no wider than 600px, and no taller than 60px """ if not value: return True filename, data = b64decode_file(value) width, height = Image.open(StringIO(data)).size if width <= height: raise Invalid(_(u'Image should have a wide aspect ratio.')) if width > 600 or height > 60: raise Invalid( _(u'Image should be no wider than 600px, and no taller than 60px.') ) return True
def get_url_disciplinary_clearance_form(): form = api.portal.get_registry_record( 'oiestudyabroadstudent.disciplinary_clearance_form', ) if form is not None: filename, data = b64decode_file(form) file = NamedFile(data=data, filename=filename) url = 'data:{0};base64, {1}'.format( file.contentType, file.data.encode('base64'), ) html = '<a target="_blank" href="{0}">Download this form</a>'.format( url, ) return RichTextValue(html, 'text/html', 'text/html') else: return RichTextValue( '<em>The disciplinary clearance form has not yet been specified by an administrator</em>', # noqa : E501 'text/html', 'text/html', )
def validate_logo(value): """Validate the image to be used in the feed. The image must follow these specifications: * Image should be .png format * Image dimensions must match one of two options: * height between 20 and 40px, width of 250px * height of 40px, width between 125 and 250px * Image background should be transparent :param value: Image encoded into base64 to be validated :type value: string :raises: :class:`~zope.interface.Invalid` if the image is not valid """ if not value: return True filename, data = b64decode_file(value) img = Image.open(StringIO(data)) # check format if img.format != 'PNG': raise Invalid(_(u'Image should be in PNG format.')) # Check image size width, height = img.size if not ((20 <= height <= 40 and width == 250) or (height == 40 and 125 <= width <= 250)): raise Invalid( _(u'Image should have height beetween 20px and 40px and width equal 250px ' u'or height equal 40px and width beetween 125px and 250px.')) # Check image transparency. if not ((img.mode in ('RGBA', 'LA')) or (img.mode == 'P' and 'transparency' in img.info)): raise Invalid(_(u'Image should have transparency layer.')) return True
def __call__(self): # TODO: Security check on form view/widget if self.context.ignoreContext: raise NotFound( "Cannot get the data file from a widget with no context") if self.context.form is not None: content = aq_inner(self.context.form.getContent()) else: content = aq_inner(self.context.context) field = aq_inner(self.context.field) dm = getMultiAdapter(( content, field, ), IDataManager) file_ = dm.get() if isinstance(file_, basestring) and IASCII.providedBy(field): """Encoded data. """ filename, data = b64decode_file(file_) if INamedImageWidget.providedBy(self.context): file_ = NamedImage(data=data, filename=filename) else: file_ = NamedFile(data=data, filename=filename) if file_ is None: raise NotFound(self, self.filename, self.request) if not self.filename: self.filename = getattr(file_, 'filename', None) set_headers(file_, self.request.response, filename=self.filename) return stream_data(file_)
def validate_base_image(value): """Validate the base image used to create featured image. The image must follow these specifications: * .png format * be at least 1200 x 630 pixels * should be smaller that 1MB :param value: Image encoded into base64 to be validated :type value: string :raises: :class:`~zope.interface.Invalid` if the image is not valid """ if not value: return False filename, data = b64decode_file(value) # check size if len(data) > 1048576: raise Invalid(_(u'Image should be smaller than 1MB.')) img = Image.open(StringIO(data)) # check format if img.format != 'PNG': raise Invalid(_(u'Image should be in PNG format.')) # check image dimensions width, height = img.size if not(width >= 1200 and height >= 630): raise Invalid(_( u'Image must be at least 1200 x 630 pixels for the best display on high resolution devices.' )) return True
def get(self, picture): if not picture: return None filename, data = b64decode_file(picture) data = NamedImage(data=data, filename=filename) return data
def convert_datagrid_iamge(picture): filename, data = b64decode_file(picture) data = NamedImage(data=data, filename=filename) return data