Esempio n. 1
0
 def item_panels(self):
     default_view = self.default_view
     html = default_view()
     if isinstance(html, six.text_type):
         html = html.encode('utf-8')
     serializer = getHTMLSerializer([html],
                                    pretty_print=False,
                                    encoding='utf-8')
     panels = dict((node.attrib['data-panel'], node)
                   for node in utils.panelXPath(serializer.tree))
     if panels:
         request = self.request.clone()
         request.URL = self.content_context.absolute_url() + '/'
         try:
             renderTiles(request, serializer.tree)
         except RuntimeError:  # maximum recursion depth exceeded
             return []
         clear = '<div style="clear: both;"></div>'
         return [
             ''.join([
                 serializer.serializer(child)
                 for child in node.getchildren()
             ]) for name, node in panels.items()
         ] + [clear]
     return []
Esempio n. 2
0
 def testRenderTiles(self):
     serializer = getHTMLSerializer([testLayout1])
     request = self.layer['request']
     tree = serializer.tree
     renderTiles(request, tree)
     result = serializer.serialize()
     self.assertIn('This is a demo tile with id tile2', result)
     self.assertIn('This is a demo tile with id tile3', result)
     self.assertIn('This is a demo tile with id tile4', result)
Esempio n. 3
0
 def testRenderTiles(self):
     serializer = getHTMLSerializer([testLayout1])
     request = self.layer['request']
     tree = serializer.tree
     renderTiles(request, tree)
     result = serializer.serialize()
     self.assertIn('This is a demo tile with id tile2', result)
     self.assertIn('This is a demo tile with id tile3', result)
     self.assertIn('This is a demo tile with id tile4', result)
Esempio n. 4
0
 def testRenderTilesError(self):
     serializer = getHTMLSerializer([testLayout2])
     request = self.layer['request']
     tree = serializer.tree
     renderTiles(request, tree)
     result = serializer.serialize()
     self.assertIn('This is a demo tile with id tile2', result)
     self.assertNotIn('This is a demo tile with id tile3', result)
     self.assertIn('There was an error while rendering this tile', result)
     self.assertIn('This is a demo tile with id tile4', result)
Esempio n. 5
0
 def testRenderTilesError(self):
     serializer = getHTMLSerializer([testLayout2])
     request = self.layer['request']
     tree = serializer.tree
     renderTiles(request, tree)
     result = serializer.serialize()
     self.assertIn('This is a demo tile with id tile2', result)
     self.assertNotIn('This is a demo tile with id tile3', result)
     self.assertIn('There was an error while rendering this tile', result)
     self.assertIn('This is a demo tile with id tile4', result)
Esempio n. 6
0
def find_broken(site):
    setup_site(site)
    catalog = site.portal_catalog

    broken = []
    good_urls = []

    req = getRequest()
    for brain in catalog(object_provides=ILayoutAware.__identifier__):
        ob = brain.getObject()
        layout = getLayout(ob)
        dom = getHTMLSerializer(layout)
        tiles.renderTiles(req, dom.tree, ob.absolute_url() + '/layout_view')
        root = dom.tree.getroot()
        for anchor in root.cssselect('a'):
            if not anchor.attrib.get('href'):
                continue
            url = anchor.attrib['href']
            if url[0] == '#' or url.startswith('data:') or url.startswith(
                    'mailto:'):
                continue
            if url in good_urls:
                continue

            if find_url(ob, url):
                good_urls.append(url)
            else:
                try:
                    text = unidecode(anchor.text_content())
                except:
                    text = ''
                result = '{} linking to broken -> {}({})'.format(
                    brain.getPath(), url, text)
                broken.append(result)
                print(result)

        for img in root.cssselect('img'):
            if not img.attrib.get('src'):
                continue
            url = img.attrib['src']
            if url[0] == '#' or url.startswith('data:'):
                continue
            if find_url(ob, url):
                good_urls.append(url)
            else:
                result = '{} linking to broken image -> {}'.format(
                    brain.getPath(), url)
                broken.append(result)
                print(result)

    filename = 'broken-links-{}.txt'
    fi = open(filename, 'w')
    fi.write('\n'.join(broken))
    fi.close()
