def _deploy_additional_directories(self, additional_directories):
        site_path = urlparse(self.context.portal_url())[2]
        if site_path != "/":
            site_path = site_path.strip("/")
        for path in additional_directories:
            folder = self.context.restrictedTraverse(str(path), None)
            if not folder:
                log.warn("Could not export %s" % path)
            try:
                if IResource.providedBy(folder):
                    fullpath = folder.context.path
                    destination_path = os.path.join(self.base_dir, site_path, "++resource++" + folder.__name__)
                    if os.path.exists(destination_path):
                        shutil.rmtree(destination_path)
                    shutil.copytree(fullpath, destination_path)
                elif IResourceDirectory.providedBy(folder):

                    def handleFolder(container, relpath):
                        for filename in container.listDirectory():
                            obj = container[filename]
                            filepath = str(os.path.join(relpath, filename))
                            if IResourceDirectory.providedBy(obj):
                                # okay folder, recurse
                                handleFolder(obj, filepath)
                            else:
                                self._deploy_views([filepath], is_page=False, omit_transform=True)

                    handleFolder(folder, path)
                else:
                    log.warn("Unsupported directory type %s" % path)
            except AttributeError:
                log.warn("Not a valid supported directory type %s" % path)
def newrelic_transaction(event):

    try:
        request = event.request
        published = request.get('PUBLISHED', None)
        trans = newrelic.agent.current_transaction()

        # TODO: Better name resolvement. SimpleViewClass seems to have no reference
        # to the browserview it simplifies. Making it hard to make a proper dotted name.
        # Preffered name would be:  Products.MyProduct.browser.views.MyView
        # Now we only get the name as defined in conifure zcml, ie: "my_view"
        transname = published.__name__

        if trans:
            # We only want to track the following:
            # 1. BrowserViews (but not the resource kind ..)
            # 2. PageTemplate (/skins/*/*.pt ) being used as views
            if (IBrowserView.providedBy(published) or IPageTemplate.providedBy(published)) and not IResource.providedBy(published):
                trans.name_transaction(transname, group='Zope2', priority=1)
                newrelic.agent.add_custom_parameter('id', published.context.id)
                newrelic.agent.add_custom_parameter('absolute_url', published.context.absolute_url())
                logger.debug("Transaction: {0}".format(transname))
            else:
                # For debugging purpose
                logger.debug("NO transaction? : {0}   Browser: {1}  Resource: {2} PageTemplate: {3}".format(
                    transname,
                    IBrowserView.providedBy(published),
                    IResource.providedBy(published),
                    IPageTemplate.providedBy(published)))

    except Exception, e:
        # Log it and carry on.
        logger.exception(e)
Exemple #3
0
def newrelic_transaction(event):

    try:
        request = event.request
        published = request.get('PUBLISHED', None)
        trans = newrelic.agent.current_transaction()

        # TODO: Better name resolvement. SimpleViewClass seems to have no reference
        # to the browserview it simplifies. Making it hard to make a proper dotted name.
        # Preffered name would be:  Products.MyProduct.browser.views.MyView
        # Now we only get the name as defined in conifure zcml, ie: "my_view"
        transname = published.__name__

        if trans:
            # We only want to track the following:
            # 1. BrowserViews (but not the resource kind ..)
            # 2. PageTemplate (/skins/*/*.pt ) being used as views
            if (IBrowserView.providedBy(published)
                    or IPageTemplate.providedBy(published)
                ) and not IResource.providedBy(published):
                trans.name_transaction(transname, group='Zope2', priority=1)
                newrelic.agent.add_custom_parameter('id', published.context.id)
                newrelic.agent.add_custom_parameter(
                    'absolute_url', published.context.absolute_url())
                logger.debug("Transaction: {0}".format(transname))
            else:
                # For debugging purpose
                logger.debug(
                    "NO transaction? : {0}   Browser: {1}  Resource: {2} PageTemplate: {3}"
                    .format(transname, IBrowserView.providedBy(published),
                            IResource.providedBy(published),
                            IPageTemplate.providedBy(published)))

    except Exception, e:
        # Log it and carry on.
        logger.exception(e)
def newrelic_transaction(event):

    try:
        request = event.request
        published = request.get("PUBLISHED", None)
        trans = newrelic.agent.current_transaction()

        # TODO: Better name resolvement. SimpleViewClass seems to have no reference
        # to the browserview it simplifies. Making it hard to make a proper dotted name.
        # Preffered name would be:  Products.MyProduct.browser.views.MyView
        # Now we only get the name as defined in conifure zcml, ie: "my_view"
        transname = published.__name__

        if trans:
            # We only want to track the following:
            # 1. BrowserViews (but not the resource kind ..)
            # 2. PageTemplate (/skins/*/*.pt ) being used as views
            # 3. PageTemplates in ZMI
            if (IBrowserView.providedBy(published) or IPageTemplate.providedBy(published)) and not IResource.providedBy(
                published
            ):
                trans.name_transaction(transname, group="Zope2", priority=1)
                if hasattr(published, "context"):  # Plone
                    newrelic.agent.add_custom_parameter("id", getattr(published.context, "id", ""))
                    newrelic.agent.add_custom_parameter("absolute_url", getattr(published.context, "absolute_url", ""))
                elif hasattr(published, "id") and hasattr(published, "absolute_url"):  # Zope
                    newrelic.agent.add_custom_parameter("id", published.id)
                    newrelic.agent.add_custom_parameter("absolute_url", published.absolute_url())
                else:
                    # We don't know what it is .. so no custom parameters!
                    logger.debug("Published has no context nor an id/absolute_url. Skipping custom parameters")

                logger.debug("Transaction: {0}".format(transname))
            else:
                # For debugging purpose
                logger.debug(
                    "NO transaction? : {0}   Browser: {1}  Resource: {2} PageTemplate: {3}".format(
                        transname,
                        IBrowserView.providedBy(published),
                        IResource.providedBy(published),
                        IPageTemplate.providedBy(published),
                    )
                )

    except Exception, e:
        # Log it and carry on.
        logger.exception(e)
 def get(self, name, default=_marker):
     value = super( SkinDirectory, self ).get( name, None)
     if value is not None:
         return value
     
     wrapper = RequestWrapper( self.request )
     
     # lookup through the layer stack to find other directory
     # resources that might contain the requested resource.
     for layer in self.layers:
         interface.directlyProvides( wrapper, layer )
         resource_dir = component.queryAdapter(wrapper, name=self.__name__)
         if not ( IResource.providedBy( resource_dir ) \
             and IBrowserPublisher.providedBy( resource_dir ) ):
             continue
         resource = resource_dir.get( name )
         if resource is not None:
             return resource
     raise NotFound( name )
