Added "oid_to_href" HTML renderer to convert "oid://" internal links to URLs
authorThierry Florac <thierry.florac@onf.fr>
Wed, 04 Jul 2018 09:03:53 +0200
changeset 797 73ced1817195
parent 796 2ef3bacda742
child 798 754dcbb0ede9
Added "oid_to_href" HTML renderer to convert "oid://" internal links to URLs
src/pyams_content/features/html/__init__.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_content/features/html/__init__.py	Wed Jul 04 09:03:53 2018 +0200
@@ -0,0 +1,53 @@
+#
+# Copyright (c) 2008-2018 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+from pyquery import PyQuery
+
+# import interfaces
+from pyams_sequence.interfaces import ISequentialIntIds
+from pyams_utils.interfaces.text import IHTMLRenderer
+from pyams_utils.interfaces.url import DISPLAY_CONTEXT
+from pyams_workflow.interfaces import IWorkflowPublicationInfo
+from pyramid.interfaces import IRequest
+
+# import packages
+from pyams_sequence.utility import get_reference_target
+from pyams_utils.adapter import adapter_config, ContextRequestAdapter
+from pyams_utils.registry import get_utility
+from pyams_utils.url import relative_url
+
+
+@adapter_config(name='oid_to_href', context=(str, IRequest), provides=IHTMLRenderer)
+class OIDHTMLRenderer(ContextRequestAdapter):
+    """An HTML renderer converting all "oid://" URLs to internal relative links"""
+
+    def render(self):
+        context = self.request.annotations.get(DISPLAY_CONTEXT, self.request.context)
+        html = PyQuery('<div>{0}</div>'.format(self.context))
+        sequence = get_utility(ISequentialIntIds)
+        for link in html('a[href]'):
+            href = link.attrib['href']
+            if href.startswith('oid://'):
+                oid = sequence.get_full_oid(href.split('//', 1)[1])
+                target = get_reference_target(oid)
+                if target is not None:
+                    publication_info = IWorkflowPublicationInfo(target, None)
+                    if (publication_info is not None) and publication_info.is_visible(self.request):
+                        link.attrib['href'] = relative_url(target, self.request, context)
+                        continue
+                # invalid link => remove href!
+                del link.attrib['href']
+        return html.html()