Esempio n. 7
0
    def get_field_data(self):
        from plone.dexterity.interfaces import IDexterityFTI
        from plone.behavior.interfaces import IBehaviorAssignable

        data = {}

        schema = getUtility(IDexterityFTI,
                            name=self.obj.portal_type).lookupSchema()
        for name, field in getFieldsInOrder(schema):
            data[name] = getattr(self.obj, name, None)

        behavior_assignable = IBehaviorAssignable(self.obj)
        for behavior in behavior_assignable.enumerateBehaviors():
            binst = behavior.interface(self.obj)
            bdata = {}
            for name, field in getFieldsInOrder(behavior.interface):
                bdata[name] = getattr(binst, name, None)
            data[behavior.interface.__identifier__] = bdata

        if ILayoutAware.providedBy(self.obj):
            from plone.tiles.data import ANNOTATIONS_KEY_PREFIX
            from plone.app.blocks.utils import getLayout
            from repoze.xmliter.utils import getHTMLSerializer
            from plone.app.blocks import tiles
            from plone.app.blocks import gridsystem
            from lxml.html import tostring
            tdata = {}
            annotations = IAnnotations(self.obj, {})
            for key in annotations.keys():
                if key.startswith(ANNOTATIONS_KEY_PREFIX):
                    adata = annotations[key]
                    tdata[key] = adata
            data['tile_data'] = tdata

            req = site.REQUEST
            layout = getLayout(self.obj)
            dom = getHTMLSerializer(layout)

            try:
                tiles.renderTiles(req,
                                  dom.tree,
                                  site=site,
                                  baseURL=self.obj.absolute_url() +
                                  '/layout_view')
            except TypeError:
                tiles.renderTiles(req,
                                  dom.tree,
                                  baseURL=self.obj.absolute_url() +
                                  '/layout_view')
            gridsystem.merge(req, dom.tree)

            data['rendered_layout'] = tostring(dom.tree)

        return data
Esempio n. 8
0
    def transformIterable(self, result, encoding):
        if not self.request.get('plone.app.blocks.enabled', False) or \
                not isinstance(result, XMLSerializer):
            return None

        result.tree = tiles.renderTiles(self.request, result.tree)
        return result
Esempio n. 9
0
def transformIterable(self, result, encoding):
    """
    Apply our customize transform that attempts to provide
    b/w compatibility with diazo if user still tries to use
    a diazo powered theme.
    """
    if self.request.response.getHeader('X-Theme-Applied'):
        return
    if not isinstance(result, XMLSerializer):
        return

    # Obtain settings. Do nothing if not found
    policy = theming_policy(self.request)
    settings = policy.getSettings()
    if settings is None:
        return None
    if not policy.isThemeEnabled():
        return None

    try:
        if isPloneTheme(settings):
            # XXX old style theme
            # manual render tiles, then do theme transform
            result.tree = tiles.renderTiles(self.request, result.tree)
            result = self._old_transformIterable(result, encoding)
            return result
    except AttributeError:
        pass

    DevelopmentMode = Globals.DevelopmentMode

    try:
        # if we are here, it means we are rendering the the
        # classic way and we need to do replacements.
        # check for #visual-portal-wrapper to make sure we need
        # transform this response
        # XXX WARNING: THIS IS NECESSARY
        wrapper = wrapper_xpath(result.tree)
        if len(wrapper) == 0:
            return None

        context = get_context_from_request(self.request)
        transform = getTransform(context, self.request)
        if transform is None:
            return None

        transformed = transform(self.request, result, context=context)
        if transformed is None:
            return None

        result = transformed
        if settings.doctype:
            result.doctype = settings.doctype
            if not result.doctype.endswith('\n'):
                result.doctype += '\n'
        return result
    except etree.LxmlError:
        if not (DevelopmentMode):
            raise
    return result
Esempio n. 10
0
    def render_content_core(self):
        try:
            layout = getLayout(self.context)
        except TypeError:
            return super(LayoutAwareItem, self).render_content_core()
        req = getRequest()
        filters = [f for _, f in getAdapters((self.context, req), IFilter)]
        layout = apply_filters(filters, layout)
        dom = getHTMLSerializer(layout)
        tiles.renderTiles(req, dom.tree,
                          self.context.absolute_url() + '/layout_view')
        gridsystem.merge(req, dom.tree)

        content = contentpanel_xpath(dom.tree)
        if len(content) > 0:
            return tostring(content[0])
        return ''
Esempio n. 11
0
 def item_panels(self):
     default_view = self.default_view
     html = default_view()
     if isinstance(html, unicode):
         html = html.encode('utf-8')
     serializer = getHTMLSerializer([html], pretty_print=False,
                                    encoding='utf-8')
     panels = dict(
         (node.attrib['data-panel'], node)
         for node in utils.panelXPath(serializer.tree)
     )
     if panels:
         request = self.request.clone()
         request.URL = self.content_context.absolute_url() + '/'
         try:
             renderTiles(request, serializer.tree)
         except RuntimeError:  # maximum recursion depth exceeded
             return []
         clear = '<div style="clear: both;"></div>'
         return [''.join([serializer.serializer(child)
                          for child in node.getchildren()])
                 for name, node in panels.items()] + [clear]
     return []
