def handle_last_publication(self, slide): """ Gets the most recent updated publication and report""" site = getSite() catalog = site.portal_catalog result = catalog.searchResults( { "portal_type": "eea.climateadapt.publicationreport", "review_state": "published", "sort_on": "effective", "sort_order": "descending", }, full_objects=True, )[0] publi = result.getObject() image_url, copyright = self.getImages(slide) return { "image_url": image_url, "copyright": copyright, "title": publi.Title(), "description": publi.long_description, "category": "Most recent <br/> Publication or Report", "url": publi.absolute_url(), }
def validate(self, value, force=False): """ :param value: :param force: :return: """ super(UniqueRollNumberValidator, self).validate(value, force) # Custom validation here school = aq_inner(self.context) # assert ISchool.providedBy(school), _('Context must be derived from content type `%s`' % CONTENT_TYPE_SCHOOL) grade_widget = self.widget.form.widgets['grade'] portal_catalog = getToolByName(getSite(), 'portal_catalog') result = portal_catalog.searchResults( path='/'.join(school.getPhysicalPath()), portal_type=CONTENT_TYPE_STUDENT, grade=grade_widget.value[0], roll_number=value, sort_limit=1 ) if result: raise Invalid(_("Provided Roll Number `%s` is already exists!" % value))
def get_existing_edit_link(self): site = getSite() publictoken = IAnnotations(self).get(TOKEN_KEY, '-missingtoken-') url = "{0}/cptk/{1}/{2}".format(site.absolute_url(), publictoken, self.getId()) print "Token url: ", url return url
def validateUserInfo(self, user, set_id, set_info): """ -> ( error_info_1, ... error_info_N ) o Returned values are dictionaries, containing at least keys: 'id' -- the ID of the property, or None if the error is not specific to one property. 'error' -- the message string, suitable for display to the user. """ errors = [] site = portal.getSite() if set_info and set_info.get('password', None) is not None: password = set_info['password'] i = 1 while True: reg = getattr(self, 'p%i_re' % i, None) if not reg: break if not re.match(reg, password): err = getattr(self, 'p%i_err' % i, None) if err: errors += [translate(err.decode('utf8'), domain='Products.PasswordStrength', context=site.REQUEST)] i += 1 errors = [{'id': 'password', 'error': e} for e in errors] return errors
def handle_last_casestudy(self, slide): """ Gets the most recent updated casestudy""" site = getSite() catalog = site.portal_catalog brain = catalog.searchResults( { "portal_type": "eea.climateadapt.casestudy", "review_state": "published", "sort_on": "effective", "sort_order": "descending", }, full_objects=True, )[0] cs = brain.getObject() image_url, copyright = self.getImages(slide) return { "image_url": image_url, "copyright": copyright, "title": cs.Title(), "description": cs.long_description, "category": "Most recent <br/> Case Study", "url": cs.absolute_url(), }
def __call__(self): if 'form.buttons.save' in self.request.form: return self.index() if self.request.method == 'POST': pid = self.request.form.get('principalid') contexts = [self.context] wc = self.get_wc(self.context) if wc: contexts.append(wc) site = getSite() for location in PLONE_LOCATIONS: if self.context.aq_parent.id != 'countries': continue obj = site.unrestrictedTraverse(location + self.context.id) if obj: contexts.append(obj) for context in contexts: context.manage_delLocalRoles([pid]) logger.info("Removed country checkout special roles for %s", pid) url = self.context.absolute_url() + '/@@bise-country-share' return self.request.response.redirect(url) else: return self.index()
def get_existing_edit_link(self): site = getSite() publictoken = IAnnotations(self).get(TOKEN_KEY, '-missingtoken-') url = "{0}/cptk/{1}/{2}".format(site.absolute_url(), publictoken, self.getId() ) print "Token url: ", url return url
def get_private_edit_link(self): """ Returns the link to edit a city profile """ site = getSite() url = "{0}/cptk/{1}/{2}".format(site.absolute_url(), self._get_public_token(), self.getId()) print "Token url: ", url return url
def get_private_edit_link(self): """ Returns the link to edit a city profile """ site = getSite() url = "{0}/cptk/{1}/{2}".format(site.absolute_url(), self._get_public_token(), self.getId() ) print "Token url: ", url return url
def constraint_grade(value): """ :param value: :return: """ grades = load_vocabulary(getSite(), 'collective_DataTable_grade') if value not in [grade.value for grade in grades]: raise Invalid(_('Grade value must be from `collective_DataTable_grade` vocabulary!')) return True
def publishTraverse(self, request, name): if name == 'image': site = portal.getSite() icon = self.context.getIcon() if icon.startswith('/'): icon = icon[1:] img = site.restrictedTraverse(icon) if "++resource++" in icon: img = Image('img', 'image', img.GET()) img = img.__of__(self.context) return IconWrapper(img) return super(AceContentImagesTraverser, self).publishTraverse(request, name)
def get_discodata(): annotations = portal.getSite().__annotations__ if 'discodata' not in annotations: annotations._p_changed = True return setup_discodata(annotations) last_import_date = annotations['discodata']['timestamp'] if (datetime.now() - last_import_date).total_seconds() > 60 * 2: annotations._p_changed = True return setup_discodata(annotations) return annotations['discodata']['data']
def validate(self, value=None, force=False): """ :param value: :param force: :return: """ # assert IBook.providedBy(aq_base(self.context)), _('Context must be derived from content type `%s`' # % CONTENT_TYPE_BOOK) portal_catalog = getToolByName(getSite(), 'portal_catalog') book = portal_catalog.searchResults(path='/'.join(self.context.getPhysicalPath()), id=self.context.getId(), sort_limit=1)[0] if int(book.book_stock) < 1: raise Invalid(_("Insufficient stock of this book `%s`" % book.Title))
def __call__(self): fpath = resource_filename('eea.climateadapt.browser', 'data/cases_en_cdata.xml') s = open(fpath).read() e = fromstring(s) container = getSite()['metadata']['case-studies'] for item_node in e.xpath('//item'): item_id, field_title = '', '' for child in item_node.iterchildren(): if child.tag == 'item_id': item_id = child.text if child.tag == 'field_title': field_title = idnormalizer.normalize(child.text, None, 500) if item_id and field_title: annot = IAnnotations(container[field_title]) annot['import_id'] = item_id return 'AdapteCCA current case study fixed import_ids'
def validate(self, value, force=False): """ :param value: :param force: :return: """ super(UniqueISBNValidator, self).validate(value, force) library = aq_base(self.context) # assert ILibrary.providedBy(library), _('Context must be derived from content type `%s`' % CONTENT_TYPE_LIBRARY) portal_catalog = getToolByName(getSite(), 'portal_catalog') result = portal_catalog.searchResults( path='/'.join(library.getPhysicalPath()), portal_type=CONTENT_TYPE_BOOK, isbn=value, sort_limit=1) if result: raise Invalid(_("Provided ISBN Number `%s` is already exists!" % value))
def input_is_valid(self, data): """ Flag input as invalid if there already exists a setting/content type """ ptype = data.get('portal_type') screen_tool = getToolByName(getSite(), 'portal_screenshot') if screen_tool == self.context: if ptype in [obj.portal_type for obj in screen_tool.objectValues()]: self.status = _("There already exists a setting for the specified " "portal type") self.formErrorsMessage = self.status return False else: for obj in screen_tool.objectValues(): if ptype == obj.portal_type and self.context != obj: self.status = _( "Cannot change portal type, there already exists " "a setting for the specified portal type") self.formErrorsMessage = self.status return False return True
def publishTraverse(self, request, name): # import pdb # pdb.set_trace() if name == 'image': site = portal.getSite() if not hasattr(self.context, 'getIcon'): return super(AceContentImagesTraverser, self).publishTraverse(request, name) icon = self.context.getIcon() if icon.startswith('/'): icon = icon[1:] img = site.restrictedTraverse(icon) if "++resource++" in icon: img = Image('img', 'image', img.GET()) img = img.__of__(self.context) return IconWrapper(img) return super(AceContentImagesTraverser, self).publishTraverse(request, name)
def share_with_principal(self, principal_id, role): """ Setup proper share role for this principal """ logger.info("Setting up proper %s role for %s", role, principal_id) print "Sharing", principal_id, role contexts = [self.context] wc = self.get_wc(self.context) if wc: contexts.append(wc) site = getSite() for location in PLONE_LOCATIONS: if self.context.aq_parent.id != 'countries': continue obj = site.unrestrictedTraverse(location + self.context.id) if obj: contexts.append(obj) for folder in contexts: self.assign_role_to_principal(folder, role, principal_id) if ICountryPage not in list(providedBy(folder)): mark(folder, ICountryPage)
def async_screenshoteer_set_image(obj, url): """ extract url from embed field for Dashboards, request to screenshoteer and set the image to the proper field """ screen_tool = getToolByName(getSite(), 'portal_screenshot') attrs = [ 'emulate', 'waitforselector', 'el', 'click', 'no', 'pdf', 'fullPage', 'w', 'h', 'waitfor' ] default_settings = { 'w': 1920, 'h': 1080, 'fullPage': 'true', 'waitfor': 20, 'url': url } for setting in screen_tool.objectValues(): if setting.portal_type == obj.portal_type: for attr in attrs: if setting.getProperty(attr): default_settings.update({attr: setting.getProperty(attr)}) service_url = setting.getProperty('service_url') if service_url.endswith('/'): service_url = service_url[:-1] service_url += '/API/v1/retrieve_image_for_url' req = requests.get(service_url, stream=True, params=default_settings) if req.status_code == 200: image = Image.open(StringIO(req.content)) destfile = StringIO() destfile.seek(0) image.save(destfile, 'JPEG') obj.setImage(destfile.getvalue()) obj._p_changed = True obj.reindexObject() else: logger.error('Failed to set image on the following object %s' \ % obj.absolute_url())
def handle_news_items(self, slide): """ Gets the most recent updated news/events item""" site = getSite() # try: # news = site.restrictedTravers( # "observatory/more-events-observatory/launch-of-the-european-climate-" # "and-health-observatory-keeping-healthy-in-a-changing-climate" # ) # except: # noqa catalog = site.portal_catalog result = catalog.searchResults( { "portal_type": ["News Item", "Event"], "review_state": "published", "sort_on": "effective", "sort_order": "reverse", "path": { "query": "/cca/news-archive" }, }, full_objects=True, )[0] news = result.getObject() image_url, copyright = self.getImages(slide) return { "image_url": image_url, "copyright": copyright, "title": news.Title(), "description": news.description, "category": "Latest <br/> News & Events", "url": news.absolute_url(), }
def get_annot(): site = getSite() annot = IAnnotations(site, {}) return annot