def resolveResource(url): """Resolve the given URL to a unicode string. If the URL is an absolute path, it will be made relative to the Plone site root. """ if url.startswith('/'): site = getSite() url = '/'.join(site.getPhysicalPath()) + url response = subrequest(url) if response.status == 404: raise NotFound(url) resolved = response.getBody() if isinstance(resolved, str): charset = extractCharset(response) resolved = resolved.decode(charset) if response.status in (301, 302): site = getSite() location = response.headers.get('location') or '' if location.startswith(site.absolute_url()): return resolveResource(location[len(site.absolute_url()):]) elif response.status != 200: raise RuntimeError(resolved) return resolved
def clean_old_interfaces(context): log = logging.getLogger("policy CIRB clean old interfaces") registry = context.getImportStepRegistry() old_steps = ["cirb.site.various", "setupFolderNav"] for old_step in old_steps: if old_step in registry.listSteps(): registry.unregisterStep(old_step) # Unfortunately we manually have to signal the context # (portal_setup) # that it has changed otherwise this change is not persisted. context._p_changed = True log.info("Old %s import step removed from import registry.", old_step) # XXX clean some unused skins ! adapters = getSite().getSiteManager().adapters._adapters # 'IThemeSpecific' from module 'cirb.site.browser.interfaces for adapter in adapters: if adapter.keys(): if adapter.keys()[0].__module__ == 'zope.interface': dic = adapter.values()[0] for key in dic.keys(): if key.__module__ == 'cirb.site.browser.interfaces': del dic[key] log.info("delete {0} ".format(key.__module__)) getSite().getSiteManager().adapters._p_changed = True getSite().getSiteManager().adapters._adapters = adapters context._p_jar.sync()
def test_site(self): traverse('/folder1') site_url1 = getSite().absolute_url() response = subrequest('/folder2/@@url') self.assertEqual(response.status, 200) site_url2 = getSite().absolute_url() self.assertEqual(site_url1, site_url2)
def __init__(self, context, request): self.request = request self.context = getSite() self.configuration = interfaces.IConfiguration(getSite()) self.membership = getToolByName(self.context, 'portal_membership') self.registration = getToolByName(self.context, 'portal_registration') self.groups = getToolByName(self.context, 'portal_groups')
def __init__(self, rel): # XXX: wrap our relationship in the current Site site_chain = getSite().aq_chain site_chain.insert(0, rel) rel = site_chain.pop(-1) for item in reversed(site_chain): rel = aq_base(site_chain.pop(-1)).__of__(rel) self.rel = rel # Use annotations for storing state self.annotations = IAnnotations(rel).setdefault(ANNOTATIONS_KEY, PersistentMapping()) # use the current Site for the tool lookup self.wf_tool = getToolByName(getSite(), 'portal_workflow')
def __call__(self, context): try: catalog = getToolByName(context, "portal_catalog") except AttributeError: catalog = getToolByName(getSite(), "portal_catalog") brains = catalog.searchResults(**self.query) return BrainsVocabulary.fromBrains(brains, context)
def send_message(self, data): subject = data.get('subject') portal = getSite() registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') send_to_address = mail_settings.email_from_address from_address = mail_settings.email_from_address registry = getUtility(IRegistry) encoding = registry.get('plone.email_charset', 'utf-8') host = getToolByName(self.context, 'MailHost') data['url'] = portal.absolute_url() message = self.generate_mail(data, encoding) message = MIMEText(message, 'plain', encoding) message['Reply-To'] = data['sender_from_address'] try: # This actually sends out the mail host.send( message, send_to_address, from_address, subject=subject, charset=encoding ) except (SMTPException, RuntimeError), e: log.error(e) plone_utils = getToolByName(portal, 'plone_utils') exception = plone_utils.exceptionString() message = _(u'Unable to send mail: ${exception}', mapping={u'exception': exception}) IStatusMessage(self.request).add(message, type=u'error')
def send_message(self, data): subject = data.get("subject") portal = getSite() registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix="plone") send_to_address = mail_settings.email_from_address from_address = mail_settings.email_from_address registry = getUtility(IRegistry) encoding = registry.get("plone.email_charset", "utf-8") host = getToolByName(self.context, "MailHost") data["url"] = portal.absolute_url() message = self.generate_mail(data, encoding) message = MIMEText(message, "plain", encoding) message["Reply-To"] = Header(data["sender_from_address"], encoding) try: # This actually sends out the mail host.send(message, send_to_address, from_address, subject=subject, charset=encoding) except (SMTPException, RuntimeError), e: log.error(e) plone_utils = getToolByName(portal, "plone_utils") exception = plone_utils.exceptionString() message = _(u"Unable to send mail: ${exception}", mapping={u"exception": exception}) IStatusMessage(self.request).add(message, type=u"error")
def repl(cls, match): groups = match.groupdict() if groups.get('url'): old_url = groups.get('url') if not old_url.startswith('resolveuid/'): site = getSite() portal_url = site.portal_url site_url = site.absolute_url() if portal_url.isURLInPortal(old_url, cls.context or None): path = old_url.replace('%s/' % site_url, '', 1) suffix = [] content = None while path: content = site.unrestrictedTraverse(path, default=None) if IUUIDAware.providedBy(content): break suffix.insert(0, path.split('/')[-1]) path = '/'.join(path.split('/')[:-1]) if content and IUUIDAware.providedBy(content): uuid = IUUID(content) suffix.insert(0, '') new_url = 'resolveuid/%s' % uuid + '/'.join(suffix) return match.string[match.start():match.end()].replace(old_url, new_url) return match.string[match.start():match.end()]
def cookWhenChangingSettings(settings, event): """When our settings are changed, re-cook the main registries """ for name in (config.JSTOOLNAME, config.CSSTOOLNAME, config.KSSTOOLNAME,): tool = getToolByName(getSite(), name, None) if tool is not None: tool.cookResources()
def handle_apply(self, action): data, errors = self.extractData() if errors: return fridgemanager = IFridgeManager(self.context) user_data = fridgemanager.get_entry_payload(data["fridge_rand"]) if user_data is not None: # Testing uniqueness of username portal = getSite() pas_tool = getToolByName(portal, "acl_users") members = pas_tool.getUserById(data["username"]) if members is not None: raise forminterfaces.WidgetActionExecutionError( "username", interface.Invalid(_(u"username_invalid_error")) ) # Add member: We store username, password and email-address in the # default Plone member profile. All other member properties # (description, location, home_page, newsletter, etc.) are stored in # the Dexterity-based memberfolder. roles = [] domains = [] mtool = getToolByName(portal, "portal_membership") password = data["password"] if isinstance(password, unicode): password = password.encode("utf-8") mtool.addMember(data["username"], password, roles, domains) mtool.createMemberarea(data["username"]) membersfolder = mtool.getMembersFolder() memberfolder = membersfolder[data["username"]] memberfolder.title = data["fullname"] memberfolder.description = data["description"] memberfolder.location = data["location"] memberfolder.home_page = data["home_page"] memberfolder.portrait = data["portrait"] memberfolder.newsletter = data["newsletter"] memberfolder.email = user_data["email"] notify(ObjectModifiedEvent(memberfolder)) memberfolder.reindexObject() # Remove the fridge entry fridgemanager.delete_entry(data["fridge_rand"]) # Log the new member in pas_tool.session._setupSession(data["username"].encode("utf-8"), self.request.RESPONSE) IStatusMessage(self.request).add( _(u"profile_registration_success_notification", default="Registration success"), type="info" ) else: IStatusMessage(self.request).add(_(u"profile_registration_expired_or_invalid_notification"), type="error") return self._redirect()
def __init__(self, context): super(PortletControlPanelAdapter, self).__init__(context) self.portal = getSite() self.properties_tool = getToolByName(self.portal, 'portal_properties') self.context = self.properties_tool.site_properties self.encoding = self.properties_tool.site_properties.default_charset
def _getRecievers(self, type): context = aq_inner(self.context) portal = getSite() presscenter = portal['presscenter'] if type == 'test': recievers = presscenter.testRecipients else: recievers = getattr(context, 'recipients', '') recipients = [] if IPressRelease.providedBy(context) and type == 'send_now': subscribers = getattr(presscenter, 'subscribers', '') if subscribers: for item in subscribers: recipient = {} recipient['mail'] = item recipient['name'] = item recipients.append(recipient) if recievers: for address in recievers: recipient = {} try: recipient_email, recipient_name = address.split(',') except: recipient_email = address recipient_name = address recipient['mail'] = recipient_email recipient['name'] = safe_unicode(recipient_name) recipients.append(recipient) return recipients
def getCurrentSkinName(self): """Get the currently active skin name """ # For reasons of horridness, we can't use acquisition here portal_url = getToolByName(getSite(), 'portal_url') return portal_url.getPortalObject().getCurrentSkinName()
def updateKupu(context): # Ordinarily, GenericSetup handlers check for the existence of XML files. # Here, we are not parsing an XML file, but we use this text file as a # flag to check that we actually meant for this import step to be run. # The file is found in profiles/default. if context.readDataFile('collective.imagetags_kupu.txt') is None: return # Add additional setup code here out = StringIO() portal = getSite() # Get kupu tool and update its paragraph_styles property kt = getToolByName(portal, 'kupu_library_tool', None) if kt: new_style = 'Show tags|img|imagetags-show' styles = kt.getParagraphStyles() if not new_style in styles: styles.append(new_style) kt.configure_kupu(parastyles=styles) transaction.savepoint() print >> out, "Updated paragraph_styles in kupu: %s" % new_style else: print >> out, "kupu already has %s in paragraph_styles" % new_style context.getLogger("collective.imagetags").info(out.getvalue()) return out.getvalue()
def loadContent(self): """ Agregate content from content_aggregation_sources. """ # issue_template = self.restrictedTraverse(self.getTemplate()) enl_template_obj_id = self.getTemplate() enl = self.getNewsletter() if enl_template_obj_id not in enl.objectIds(): log.warn("No enl_template found, skip loadContent!") return issue_template = getattr(enl.aq_explicit, enl_template_obj_id, None) # here we create a write on read, but we do not need to persist it: sp = transaction.savepoint() issue_template.setIssue(self.UID()) portal = getSite() template_id = issue_template.getAggregationTemplate() if template_id != 'custom': template_obj = portal.restrictedTraverse(template_id) # XXX we copy over the template here every time we load the content # which is not perfect but ok for now. # This will be refactored when we drop Plone 4 support and use # behaviors on source object like Collections issue_template.setBody(template_obj.read()) text = issue_template.body() sp.rollback() self.setText(text)
def CMFDefaultPortal(db=None, connection=None, environ=None): """Context manager for working with the Plone portal during layer setup:: with CMFDefaultPortal() as portal: ... This is based on the ``z2.zopeApp()`` context manager. See the module ``plone.testing.z2`` for details. Do not use this in a test. Use the 'portal' resource from the PloneFixture layer instead! Pass a ZODB handle as ``db`` to use a specificdatabase. Alternatively, pass an open connection as ``connection`` (the connection will not be closed). """ from zope.site.hooks import setSite, getSite, setHooks setHooks() site = getSite() with z2.zopeApp(db, connection, environ) as app: portal = app[SITE_ID] setSite(portal) z2.login(portal['acl_users'], TEST_USER_ID) try: yield portal finally: z2.logout() if site is not portal: setSite(site)
def wrapped_func(*args, **kw): sm, site = getSecurityManager(), getSite() try: return func(*args, **kw) finally: setSecurityManager(sm) setSite(site)
def __init__(self, context): self.context = context self.portal = getSite() registry = getUtility(IRegistry) self.encoding = 'utf-8' self.mail_settings = registry.forInterface( IMailSchema, prefix="plone")
def breadcrumbs(self): context = aq_inner(self.context) request = self.request if hasattr(context, 'route') and context.route.breadcrumbFactory: return context.route.breadcrumbFactory(context, request) # XXX this is the main part here: # to up 2 parents since the current context # is wrapped if IWrappedContext.providedBy(context): container = utils.parent(utils.parent(context)) elif IFragmentContext.providedBy(context): container = getSite() name, item_url = get_view_url(context) view = getMultiAdapter((container, request), name='breadcrumbs_view') base = tuple(view.breadcrumbs()) if base: item_url = '%s/%s' % (base[-1]['absolute_url'], name) base += ({'absolute_url': item_url, 'Title': utils.pretty_title_or_id(context, context)},) return base
def cachingInstanceSchemaFactory(context): """ schema adapter factory using a cache on the request object """ schema = None if CACHE_ENABLED: try: lookup = context.aq_acquire except AttributeError: site = getSite() lookup = site.aq_acquire try: request = lookup('REQUEST') except AttributeError: pass else: attr = CACHE_KEY cache = getattr(request, attr, _marker) if cache is _marker: cache = dict() setattr(request, attr, cache) # Setting the cache to something non-dictish like # None or False disables it if isinstance(cache, dict): # If the object is just being created, we use its id() as a # fallback. Generally the id() is not stable, as it changes # with Acquisition wrappers and ZODB ghosting key = IUUID(context, str(id(context))) schema = cache.get(key, None) if schema is None: schema = cache[key] = instanceSchemaFactory(context) if schema is None: schema = instanceSchemaFactory(context) return schema
def all_keywords(self, kwfilter): site = getSite() self.catalog = getToolByName(site, 'portal_catalog', None) if self.catalog is None: return SimpleVocabulary([]) index = self.catalog._catalog.getIndex(self.keyword_index) return safe_simplevocabulary_from_values(index._index, query=kwfilter)
def pushGlobalRegistry(portal, new=None, name=None): """Set a new global component registry that uses the current registry as a base. If you use this, you *must* call ``popGlobalRegistry()`` to restore the original state. If ``new`` is not given, a new registry is created. If given, you must provide a ``zope.component.globalregistry.BaseGlobalComponents`` object. Returns the new registry. Also ensure that the persistent component registry at ``portal`` has the new global registry as its base. """ from zope.site.hooks import setSite, getSite, setHooks site = getSite() localSiteManager = portal.getSiteManager() current = zca.pushGlobalRegistry(new=new) if current not in localSiteManager.__bases__: localSiteManager.__bases__ = (current, ) if site is not None: setHooks() setSite(site) return current
def __call__(self, context): site = getSite() wtool = getToolByName(site, "portal_workflow", None) if wtool is None: return SimpleVocabulary([]) transitions = {} for wf in wtool.values(): transition_folder = getattr(wf, "transitions", None) wf_name = wf.title or wf.id if transition_folder is not None: for transition in transition_folder.values(): # zope.i18nmessageid will choke # if undecoded UTF-8 bytestrings slip through # which we may encounter on international sites # where transition names are in local language. # This may break overlying functionality even # if the terms themselves are never used name = safe_unicode(transition.actbox_name) transition_title = translate(_(name), context=aq_get(wtool, "REQUEST", None)) transitions.setdefault(transition.id, []).append(dict(title=transition_title, wf_name=wf_name)) items = [] transition_items = transitions.items() transition_items.sort(key=lambda transition: transition[0]) for transition_id, info in transition_items: titles = set([i["title"] for i in info]) item_title = " // ".join(sorted(titles)) item_title = "%s [%s]" % (item_title, transition_id) items.append(SimpleTerm(transition_id, transition_id, item_title)) return SimpleVocabulary(items)
def _construct_webview_link(self): context = aq_inner(self.context) portal = getSite() portal_url = portal.absolute_url() uuid = IUUID(context, None) url = portal_url + '/@@pressitem-view?uid=' + uuid return url
def handle_apply(self, action): data, errors = self.extractData() if errors: return portal = getSite() # create a new rand expires = datetime.now() + timedelta(days=2) data = {'email': data['email']} rand = IFridgeManager(self.context).add_entry(data, expires) # send mail to user mail_to = data['email'] url = u"%s/%s/%s" % (self.context.absolute_url(), FORM_ID, rand) link = u'<a href="%s">%s</a>' % (url, url) message = translate(msgid=u'request_registration_mail_text', domain=DOMAIN, mapping={'link': link, 'expires': expires.strftime('%d.%m.%Y %H:%M')}, context=self.request, default=u'Finish your registration here ${link} by ${expires}.', ) mail_subject = translate(msgid="request_registration_mail_subject", domain=DOMAIN, context=self.request, default=u'Registration', ) notify(MailEvent(message, mail_to, subject=mail_subject)) IStatusMessage(self.request).add(_(u'request_registration_success_notification'), type='warn') return self._redirect()
def __call__(self, context): site = getSite() groups_tool = getToolByName(site, "portal_groups") is_zope_manager = getSecurityManager().checkPermission(ManagePortal, context) groups = groups_tool.listGroups() # Get group id, title tuples for each, omitting virtual group # 'AuthenticatedUsers' terms = [] for g in groups: if g.id == "AuthenticatedUsers": continue if "Manager" in g.getRoles() and not is_zope_manager: continue group_title = safe_unicode(g.getGroupTitleOrName()) if group_title != g.id: title = u"%s (%s)" % (group_title, g.id) else: title = group_title terms.append(SimpleTerm(g.id, g.id, title)) # Sort by title terms.sort(key=lambda x: normalizeString(x.title)) return SimpleVocabulary(terms)
def __getattr__(self, key): if not IS_PLONE_5: # BBB portal = getSite() mail_host = getUtility(IMailHost) key_map = { 'smtp_host': 'smtp_host', 'smtp_port': 'smtp_port', 'smtp_userid': 'smtp_uid', 'smtp_pass': '******', } if key in key_map: return getattr(mail_host, key, '') elif key == 'email_from_address': return portal.getProperty(key) elif key == 'email_from_name': return portal.getProperty(key) elif key == 'email_charset': return portal.getProperty(key) else: self.registry = getUtility(IRegistry) reg_mail = self.registry.forInterface( IMailSchema, prefix='plone') self.settings['smtp_host'] = reg_mail.smtp_host self.settings['smtp_port'] = reg_mail.smtp_port self.settings['smtp_userid'] = reg_mail.smtp_userid self.settings['smtp_pass'] = reg_mail.smtp_pass self.settings['email_from_address'] = reg_mail.email_from_address self.settings['email_from_name'] = reg_mail.email_from_name self.settings['email_charset'] = reg_mail.email_charset return self.settings.get(key)
def test_right_macro(self): # fixes #8016 class MyField: __name__ = 'the field' required = True default = u'the value' missing_value = None title = "" description = "" # the wysiwyg widget depends on the used editor pm = getToolByName(self.portal, 'portal_membership') member = pm.getAuthenticatedMember() editor = member.getProperty('wysiwyg_editor', '').lower() # let's add a custom editor # with a fake skin that should be catched # to provide a custom macro site = getSite() class MyMacros(object): def wysiwygEditorBox(self): return (('version', '1.6'), ('mode', 'html')) class MySkin(object): macros = MyMacros() site.cool_editor_wysiwyg_support = MySkin() # let's change it to `cool_editor` member.setMemberProperties({'wysiwyg_editor': 'cool_editor'}) w = WYSIWYGWidget(MyField(), TestRequest()) cool_editor = w()
def CreateOrgEvent(event): """this event be fired by member join event, username,address password parameters to create a membrane object""" site = getSite() catalog = getToolByName(site,'portal_catalog') try: newest = catalog.unrestrictedSearchResults({'object_provides': IOrgnizationFolder.__identifier__}) except: return memberfolder = newest[0].getObject() memberid = event.id try: item =createContentInContainer(memberfolder,"my315ok.socialorgnization.orgnization",checkConstraints=False,id=memberid) # setattr(memberfolder,'registrant_increment',memberid) item.title = event.title item.description = event.description item.address = event.address item.legal_person = event.legal_person item.supervisor = event.supervisor item.register_code = event.register_code ot = event.belondto_area if isinstance(ot, unicode): ot = ot.encode("utf-8") if ot == '\xe5\xb2\xb3\xe5\xa1\x98\xe5\x8c\xba': # 岳塘区 item.belondto_area = "yuetangqu" elif ot == '\xe9\x9b\xa8\xe6\xb9\x96\xe5\x8c\xba': #雨湖区 item.belondto_area = "yuhuqu" elif ot == '\xe9\x9f\xb6\xe5\xb1\xb1\xe5\xb8\x82': #韶山市 item.belondto_area = "shaoshanshi" elif ot == '\xe6\xb9\x98\xe4\xb9\xa1\xe5\xb8\x82': #湘乡市 item.belondto_area = "xiangxiangshi" elif ot == '\xe6\xb9\x98\xe6\xbd\xad\xe5\x8e\xbf': #湘潭县 item.belondto_area = "xiangtanxian" else: item.belondto_area = "xiangtanshi" #湘潭市 # item.belondto_area = event.belondto_area ot = event.organization_type if isinstance(ot, unicode): ot = ot.encode("utf-8") if ot == '\xe6\xb0\x91\xe9\x9d\x9e': # 民非 item.organization_type = "minfei" elif ot == '\xe7\xa4\xbe\xe4\xbc\x9a\xe5\x9b\xa2\xe4\xbd\x93': #社会团体 item.organization_type = "shetuan" else: item.organization_type = "jijinhui" # item.announcement_type = event.announcement_type import datetime datearray = event.passDate.split('-') if len(datearray) >= 3: val = map(int,datearray) item.passDate = datetime.date(*val) else: item.passDate = datetime.date.today() item.reindexObject() # membrane = getToolByName(item, 'membrane_tool') # membrane.reindexObject(item) except: return
def registerSAMLLogoutResponder(plugin, event): site = getSite() if site is None: return sm = site.getSiteManager() sm.registerUtility(plugin, ISAMLLogoutHandler)
def link_repl_func(link): portal_url = getSite().absolute_url() if link.startswith(portal_url): return 'http://www.sll.fi/{}'.format(link[len(portal_url) + 1:]) else: return link
def _setXLIFF(self, data, target_language=''): """ Set the data on one object """ site = getSite() uid_catalog = getToolByName(site, 'uid_catalog') if target_language == '': target_language = data['target-language'].encode('ascii') # nothing to do if there is no target language if not target_language: return try: oid = data['oid'].encode('ascii') results = uid_catalog(UID=oid) if len(results) != 1: #raise ValueError, "Uid catalog should return exactly one #result but returned %s." % len(results) raise KeyError, "Invalid OID %s" % oid source_ob = results[0].getObject() except KeyError: # old style xliff file. Using path #print "Using path to find target object" path = data['original'].encode('utf-8') source_ob = site.restrictedTraverse(path, None) if source_ob is None: raise ValueError( "%s not found, can not add translation." % data['original'].encode('utf-8')) # If the source object is language-neutral, it must receive a language # prior to translation # XXXX What to do if the source_ob HAS a language, but it differs # from the source-language inside the data? if source_ob.Language() == '': # Get the source language from the data source_language = data.get('source-language') # No source language present in the section, use site default if not source_language: langtool = getToolByName(site, 'portal_languages') source_language = langtool.getPreferredLanguage() source_ob.setLanguage(source_language) tm = ITranslationManager(source_ob) if not tm.has_translation(target_language): tm.add_translation(target_language) self.new_translations += 1 target_ob = tm.get_translation(target_language) if IBaseObject.providedBy(target_ob): # We dont want the id to get renamed to match the title target_ob.unmarkCreationFlag() values = {} for unit in data.findAll('trans-unit'): fieldname = unit['id'].encode('utf-8') value = unit.find('target').renderContents('utf-8').strip() # Note: We don't use xliff to remove values, so no value means no # translation and no change to the original # XXX: This doesn't handle values other than strings, this may be # a problem. if not value: continue # convert HTML entities value = safe_unicode(value) value = html_parser.unescape(value) values[fieldname] = value if IDexterityContent.providedBy(target_ob): # Dexterity schema = get_dx_schema(target_ob) for name, field in schema.items(): if ILanguageIndependentField.providedBy(field): # Copy from the original: field.set(target_ob, field.get(source_ob)) pass elif name == 'header_links': value = eval(values[name]) schema[name].set(target_ob, value) elif name in values: value = values[name] if IRichText.providedBy(field): value = RichTextValue(value,'text/html', 'text/x-html-safe') schema[name].set(target_ob, value) ######### set SEO Properties #### for seo_value in values: if seo_value.startswith('qSEO_'): if target_ob.hasProperty(seo_value): target_ob.manage_changeProperties({seo_value: values[seo_value].encode('utf-8')}) else: target_ob.manage_addProperty(seo_value, values[seo_value.encode('utf-8')], 'string') else: # Archetypes target_ob.processForm(data=1, metadata=1, values=values) # Set the correct format if shasattr(source_ob, 'text_format'): target_ob.setFormat(source_ob.text_format) self.total += 1
def AddContents(self): """ """ normalizer = getUtility(IIDNormalizer) try: if self.dados: portal = getSite() #Create folder SINESP if not hasattr(portal, 'sinesp'): _createObjectByType('Folder', portal, 'sinesp', title='Sinesp') folder_sinesp = getattr(portal, 'sinesp') folder_sinesp.setLayout('estatisticas-publicas-sinesp') for i in self.dados: #Create folder type tipo = i['tipo'] tipo_id = normalizer.normalize(tipo) if not hasattr(folder_sinesp, tipo_id): _createObjectByType('Folder', folder_sinesp, tipo_id, title=tipo) folder_tipo = getattr(folder_sinesp, tipo_id) #Create folder year ano = str(i['ano']) if not hasattr(folder_tipo, ano): _createObjectByType('Folder', folder_tipo, ano, title=ano) folder_ano = getattr(folder_tipo, ano) #Create folder UF # uf = i['uf'] # if not hasattr(folder_tipo, uf): # _createObjectByType('Folder', # folder_tipo, # uf, # title=uf) # folder_uf = getattr(folder_tipo, uf) #Create content id = str(i['ano']) + '-' + i['tipo'] + '-' + i['uf'] object_id = normalizer.normalize(id) if not hasattr(folder_ano, object_id): titulo = i['uf'] + ': ' + i['tipo'] _createObjectByType( 'sinesp', folder_ano, object_id, title=titulo, tipo=i['tipo'], uf=i['uf'], ano=i['ano'], qtd_ocorrencias=i['qtd_ocorrencias'], taxa=i['taxa'], universo=i['universo']) return True except: return False
def getItems(self): site = getSite() annotations = IAnnotations(site) return annotations.get('collective.newsflash.newsflash', [])
def __init__(self, context): self.context = context self.portal = getSite() registry = getUtility(IRegistry) self.encoding = 'utf-8' self.mail_settings = registry.forInterface(IMailSchema, prefix="plone")
def subrequest(url, root=None, stdout=None): assert url is not None, "You must pass a url" if isinstance(url, unicode): url = url.encode('utf-8') _, _, path, query, _ = urlsplit(url) parent_request = getRequest() assert parent_request is not None, \ "Unable to get request, perhaps zope.globalrequest is not configured." parent_site = getSite() security_manager = getSecurityManager() parent_app = parent_request.PARENTS[-1] if path.startswith('/'): path = normpath(path) vurl_parts = parent_request.get('VIRTUAL_URL_PARTS') if vurl_parts is not None: # Use the virtual host root path_past_root = unquote(vurl_parts[-1]) root_path = normpath(parent_request['PATH_INFO']).rstrip( '/')[:-len(path_past_root) or None] if root is None: path = root_path + path else: path = '%s/%s%s' % (root_path, root.virtual_url_path(), path) elif root is not None: path = '/%s%s' % (root.virtual_url_path(), path) else: try: parent_url = parent_request['URL'] if isinstance(parent_url, unicode): parent_url = parent_url.encode('utf-8') # extra is the hidden part of the url, e.g. a default view extra = unquote(parent_url[len(parent_request['ACTUAL_URL']):]) except KeyError: extra = '' here = parent_request['PATH_INFO'] + extra path = urljoin(here, path) path = normpath(path) request = parent_request.clone() for name, parent_value in parent_request.other.items(): if name in OTHER_IGNORE \ or OTHER_IGNORE_RE.match(name) \ or name.startswith('_'): continue request.other[name] = parent_value for key, value in parent_request.response.cookies.items(): request.cookies[key] = value['value'] request['PARENT_REQUEST'] = parent_request alsoProvides(request, ISubRequest) try: setRequest(request) request_container = RequestContainer(REQUEST=request) app = aq_base(parent_app).__of__(request_container) request['PARENTS'] = [app] response = request.response response.__class__ = SubResponse response.stderr = None # only used on retry it seems if stdout is None: stdout = StringIO() # It might be possible to optimize this response.stdout = stdout environ = request.environ environ['PATH_INFO'] = path environ['QUERY_STRING'] = query # Clean up the request. for header in CONDITIONAL_HEADERS: environ.pop(header, None) try: request.processInputs() traversed = request.traverse(path) result = mapply(traversed, positional=request.args, keyword=request, debug=None, maybe=1, missing_name=missing_name, handle_class=dont_publish_class, context=request, bind=1) if result is not response: response.setBody(result) for key, value in request.response.cookies.items(): parent_request.response.cookies[key] = value except: logger.exception("Error handling subrequest to %s" % url) response.exception() return response finally: request.clear() setRequest(parent_request) setSite(parent_site) setSecurityManager(security_manager)
def default_show_search(): # take the value from the global settings from collective.documentviewer.settings import GlobalSettings gsettings = GlobalSettings(getSite()) return gsettings.show_search
def __call__(self): site = getSite() self.request.response.redirect(site.absolute_url() + '/registrator/request_registration')
def default_enable_indexation(): # take the value from the global settings from collective.documentviewer.settings import GlobalSettings gsettings = GlobalSettings(getSite()) return gsettings.enable_indexation
def back_to_controlpanel(self): root = getSite() return dict(url=root.absolute_url() + '/plone_control_panel')