Exemple #6
0
    def get(self, name, default=_marker):
        value = super(SkinDirectory, self).get(name, None)
        if value is not None:
            return value

        wrapper = RequestWrapper(self.request)

        # lookup through the layer stack to find other directory
        # resources that might contain the requested resource.
        for layer in self.layers:
            interface.directlyProvides(wrapper, layer)
            resource_dir = component.queryAdapter(wrapper, name=self.__name__)
            if not ( IResource.providedBy( resource_dir ) \
                and IBrowserPublisher.providedBy( resource_dir ) ):
                continue
            resource = resource_dir.get(name)
            if resource is not None:
                return resource
        raise NotFound(name)
Exemple #7
0
    def transform(self, result):
        result = self.parseTree(result)
        if result is None:
            return None
        root = result.tree.getroot()
        url = urlparse(self.request.URL)
        try:
            token = createToken()
        except ComponentLookupError:
            context = self.getContext()
            if IApplication.providedBy(context) or \
                    IResource.providedBy(context):
                # skip here, utility not installed yet on zope root
                return
            raise

        for form in root.cssselect('form'):
            # XXX should we only do POST? If we're logged in and
            # it's an internal form, I'm inclined to say no...
            #method = form.attrib.get('method', 'GET').lower()
            #if method != 'post':
            #    continue

            # some get forms we definitely do not want to protect.
            # for now, we know search we do not want to protect
            method = form.attrib.get('method', 'GET').lower()
            action = form.attrib.get('action', '').strip()
            if method == 'get' and '@@search' in action:
                continue
            action = form.attrib.get('action', '').strip()
            if not self.isActionInSite(action, url):
                continue
            # check if the token is already on the form..
            hidden = form.cssselect('[name="_authenticator"]')
            if len(hidden) == 0:
                hidden = etree.Element("input")
                hidden.attrib['name'] = '_authenticator'
                hidden.attrib['type'] = 'hidden'
                hidden.attrib['value'] = token
                form.append(hidden)

        return result
    def _render_obj(self, obj, new_req=None):
        """
        Render object to string.
        """
        if isinstance(obj, basestring):
            return obj
        if new_req is None:
            new_req = self.request

        try:
            if IResource.providedBy(obj):
                try:
                    f = open(obj.context.path)
                    result = f.read()
                    f.close()
                except AttributeError:
                    result = obj.context.data
                except IOError:
                    log.error("Couldn't open '%s' file with resource" % (obj.context.path))
                    return None

                return result

            if isinstance(obj, (BrowserView, FSPageTemplate, PythonScript)):
                try:
                    return obj()
                except NotFound:
                    log.error("Resource '%s' not found" % repr(obj))
                    return None
            if isinstance(obj, (FSFile, FSImage)):
                return self._render_obj(obj._readFile(None))

            if isinstance(obj, FSDTMLMethod):
                return self._render_obj(obj.read())

            mt = None
            try:
                mt = obj.aq_base.meta_type
            except AttributeError:
                pass

            if mt in self.file_types or isinstance(obj, (ImageField, OFSImage, Pdata, File)):
                return self._render_obj(obj.data)

            if PLONE_RESOURCE_INSTALLED and isinstance(obj, FilesystemFile):
                if not obj.request:
                    obj.request = new_req
                    return obj().read()

            if PLONE_APP_BLOB_INSTALLED and IBlobWrapper.providedBy(obj):
                return obj.data

            if IBaseObject.providedBy(obj) or isinstance(obj, PloneSite):
                def_page_id = obj.getDefaultPage()
                if def_page_id:
                    def_page = obj[def_page_id]
                    return self._render_obj(def_page)

                view_name = obj.getLayout()
                view = queryMultiAdapter((obj, new_req), name=view_name)
                if view_name == "language-switcher":
                    lang = new_req.get("LANGUAGE")
                    def_page = getattr(obj, lang, None)
                    if def_page:
                        return self._render_obj(def_page)
                if view:
                    try:
                        return view.context()
                    except (ContentProviderLookupError, TypeError):
                        pass

                view = obj.restrictedTraverse(view_name, None)
                if view:
                    try:
                        return view.context()
                    except (AttributeError, TypeError):
                        try:
                            return view()
                        except Exception, error:
                            log.warning("Unable to render view: '%s'! Error occurred: %s" % (view, error))
                else:
                    try:
                        return obj()
                    except AttributeError:
                        pass

        finally:
            pass

        log.warning("Not recognized object '%s'!" % repr(obj))
        return None