def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'img') chart_url = self.context.absolute_url() + "#" + "tab-" + filename filename = filename + ".png" sp = self.siteProperties qr_size = sp.get('googlechart.qrcode_size', '70') if qr_size == '0': qr_size = '70' qr_url = (u"http://chart.apis.google.com" "/chart?cht=qr&chld=H|0&chs=%sx%s&chl=%s" % (qr_size, qr_size, urllib2.quote(chart_url))) self.request.form['qr_url'] = qr_url img = super(SavePNGChart, self).__call__() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) return _("Success")
class IWidgetAdd(Interface): """ Add widget """ wtype = schema.Choice(title=_(u'Widget type'), description=_(u'Select widget type to add'), required=True, vocabulary=u'eea.googlecharts.vocabularies.Widgets')
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't set thumbnail on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'cover.png') convert = getUtility(IConvert) img = convert(data=kwargs.get('svg', ''), data_from='svg', data_to='png') if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) self.context.getOrdering().moveObjectsToTop(ids=[obj.getId()]) return _("Success")
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't set thumbnail on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'cover.png') img = None convert = getUtility(IConvert) if kwargs.get('svg', '') != '': img = convert(data=kwargs.get('svg', ''), data_from='svg', data_to='png') if kwargs.get('imageChart_url', '') != '': try: img_con = urllib2.urlopen(kwargs.get('imageChart_url'), timeout=10) img = img_con.read() img_con.close() except Exception: img = None if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) self.context.getOrdering().moveObjectsToTop(ids=[obj.getId()]) notify(InvalidateCacheEvent(obj)) return _("Success")
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'img') chart_url = self.context.absolute_url() + "#" + "tab-" + filename filename = filename + ".png" sp = self.siteProperties qr_size = sp.get('googlechart.qrcode_size', '70') if qr_size == '0': qr_size = '70' qr_url = "http://chart.apis.google.com/chart?cht=qr&chld=H|0&chs=" + \ qr_size + "x" + qr_size + "&chl=" + urllib2.quote(chart_url) self.request.form['qr_url'] = qr_url img = super(SavePNGChart, self).__call__() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) return _("Success")
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, "form", {}) kwargs.update(form) filename = kwargs.get("filename", "img") chart_url = self.context.absolute_url() + "#" + "tab-" + filename filename = filename + ".png" sp = self.siteProperties qr_size = sp.get("googlechart.qrcode_size", "70") if qr_size == "0": qr_size = "70" qr_url = u"http://chart.apis.google.com" "/chart?cht=qr&chld=H|0&chs=%sx%s&chl=%s" % ( qr_size, qr_size, urllib2.quote(chart_url), ) self.request.form["qr_url"] = qr_url img = super(SavePNGChart, self).__call__() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory("Image", id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField("image").getMutator(obj)(img) return _("Success")
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't set thumbnail on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'cover.png') convert = getUtility(IConvert) if kwargs.get('svg', '') != '': img = convert( data=kwargs.get('svg', ''), data_from='svg', data_to='png' ) if kwargs.get('imageChart_url', '') != '': img_con = urllib2.urlopen(kwargs.get('imageChart_url')) img = img_con.read() img_con.close() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) self.context.getOrdering().moveObjectsToTop(ids=[obj.getId()]) notify(ObjectModifiedEvent(obj)) return _("Success")
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't set thumbnail on a non-folderish object !") form = getattr(self.request, "form", {}) kwargs.update(form) filename = kwargs.get("filename", "cover.png") convert = getUtility(IConvert) if kwargs.get("svg", "") != "": img = convert(data=kwargs.get("svg", ""), data_from="svg", data_to="png") if kwargs.get("imageChart_url", "") != "": try: img_con = urllib2.urlopen(kwargs.get("imageChart_url"), timeout=10) img = img_con.read() img_con.close() except Exception: img = None if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory("Image", id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField("image").getMutator(obj)(img) self.context.getOrdering().moveObjectsToTop(ids=[obj.getId()]) notify(InvalidateCacheEvent(obj)) return _("Success")
class IAdd(Interface): """ Widget add schema """ name = schema.Choice( title=_(u"Chart"), description=_(u"Select chart"), required=True, vocabulary=u"eea.googlecharts.vocabularies.charts.add" )
class IAdd(Interface): """ Widget add schema """ name = schema.Choice( title=_(u"Chart"), description=_(u"Select the chart for which you want the multiples"), required=True, vocabulary=u"eea.googlecharts.vocabularies.multiples.add") multiples_settings = schema.TextLine( title=_(u"Settings"), description=_(u"JSON of small multiple settings"), required=False)
def sectionsPosition(self, **kwargs): """ Change sections position in dashboard """ order = kwargs.get('order', []) if not order: return _(u'New order not provided') for item in order: self.dashboard.setdefault(item, {}) self.dashboard[item]['order'] = order.index(item) self.dashboards = 'Changed' return _('Position changed')
class IWidgetEdit(Interface): """ Widget edit schema """ title = schema.TextLine( title=_(u'Title'), description=_(u"Widget's title"), required=True ) text = schema.Text( title=_(u"Text"), description=_(u"Widget's body"), required=False )
class IWidgetAdd(Interface): """ Widget add schema """ name = schema.TextLine( title=_(u'Name'), description=_(u"Widget's name"), required=True ) text = schema.Text( title=_(u"Text"), description=_(u"Widget's body"), required=False )
def chartsPosition(self, **kwargs): """ Change chats position in dashboard """ order = kwargs.get('order', []) order = dict((name, index) for index, name in enumerate(order)) # Widgets order widgets = self.dashboard.get('widgets', []) changed = False for widget in widgets: dashboard = widget.get('dashboard', {}) if not dashboard: continue name = widget.get('name', '') new_order = order.get(name, -1) my_order = dashboard.get('order', -1) if my_order == new_order: continue dashboard['order'] = new_order changed = True if changed: widgets.sort(cmp=compare) self.dashboards = 'Changed' return _(u'Changed saved')
def dashboardRename(self, **kwargs): """ Rename dashboard """ title = kwargs.get('title', '') self.dashboard['title'] = title self.dashboards = "Changed" return _(u"Dashboard renamed")
def submit_charts(self): """ Submit """ mutator = queryAdapter(self.context, IVisualizationConfig) data = {} data['chartsconfig'] = json.loads(self.request['charts']) mutator.edit_view('googlechart.googlecharts', **data) if not IFolderish.providedBy(self.context): return "Changes saved, but can't save png" + \ "chart on a non-folderish object!" previews = [ "googlechart.googledashboard.preview.png", "googlechart.motionchart.preview.png", "googlechart.organizational.preview.png", "googlechart.imagechart.preview.png", "googlechart.sparkline.preview.png", "googlechart.table.preview.png", "googlechart.annotatedtimeline.preview.png", "googlechart.treemap.preview.png" ] for previewname in previews: if not self.context.get(previewname, None): img = self.context.restrictedTraverse("++resource++" + previewname) self.context.invokeFactory('Image', id=previewname, title=previewname, image=img.GET()) notify(ChartsChanged(self.context, config=data)) return _('Changes saved')
class DashboardsView(ViewForm): """ Google dashboards view """ label = _('Dashboards') @property def tabs(self): """ View tabs """ png_url = self.context.absolute_url() + \ "/googlechart.googledashboard.preview.png" mutator = queryAdapter(self.context, IVisualizationConfig) view = dict(mutator.view(self.__name__, {})) tabs = [] for dashboard in view.get('dashboards', []): name = dashboard.get('name', '') tab = { 'name': name, 'title': dashboard.get('title', name), 'css': 'googlechart_class_Dashboard', 'tabname': 'tab-%s' % name.replace('.', '-'), 'fallback-image': png_url } tabs.append(tab) return tabs
def submit_data(self): """ Submit """ mutator = queryAdapter(self.context, IVisualizationConfig) data = {} data['chartsconfig'] = json.loads(self.request['chartsconfig']) mutator.edit_view('googlechart.googlecharts', **data) if not IFolderish.providedBy(self.context): return "Changes saved, but can't save png" + \ "chart on a non-folderish object!" previews = ["googlechart.googledashboard.preview.png", "googlechart.motionchart.preview.png", "googlechart.organizational.preview.png", "googlechart.imagechart.preview.png", "googlechart.sparkline.preview.png", "googlechart.table.preview.png", "googlechart.annotatedtimeline.preview.png", "googlechart.treemap.preview.png"] for previewname in previews: if not self.context.get(previewname, None): img = self.context.restrictedTraverse( "++resource++" + previewname) self.context.invokeFactory('Image', id=previewname, title=previewname, image=img.GET()) notify(ChartsChanged(self.context, config=data)) return _('Changes saved')
class View(ViewForm): """ GoogleChartsView """ label = _('Charts') view_name = "googlechart.googlecharts" @property def jquery_src(self): """ returns available jquery source href """ src = '++resource++eea.jquery.js' possible_resources = ( 'jquery.js', '++resource++plone.app.jquery.js', ) for res in possible_resources: try: self.context.restrictedTraverse(res) return res except Exception, err: logger.debug(err) continue return src
def __call__(self, **kwargs): form = getattr(self.request, "form", {}) kwargs.update(form) convert = getUtility(IConvert) svg = kwargs.get("svg", "") # Fix for IE inserting double " in some svg attributes" svg = re.sub(r"url\("(.*?)"\)", r"url(\1)", svg) filename = kwargs.get("filename", "export") img = None if kwargs.get("export_fmt") == "svg" and svg != "": return self.export_svg(svg, filename) if svg != "": img = convert(data=svg, data_from="svg", data_to="png") if kwargs.get("imageChart_url", "") != "": try: img_con = urllib2.urlopen(kwargs.get("imageChart_url"), timeout=10) img = img_con.read() img_con.close() except Exception: img = None if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") sp = self.siteProperties qrPosition = sp.get("googlechart.qrcode_position", "Disabled") qrVertical = int(sp.get("googlechart.qrcode_vertical_space_for_png_export", 0)) qrHorizontal = int(sp.get("googlechart.qrcode_horizontal_space_for_png_export", 0)) wmPath = sp.get("googlechart.watermark_image", "") wmPosition = sp.get("googlechart.watermark_position", "Disabled") wmVertical = int(sp.get("googlechart.watermark_vertical_space_for_png_export", 0)) wmHorizontal = int(sp.get("googlechart.watermark_horizontal_space_for_png_export", 0)) shiftSecondImg = False hShift = 0 if qrPosition == wmPosition: shiftSecondImg = True if qrPosition != "Disabled": qr_con = urllib2.urlopen(kwargs.get("qr_url"), timeout=10) qr_img = qr_con.read() qr_con.close() img = applyWatermark(img, qr_img, qrPosition, qrVertical, qrHorizontal, 0.7) if shiftSecondImg: hShift = Image.open(StringIO(qr_img)).size[0] + qrHorizontal if wmPosition != "Disabled": try: wm_con = urllib2.urlopen(wmPath, timeout=10) wm_img = wm_con.read() wm_con.close() img = applyWatermark(img, wm_img, wmPosition, wmVertical, wmHorizontal + hShift, 0.7) except ValueError, err: logger.exception(err) except Exception, err: logger.exception(err)
def filterAdd(self, **kwargs): """ Add filter """ self.dashboard.setdefault('filters', []) self.dashboard['filters'].append(kwargs) self.dashboards = 'Changed' return _(u'Filter added')
def dashboardDelete(self, **kwargs): """ Delete dashboard """ dashboards = self.dashboards.get('dashboards', []) self.dashboards['dashboards'] = [ dashboard for dashboard in dashboards if dashboard.get('name') != self.dashboard_name] self.dashboards = 'Changed' return _(u"Dashboard deleted")
def chartsSize(self, **kwargs): """ Change filters box size """ self.dashboard.setdefault('chartsBox', {}) self.dashboard['chartsBox']['width'] = kwargs.get('width', '100%') self.dashboard['chartsBox']['height'] = kwargs.get('height', 'auto') self.dashboards = 'Changed' return _('Charts box resized')
def filtersPosition(self, **kwargs): """ Change filters position """ order = kwargs.get('order', []) if not order: return _('New order not provided') filters = dict((item.get('column'), item) for item in self.dashboard.get('filters', [])) reordered = [] for name in order: if name not in filters: continue reordered.append(filters.get(name)) self.dashboard['filters'] = reordered self.dashboards = 'Changed' return _('Filters position changed')
def submit_data(self): """ Submit """ mutator = queryAdapter(self.context, IVisualizationConfig) data = {} data['chartsconfig'] = json.loads(self.request['chartsconfig']) mutator.edit_view('googlechart.googlecharts', **data) notify(ChartsChanged(self.context, config=data)) return _('Changes saved')
def filterDelete(self, **kwargs): """ Delete filter """ filtername = kwargs.get('name', '') filters = [item for item in self.dashboard.get('filters', []) if item.get('column', '') != filtername] self.dashboard['filters'] = filters self.dashboards = 'Changed' return _(u'Filter deleted')
def dashboardDelete(self, **kwargs): """ Delete dashboard """ dashboards = self.dashboards.get('dashboards', []) self.dashboards['dashboards'] = [ dashboard for dashboard in dashboards if dashboard.get('name') != self.dashboard_name ] self.dashboards = 'Changed' return _(u"Dashboard deleted")
def filterUpdate(self, **kwargs): """ Update filter """ self.dashboard.setdefault('filters', []) for dfilter in self.dashboard['filters']: if kwargs['column'] == dfilter['column']: dfilter['type'] = kwargs['type'] dfilter['defaults'] = kwargs['defaults'] self.dashboards = 'Changed' return _(u'Filter updated')
def filterDelete(self, **kwargs): """ Delete filter """ filtername = kwargs.get('name', '') filters = [ item for item in self.dashboard.get('filters', []) if item.get('column', '') != filtername ] self.dashboard['filters'] = filters self.dashboards = 'Changed' return _(u'Filter deleted')
def filterUpdate(self, **kwargs): """ Update filter """ self.dashboard.setdefault('filters', []) for dfilter in self.dashboard['filters']: if kwargs['column'] == dfilter['column']: dfilter['type'] = kwargs['type'] dfilter['defaults'] = kwargs['defaults'] dfilter['settings'] = kwargs['settings'] self.dashboards = 'Changed' return _(u'Filter updated')
def filtersSize(self, **kwargs): """ Change filters box size """ width = kwargs.get('width', '100%') height = kwargs.get('height', 'auto') self.dashboard.setdefault('filtersBox', {}) self.dashboard['filtersBox']['width'] = width self.dashboard['filtersBox']['height'] = height self.dashboards = 'Changed' return _('Filters box resized')
class ChartsEdit(EditForm, Edit): """ Edit google charts """ label = _("Googlechart Edit") form_fields = Fields(IGoogleChartsEdit) def __call__(self, **kwargs): index = getattr(self, 'index', '') if index: index = index() result = super(ChartsEdit, self).__call__() return '\n'.join((index, result))
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't set thumbnail on a non-folderish object !") form = getattr(self.request, "form", {}) kwargs.update(form) filename = kwargs.get("filename", "cover.png") convert = getUtility(IConvert) img = convert(data=kwargs.get("svg", ""), data_from="svg", data_to="png") if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory("Image", id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField("image").getMutator(obj)(img) self.context.getOrdering().moveObjectsToTop(ids=[obj.getId()]) return _("Success")
def __call__(self, **kwargs): form = getattr(self.request, 'form', {}) kwargs.update(form) convert = getUtility(IConvert) img = convert(data=kwargs.get('svg', ''), data_from='svg', data_to='png') if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") sp = self.siteProperties qrPosition = sp.get('googlechart.qrcode_position', 'Disabled') qrVertical = int( sp.get('googlechart.qrcode_vertical_space_for_png_export', 0)) qrHorizontal = int( sp.get('googlechart.qrcode_horizontal_space_for_png_export', 0)) wmPath = sp.get('googlechart.watermark_image', '') wmPosition = sp.get('googlechart.watermark_position', 'Disabled') wmVertical = int( sp.get('googlechart.watermark_vertical_space_for_png_export', 0)) wmHorizontal = int( sp.get('googlechart.watermark_horizontal_space_for_png_export', 0)) shiftSecondImg = False hShift = 0 if qrPosition == wmPosition: shiftSecondImg = True if qrPosition != 'Disabled': qr_con = urllib2.urlopen(kwargs.get('qr_url')) qr_img = qr_con.read() qr_con.close() img = applyWatermark(img, qr_img, qrPosition, qrVertical, qrHorizontal, 0.7) if shiftSecondImg: hShift = Image.open(StringIO(qr_img)).size[0] + qrHorizontal if wmPosition != 'Disabled': try: wm_con = urllib2.urlopen(wmPath) wm_img = wm_con.read() wm_con.close() img = applyWatermark(img, wm_img, wmPosition, wmVertical, wmHorizontal + hShift, 0.7) except ValueError, err: logger.exception(err)
def widgetDelete(self, **kwargs): """ Delete widget """ widget_name = kwargs.get('name', '') if not widget_name: err = 'Empty widget name provided %s' % widget_name logger.exception(err) return err widgets = self.dashboard.get('widgets', []) changed = False for index, widget in enumerate(widgets): if widget.get('name', '') == widget_name: widgets.pop(index) changed = True break if changed: self.dashboards = 'Changed' return _(u'Widget deleted')
def __call__(self, **kwargs): form = getattr(self.request, "form", {}) kwargs.update(form) convert = getUtility(IConvert) img = convert(data=kwargs.get("svg", ""), data_from="svg", data_to="png") if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") sp = self.siteProperties qrPosition = sp.get("googlechart.qrcode_position", "Disabled") qrVertical = int(sp.get("googlechart.qrcode_vertical_space_for_png_export", 0)) qrHorizontal = int(sp.get("googlechart.qrcode_horizontal_space_for_png_export", 0)) wmPath = sp.get("googlechart.watermark_image", "") wmPosition = sp.get("googlechart.watermark_position", "Disabled") wmVertical = int(sp.get("googlechart.watermark_vertical_space_for_png_export", 0)) wmHorizontal = int(sp.get("googlechart.watermark_horizontal_space_for_png_export", 0)) shiftSecondImg = False hShift = 0 if qrPosition == wmPosition: shiftSecondImg = True if qrPosition != "Disabled": qr_con = urllib2.urlopen(kwargs.get("qr_url")) qr_img = qr_con.read() qr_con.close() img = applyWatermark(img, qr_img, qrPosition, qrVertical, qrHorizontal, 0.7) if shiftSecondImg: hShift = Image.open(StringIO(qr_img)).size[0] + qrHorizontal if wmPosition != "Disabled": try: wm_con = urllib2.urlopen(wmPath) wm_img = wm_con.read() wm_con.close() img = applyWatermark(img, wm_img, wmPosition, wmVertical, wmHorizontal + hShift, 0.7) except ValueError, err: logger.exception(err)
class GooglechartsSection(object): """ Googlecharts Settings Section """ implements(IDavizSection) prefix = 'googlechart' title = _('Google Charts Settings') form_fields = FormFields( schema.Choice( __name__='googlechart.qrcode_position', title=_(u"QRCode Position"), description=_(u"Position of QR Code"), required=True, default='Disabled', vocabulary= 'eea.googlecharts.controlpanel.vocabularies.imgPositions', ), schema.Int( __name__='googlechart.qrcode_horizontal_space_for_png_export', title=_(u'QRCode Horizontal Space For PNG Export'), description=_(u"""Horizontal space of QR Code from margin of the container (for PNG Export)"""), required=False, default=0), schema.Int( __name__='googlechart.qrcode_vertical_space_for_png_export', title=_(u'QRCode Vertical Space For PNG Export'), description=_(u"""Vertical space of QR Code from margin of the container (for PNG Export)"""), required=False, default=0), schema.Int(__name__='googlechart.qrcode_size', title=_(u'QRCode Size'), description=_(u"Size of QR Code"), required=False, default=70), schema.Choice( __name__='googlechart.watermark_position', title=_(u"Watermark Position"), description=_(u"Position of Watermark"), required=True, default='Disabled', vocabulary= 'eea.googlecharts.controlpanel.vocabularies.imgPositions', ), schema.TextLine(__name__='googlechart.watermark_image', description=_(u"Link to watermark image"), title=_(u'Watermark Image'), required=True), schema.Int( __name__='googlechart.watermark_horizontal_space_for_png_export', title=_(u'Watermark Horizontal Space For PNG Export'), description=_(u"""Horizontal space of Watermark image from margin of the container (for PNG Export)"""), required=False, default=0), schema.Int( __name__='googlechart.watermark_vertical_space_for_png_export', title=_(u'Watermark Vertical Space For PNG Export'), description=_(u"""Vertical space of Watermark image from margin of the container (for PNG Export)"""), required=False, default=0), )
def save_svg_and_png(self, kwargs): """ Save png out of the svg version of the chart """ if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'img') chart_url = self.context.absolute_url() + "#" + "tab-" + filename svg_filename = filename + ".svg" filename += ".png" sp = self.siteProperties qr_size = sp.get('googlechart.qrcode_size', '70') object_ids = self.context.objectIds() if qr_size == '0': qr_size = '70' qr_url = (u"https://chart.apis.google.com" "/chart?cht=qr&chld=H%sC0&chs=%sx%s&chl=%s" % ("%7", qr_size, qr_size, urllib2.quote(chart_url))) self.request.form['qr_url'] = qr_url svg_data = kwargs.get('svg', '') if not svg_data: return _("Success") new_svg = False if svg_filename not in object_ids: new_svg = True svg_filename = self.context.invokeFactory('File', id=svg_filename) svg_obj = self.context._getOb(svg_filename) svg_file_field = svg_obj.getField('file') svg_field_data = svg_file_field.getRaw(svg_obj).getIterator().read() if svg_field_data and svg_data == svg_field_data: return _("Success") elif svg_field_data: # 21894 svg_data from the form and the data saved within the current # svg files sometimes has the clipPath id number changed, otherwise # the files are identical in which case we no longer need to perform # any svg and image generation pattern = re.compile(r'_ABSTRACT_RENDERER_ID_\d+') # 79908 check if we have a result for pattern search pattern_match = pattern.search(svg_data) if pattern_match: svg_data_match = pattern_match.group() svg_field_data_matched = pattern.sub(svg_data_match, svg_field_data) if svg_data == svg_field_data_matched: return _("Success") # create image from the current svg img = super(SavePNGChart, self).__call__() # 79908 check if img return has PNG within the string # as img can contain ERROR message in case of an error # which means the image will contain a string instead of actual # image data if not img or img and 'PNG' not in img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") new_file = False if filename not in object_ids: new_file = True filename = self.context.invokeFactory('Image', id=filename) img_obj = self.context._getOb(filename) if new_file: img_obj.setExcludeFromNav(True) image_field = img_obj.getField('image') image_field.getMutator(img_obj)(img) if new_svg: svg_obj.setExcludeFromNav(True) svg_file_field.getMutator(svg_obj)(svg_data) wftool = getToolByName(svg_obj, "portal_workflow") state = wftool.getInfoFor(svg_obj, 'review_state', None) if state: if state != 'visible': workflows = wftool.getWorkflowsFor(svg_obj) workflow = workflows[0] transitions = workflow.transitions # publish for transition in wftool.getTransitionsFor(svg_obj): tid = transition.get('id') tob = transitions.get(tid) if not tob: continue if tob.new_state_id != 'published': continue self.request.form['_no_emails_'] = True workflow.doActionFor(svg_obj, tid) break # then make it public draft for transition in wftool.getTransitionsFor(svg_obj): tid = transition.get('id') tob = transitions.get(tid) if not tob: continue if tob.new_state_id != 'visible': continue workflow.doActionFor(svg_obj, tid) break svg_obj.reindexObject() if not new_svg: notify(InvalidateCacheEvent(svg_obj)) return _("Success")
def __call__(self, **kwargs): form = getattr(self.request, 'form', {}) kwargs.update(form) convert = getUtility(IConvert) svg = kwargs.get('svg', '') # Fix for IE inserting double " in some svg attributes" svg = re.sub(r"url\("(.*?)"\)", r'url(\1)', svg) filename = kwargs.get('filename', 'export') img = None if kwargs.get('export_fmt') == 'svg' and svg != '': return self.export_svg(svg, filename) if svg != '': img = convert(data=svg, data_from='svg', data_to='png') if kwargs.get('imageChart_url', '') != '': img_con = urllib2.urlopen(kwargs.get('imageChart_url')) img = img_con.read() img_con.close() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") sp = self.siteProperties qrPosition = sp.get('googlechart.qrcode_position', 'Disabled') qrVertical = int( sp.get('googlechart.qrcode_vertical_space_for_png_export', 0)) qrHorizontal = int( sp.get('googlechart.qrcode_horizontal_space_for_png_export', 0)) wmPath = sp.get('googlechart.watermark_image', '') wmPosition = sp.get('googlechart.watermark_position', 'Disabled') wmVertical = int( sp.get('googlechart.watermark_vertical_space_for_png_export', 0)) wmHorizontal = int( sp.get('googlechart.watermark_horizontal_space_for_png_export', 0)) shiftSecondImg = False hShift = 0 if qrPosition == wmPosition: shiftSecondImg = True if qrPosition != 'Disabled': qr_con = urllib2.urlopen(kwargs.get('qr_url')) qr_img = qr_con.read() qr_con.close() img = applyWatermark(img, qr_img, qrPosition, qrVertical, qrHorizontal, 0.7) if shiftSecondImg: hShift = Image.open(StringIO(qr_img)).size[0] + qrHorizontal if wmPosition != 'Disabled': try: wm_con = urllib2.urlopen(wmPath) wm_img = wm_con.read() wm_con.close() img = applyWatermark(img, wm_img, wmPosition, wmVertical, wmHorizontal + hShift, 0.7) except ValueError, err: logger.exception(err)
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'img') chart_url = self.context.absolute_url() + "#" + "tab-" + filename svg_filename = filename + ".svg" filename = filename + ".png" sp = self.siteProperties qr_size = sp.get('googlechart.qrcode_size', '70') if qr_size == '0': qr_size = '70' qr_url = (u"http://chart.apis.google.com" "/chart?cht=qr&chld=H|0&chs=%sx%s&chl=%s" % (qr_size, qr_size, urllib2.quote(chart_url))) self.request.form['qr_url'] = qr_url img = super(SavePNGChart, self).__call__() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) svg_data = kwargs.get('svg', '') if svg_data: if svg_filename not in self.context.objectIds(): svg_filename = self.context.invokeFactory('File', id=svg_filename) svg_obj = self.context._getOb(svg_filename) svg_obj.setExcludeFromNav(True) svg_obj.getField('file').getMutator(svg_obj)(kwargs.get('svg', '')) wftool = getToolByName(svg_obj, "portal_workflow") workflows = wftool.getWorkflowsFor(svg_obj) if len(workflows) > 0: workflow = workflows[0] transitions = workflow.transitions state = wftool.getInfoFor(svg_obj, 'review_state') if state != 'visible': available_transitions = [ transitions[i['id']] for i in wftool.getTransitionsFor(svg_obj) ] to_do = [ k for k in available_transitions if k.new_state_id == 'published' ] self.request.form['_no_emails_'] = True for item in to_do: workflow.doActionFor(svg_obj, item.id) break # then make it public draft available_transitions = [ transitions[i['id']] for i in wftool.getTransitionsFor(svg_obj) ] to_do = [ k for k in available_transitions if k.new_state_id == 'visible' ] for item in to_do: workflow.doActionFor(svg_obj, item.id) break svg_obj.reindexObject() notify(InvalidateCacheEvent(svg_obj)) return _("Success")
class DashboardEdit(ChartsEdit): """ Edit google dashboard """ form_fields = Fields(IGoogleChartsEdit) def __init__(self, context, request): super(DashboardEdit, self).__init__(context, request) self.dashboard_name = '' self._dashboards = None self._dashboard = None @property def dashboards(self): """ Get dashboards from annotations """ if self._dashboards is None: mutator = queryAdapter(self.context, IVisualizationConfig) viewname = self.__name__.replace('googlechart.googledashboard', 'googlechart.googledashboards', 1) viewname = viewname.replace('.edit', '') self._dashboards = mutator.view(viewname, {}) return self._dashboards @dashboards.setter def dashboards(self, value): """ Update dashboards settings """ if value == 'Changed': value = self.dashboards mutator = queryAdapter(self.context, IVisualizationConfig) viewname = self.__name__.replace('googlechart.googledashboard', 'googlechart.googledashboards', 1) viewname = viewname.replace('.edit', '') mutator.edit_view(viewname, **value) @property def dashboard(self): """ Return dashboard by name """ if self._dashboard is None: self.dashboards.setdefault('dashboards', []) for dashboard in self.dashboards['dashboards']: if dashboard.get('name', '') == self.dashboard_name: self._dashboard = dashboard break # Dashboard not found if self._dashboard is None: self._dashboard = {} return self._dashboard def json(self, **kwargs): """ Return config JSON """ return json.dumps(dict(self.dashboard)) def dashboardRename(self, **kwargs): """ Rename dashboard """ title = kwargs.get('title', '') self.dashboard['title'] = title self.dashboards = "Changed" return _(u"Dashboard renamed") def dashboardDelete(self, **kwargs): """ Delete dashboard """ dashboards = self.dashboards.get('dashboards', []) self.dashboards['dashboards'] = [ dashboard for dashboard in dashboards if dashboard.get('name') != self.dashboard_name ] self.dashboards = 'Changed' return _(u"Dashboard deleted") def widgetEdit(self, **kwargs): """ Edit dashboard widget """ settings = kwargs.pop('settings', "{}") try: settings = json.loads(settings) except Exception, err: logger.exception(err) return err name = kwargs.get('name', '') if not name: msg = 'Empty widget name provided %s' % name logger.exception(msg) return msg widgets = self.dashboard.get('widgets', []) changed = False for widget in widgets: if widget.get('name', '') == name: widget.update(settings) changed = True if changed: self.dashboards = 'Changed' return _(u'Changes saved')
def save_svg_and_png(self, kwargs): """ Save png out of the svg version of the chart """ if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'img') chart_url = self.context.absolute_url() + "#" + "tab-" + filename svg_filename = filename + ".svg" filename += ".png" sp = self.siteProperties qr_size = sp.get('googlechart.qrcode_size', '70') object_ids = self.context.objectIds() if qr_size == '0': qr_size = '70' qr_url = ( u"http://chart.apis.google.com" "/chart?cht=qr&chld=H|0&chs=%sx%s&chl=%s" % ( qr_size, qr_size, urllib2.quote(chart_url))) self.request.form['qr_url'] = qr_url svg_data = kwargs.get('svg', '') if not svg_data: return _("Success") new_svg = False if svg_filename not in object_ids: new_svg = True svg_filename = self.context.invokeFactory('File', id=svg_filename) svg_obj = self.context._getOb(svg_filename) svg_file_field = svg_obj.getField('file') svg_field_data = svg_file_field.getRaw(svg_obj).getIterator().read() if svg_field_data and svg_data == svg_field_data: return _("Success") elif svg_field_data: # 21894 svg_data from the form and the data saved within the current # svg files sometimes has the clipPath id number changed, otherwise # the files are identical in which case we no longer need to perform # any svg and image generation pattern = re.compile(r'_ABSTRACT_RENDERER_ID_\d+') svg_data_match = pattern.search(svg_data).group() svg_field_data_matched = pattern.sub(svg_data_match, svg_field_data) if svg_data == svg_field_data_matched: return _("Success") # create image from the current svg img = super(SavePNGChart, self).__call__() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") new_file = False if filename not in object_ids: new_file = True filename = self.context.invokeFactory('Image', id=filename) img_obj = self.context._getOb(filename) if new_file: img_obj.setExcludeFromNav(True) image_field = img_obj.getField('image') image_field.getMutator(img_obj)(img) if new_svg: svg_obj.setExcludeFromNav(True) svg_file_field.getMutator(svg_obj)(svg_data) wftool = getToolByName(svg_obj, "portal_workflow") state = wftool.getInfoFor(svg_obj, 'review_state', None) if state: if state != 'visible': workflows = wftool.getWorkflowsFor(svg_obj) workflow = workflows[0] transitions = workflow.transitions available_transitions = [transitions[i['id']] for i in wftool.getTransitionsFor(svg_obj)] to_do = [k for k in available_transitions if k.new_state_id == 'published'] self.request.form['_no_emails_'] = True for item in to_do: workflow.doActionFor(svg_obj, item.id) break # then make it public draft available_transitions = [transitions[i['id']] for i in wftool.getTransitionsFor(svg_obj)] to_do = [k for k in available_transitions if k.new_state_id == 'visible'] for item in to_do: workflow.doActionFor(svg_obj, item.id) break svg_obj.reindexObject() if not new_svg: notify(InvalidateCacheEvent(svg_obj)) return _("Success")
def __call__(self, **kwargs): form = getattr(self.request, 'form', {}) kwargs.update(form) convert = getUtility(IConvert) svg = kwargs.get('svg', '') # Fix for IE inserting double " in some svg attributes" svg = re.sub(r"url\("(.*?)"\)", r'url(\1)', svg) filename = kwargs.get('filename', 'export') img = None if kwargs.get('export_fmt') == 'svg' and svg != '': return self.export_svg(svg, filename) if svg != '': img = convert( data=svg, data_from='svg', data_to='png' ) if kwargs.get('imageChart_url', '') != '': img_con = urllib2.urlopen(kwargs.get('imageChart_url')) img = img_con.read() img_con.close() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") sp = self.siteProperties qrPosition = sp.get( 'googlechart.qrcode_position', 'Disabled') qrVertical = int(sp.get( 'googlechart.qrcode_vertical_space_for_png_export', 0)) qrHorizontal = int(sp.get( 'googlechart.qrcode_horizontal_space_for_png_export', 0)) wmPath = sp.get( 'googlechart.watermark_image', '') wmPosition = sp.get( 'googlechart.watermark_position', 'Disabled') wmVertical = int(sp.get( 'googlechart.watermark_vertical_space_for_png_export', 0)) wmHorizontal = int(sp.get( 'googlechart.watermark_horizontal_space_for_png_export', 0)) shiftSecondImg = False hShift = 0 if qrPosition == wmPosition: shiftSecondImg = True if qrPosition != 'Disabled': qr_con = urllib2.urlopen(kwargs.get('qr_url')) qr_img = qr_con.read() qr_con.close() img = applyWatermark(img, qr_img, qrPosition, qrVertical, qrHorizontal, 0.7) if shiftSecondImg: hShift = Image.open(StringIO(qr_img)).size[0] + qrHorizontal if wmPosition != 'Disabled': try: wm_con = urllib2.urlopen(wmPath) wm_img = wm_con.read() wm_con.close() img = applyWatermark(img, wm_img, wmPosition, wmVertical, wmHorizontal + hShift, 0.7) except ValueError, err: logger.exception(err)
def __call__(self, **kwargs): if not IFolderish.providedBy(self.context): return _("Can't save png chart on a non-folderish object !") form = getattr(self.request, 'form', {}) kwargs.update(form) filename = kwargs.get('filename', 'img') chart_url = self.context.absolute_url() + "#" + "tab-" + filename svg_filename = filename + ".svg" filename = filename + ".png" sp = self.siteProperties qr_size = sp.get('googlechart.qrcode_size', '70') if qr_size == '0': qr_size = '70' qr_url = ( u"http://chart.apis.google.com" "/chart?cht=qr&chld=H|0&chs=%sx%s&chl=%s" % ( qr_size, qr_size, urllib2.quote(chart_url))) self.request.form['qr_url'] = qr_url img = super(SavePNGChart, self).__call__() if not img: return _("ERROR: An error occured while exporting your image. " "Please try again later.") if filename not in self.context.objectIds(): filename = self.context.invokeFactory('Image', id=filename) obj = self.context._getOb(filename) obj.setExcludeFromNav(True) obj.getField('image').getMutator(obj)(img) svg_data = kwargs.get('svg', '') if svg_data: if svg_filename not in self.context.objectIds(): svg_filename = self.context.invokeFactory('File', id=svg_filename) svg_obj = self.context._getOb(svg_filename) svg_obj.setExcludeFromNav(True) svg_obj.getField('file').getMutator(svg_obj)(kwargs.get('svg', '')) wftool = getToolByName(svg_obj, "portal_workflow") workflows = wftool.getWorkflowsFor(svg_obj) if len(workflows) > 0: workflow = workflows[0] transitions = workflow.transitions state = wftool.getInfoFor(svg_obj, 'review_state') if state != 'visible': available_transitions = [transitions[i['id']] for i in wftool.getTransitionsFor(svg_obj)] to_do = [k for k in available_transitions if k.new_state_id == 'published'] for item in to_do: workflow.doActionFor(svg_obj, item.id) break # then make it public draft available_transitions = [transitions[i['id']] for i in wftool.getTransitionsFor(svg_obj)] to_do = [k for k in available_transitions if k.new_state_id == 'visible'] for item in to_do: workflow.doActionFor(svg_obj, item.id) break svg_obj.reindexObject() notify(ObjectModifiedEvent(svg_obj)) return _("Success")