Esempio n. 12
0
    def __call__(self, request, result, context=None):
        if '++plone++' in request.ACTUAL_URL:
            return
        portal = api.portal.get()
        original_context = context
        if context is None or IResourceDirectory.providedBy(context):
            original_context = context = portal

        try:
            context_url = context.absolute_url()
        except AttributeError:
            # could be a form/browser class
            try:
                context = context.context
            except:
                context = aq_parent(context)
            context_url = context.absolute_url()

        if (not ISiteRoot.providedBy(context)
                and not IDexterityContent.providedBy(context)):
            context = aq_parent(context)
        portal_url = portal.absolute_url()

        raw = False
        if isinstance(result, basestring):
            raw = True
        else:
            self.rewrite(result, context.absolute_url() + '/')
            result = result.tree

        theme_base_url = '%s/++%s++%s/index.html' % (
            portal_url, THEME_RESOURCE_NAME, self.name)

        content = self.get_fill_content(result, raw)
        utils = getMultiAdapter((context, request), name='castle-utils')

        layout = self.get_layout(context, request=request)
        layout = layout(portal_url=portal_url,
                        site_url=portal_url,
                        context_url=context_url,
                        request=request,
                        context=context,
                        portal=portal,
                        site=portal,
                        theme_base_url=theme_base_url,
                        content=content,
                        anonymous=api.user.is_anonymous(),
                        debug=api.env.debug_mode(),
                        utils=utils)

        dom = getHTMLSerializer([layout])
        self.rewrite(dom, theme_base_url)
        if not raw:
            # old style things...
            self.bbb(dom.tree, result)

        dom.tree = tiles.renderTiles(request, dom.tree)

        self.add_body_classes(original_context, context, request, dom.tree,
                              result, raw)

        self.add_included_resources(dom.tree, portal, request)
        self.dynamic_grid(dom.tree)
        # #
        # dom.tree = tiles.renderTiles(request, dom.tree)

        return dom
Esempio n. 13
0
    def staticpages_single(self):
        """saticpages/single View

        Context: INavigationRoot content

        Get parameter:

            * lang: language folder, multiple allowed to set fallback, required
            * path: path to item relative to the lang folder

        Traverse to the content under lang/path and return the rendered html
        of the default view.

        @return: JSON dictionary with html representation

        """
        item = None
        view = None
        link = None
        response_data = {}
        lang = u''
        data = self._get_data()
        if data['langs'] == [] or data['path'] == '':
            raise KeyError
        if data['path'].startswith("author/")\
                or data['path'].startswith("sitemap"):
            view = self.context.restrictedTraverse(data['path'])
        else:
            for lang in data['langs']:
                try:
                    item = self.context\
                        .restrictedTraverse("/".join([lang, data['path']]))
                    lang = lang
                    if item is not None:
                        break
                except (KeyError, TraversalError):
                    pass
            if item is None:
                raise KeyError
        if ILink.providedBy(item):
            link = item
            item = None
        response_data['lang'] = lang
        response_data['private'] = False

        html = ''
        tree = None
        redirect_url = u''
        if link:
            portal_state = link.restrictedTraverse("@@plone_portal_state")
            if "${navigation_root_url}" in link.remoteUrl:
                navigation_root_url = portal_state.navigation_root_url()
                redirect_url = link.remoteUrl.replace("${navigation_root_url}",
                                                      navigation_root_url)
            elif "${portal_url}" in link.remoteUrl:
                portal_url = portal_state.portal_url()
                redirect_url = link.remoteUrl.replace("${portal_url}",
                                                      portal_url)
            else:
                redirect_url = link.remoteUrl
        if view:
            html = view()
        if item:
            default_page_view = getMultiAdapter((item, self.request),
                                                name="default_page")
            default_page = default_page_view.getDefaultPage()
            item = item[default_page] if default_page else item

            viewname = item.getLayout() or item.getDefaultLayout()
            view = None
            try:
                view = getMultiAdapter((item, self.request), name=viewname)
            except ComponentLookupError:
                viewname = 'view'
                view = getMultiAdapter((item, self.request), name=viewname)
            view.request.URL = item.absolute_url() + "/" + viewname
            view.request.response.setHeader('Content-Type', 'text/html')
            view.request['plone.app.blocks.enabled'] = True
            html_no_tiles = view()
            parser = etree.HTMLParser()
            tree = etree.parse(StringIO(html_no_tiles), parser)
            renderTiles(view.request, tree)
            html = etree.tostring(tree.getroot(), method="html",
                                  pretty_print=True)

        soup = BeautifulSoup(html)

        css_classes_soup = soup.body['class'] if soup.body else None
        response_data['css_classes'] = css_classes_soup\
            if css_classes_soup else []
        column_r_soup = soup.find(id='portal-column-two')
        response_data['column_right'] = column_r_soup.encode('utf-8').strip()\
            if column_r_soup else u''
        nav_soup = soup.find(id='portal-globalnav')
        response_data['nav'] = nav_soup.encode('utf-8').strip()\
            if nav_soup else u''

        content_soup = soup.find(id="content")
        remove_ids = ['plone-document-byline']
        for id_ in remove_ids:
            tag = content_soup.find(id=id_) if content_soup else None
            if tag:
                tag.extract()
        remove_tags = ['script']
        for tag in remove_tags:
            tags_ = content_soup.find_all(tag) if content_soup else []
            for tag_ in tags_:
                tag_.extract()
        title_soup = content_soup.find(class_='documentFirstHeading')\
            if content_soup else None
        response_data['title'] = title_soup.extract().get_text().strip()\
            if title_soup else u''
        descr_soup = content_soup.find(class_='documentDescription')\
            if content_soup else None
        response_data['description'] = descr_soup.extract().get_text().strip()\
            if descr_soup else u''
        response_data['body'] = content_soup.encode("utf-8").strip()\
            if content_soup else u''
        response_data['redirect_url'] = redirect_url

        return response_data