From 748a6b2747bfd184d96915415ffd772cad540f42 Mon Sep 17 00:00:00 2001
From: Yoshinori Okuji <yo@nexedi.com>
Date: Thu, 12 Jun 2008 15:43:24 +0000
Subject: [PATCH] Add asSubjectText into Document and TextDocument. Allow
 callers to pass parameters to a substitution method.

git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk@21557 20353a03-c40f-0410-a6d1-a30d3c3de9de
---
 product/ERP5/Document/Document.py     | 34 +++++++++++----
 product/ERP5/Document/Image.py        |  2 +-
 product/ERP5/Document/TextDocument.py | 63 ++++++++++++++++++---------
 3 files changed, 69 insertions(+), 30 deletions(-)

diff --git a/product/ERP5/Document/Document.py b/product/ERP5/Document/Document.py
index f4403703c9..faa25ef323 100644
--- a/product/ERP5/Document/Document.py
+++ b/product/ERP5/Document/Document.py
@@ -1178,16 +1178,30 @@ class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, Sna
     format, data = self.convert(format)
     return len(data)
 
+  security.declareProtected(Permissions.View, 'asSubjectText')
+  def asSubjectText(self, **kw):
+    """
+      Converts the subject of the document to a textual representation.
+    """
+    subject = self.getSubject()
+    if not subject:
+      # XXX not sure if this fallback is a good idea.
+      subject = self.getTitle()
+    if subject is None:
+      subject = ''
+    return str(subject)
+
   security.declareProtected(Permissions.View, 'asText')
-  def asText(self):
+  def asText(self, **kw):
     """
       Converts the content of the document to a textual representation.
     """
-    mime, data = self.convert(format='txt')
+    kw['format'] = 'txt'
+    mime, data = self.convert(**kw)
     return str(data)
 
   security.declareProtected(Permissions.View, 'asEntireHTML')
-  def asEntireHTML(self):
+  def asEntireHTML(self, **kw):
     """
       Returns a complete HTML representation of the document
       (with body tags, etc.). Adds if necessary a base
@@ -1196,7 +1210,7 @@ class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, Sna
 
       Actual conversion is delegated to _asHTML
     """
-    html = self._asHTML()
+    html = self._asHTML(**kw)
     if self.getUrlString():
       # If a URL is defined, add the base tag
       # if base is defined yet.
@@ -1210,7 +1224,7 @@ class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, Sna
     return html
 
   security.declarePrivate('_asHTML')
-  def _asHTML(self):
+  def _asHTML(self, **kw):
     """
       A private method which converts to HTML. This method
       is the one to override in subclasses.
@@ -1218,13 +1232,15 @@ class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, Sna
     if not self.hasBaseData():
       raise ConversionError('This document has not been processed yet.')
     if self.hasConversion(format='base-html'):
+      # FIXME: no substitution may occur in this case.
       mime, data = self.getConversion(format='base-html')
       return data
-    mime, html = self.convert(format='html')
+    kw['format'] = 'html'
+    mime, html = self.convert(**kw)
     return html
 
   security.declareProtected(Permissions.View, 'asStrippedHTML')
-  def asStrippedHTML(self):
+  def asStrippedHTML(self, **kw):
     """
       Returns a stripped HTML representation of the document
       (without html and body tags, etc.) which can be used to inline
@@ -1233,9 +1249,11 @@ class Document(PermanentURLMixIn, XMLObject, UrlMixIn, ConversionCacheMixin, Sna
     if not self.hasBaseData():
       return ''
     if self.hasConversion(format='stripped-html'): # XXX this is redundant since we never set it
+      # FIXME: no substitution may occur in this case.
       mime, data = self.getConversion(format='stripped-html')
       return data
-    mime, html = self.convert(format='html')
+    kw['format'] = 'html'
+    mime, html = self.convert(**kw)
     body_list = re.findall(self.body_parser, str(html))
     if len(body_list):
       stripped_html = body_list[0]
diff --git a/product/ERP5/Document/Image.py b/product/ERP5/Document/Image.py
index fd16aaf78c..73b6677458 100644
--- a/product/ERP5/Document/Image.py
+++ b/product/ERP5/Document/Image.py
@@ -294,7 +294,7 @@ class Image(File, OFSImage):
 
   # Conversion API
   security.declareProtected(Permissions.ModifyPortalContent, 'convert')
-  def convert(self, format, display=None, quality=75, resolution=None, frame=None):
+  def convert(self, format, display=None, quality=75, resolution=None, frame=None, **kw):
     """
     Implementation of conversion for PDF files
     """
diff --git a/product/ERP5/Document/TextDocument.py b/product/ERP5/Document/TextDocument.py
index fc00d04446..3b6ad1702a 100644
--- a/product/ERP5/Document/TextDocument.py
+++ b/product/ERP5/Document/TextDocument.py
@@ -151,8 +151,46 @@ class TextDocument(Document, TextContent):
       RESPONSE.setHeader('Accept-Ranges', 'bytes')
       return data
 
+    def _substituteTextContent(self, text, **kw):
+      # If a method for string substitutions of the text content, perform it.
+      # Decode everything into unicode before the substitutions, in order to
+      # avoid encoding errors.
+      method_id = self.getTextContentSubstitutionMappingMethodId()
+      if method_id:
+        mapping = guarded_getattr(self, method_id)(**kw)
+
+        is_str = isinstance(text, str)
+        if is_str:
+          text = text.decode('utf-8')
+
+        unicode_mapping = {}
+        for k, v in mapping.iteritems():
+          if isinstance(v, str):
+            v = v.decode('utf-8')
+          elif not isinstance(v, unicode):
+            v = str(v).decode('utf-8')
+          unicode_mapping[k] = v
+
+        text = Template(text).substitute(unicode_mapping)
+
+        # If the original was a str, convert it back to str.
+        if is_str:
+          text = text.encode('utf-8')
+
+      return text
+
+    security.declareProtected(Permissions.View, 'asSubjectText')
+    def asSubjectText(self, substitution_method_parameter_dict=None, **kw):
+      """
+        Converts the subject of the document to a textual representation.
+      """
+      subject = TextDocument.inheritedAttribute('asSubjectText')(self, **kw)
+      if substitution_method_parameter_dict is None:
+        substitution_method_parameter_dict = {}
+      return self._substituteTextContent(subject, **substitution_method_parameter_dict)
+
     security.declareProtected(Permissions.View, 'convert')
-    def convert(self, format, **kw):
+    def convert(self, format, substitution_method_parameter_dict=None, **kw):
       """
         Convert text using portal_transforms or oood
       """
@@ -179,26 +217,9 @@ class TextDocument(Document, TextContent):
                 'portal_transforms failed to convert to %s: %r' % (mime_type, self))
             result = ''
 
-        # If a method for string substitutions of the text content, perform it.
-        # Decode everything into unicode before the substitutions, in order to
-        # avoid encoding errors.
-        method_id = self.getTextContentSubstitutionMappingMethodId()
-        if method_id:
-          mapping = guarded_getattr(self, method_id)()
-
-          if isinstance(result, str):
-            result = result.decode('utf-8')
-
-          unicode_mapping = {}
-          for k, v in mapping.iteritems():
-            if isinstance(v, str):
-              v = v.decode('utf-8')
-            elif not isinstance(v, unicode):
-              v = str(v).decode('utf-8')
-            unicode_mapping[k] = v
-
-          result = Template(result).substitute(unicode_mapping)
-          # XXX is it better to convert back to str?
+        if substitution_method_parameter_dict is None:
+          substitution_method_parameter_dict = {}
+        result = self._substituteText(result, **substitution_method_parameter_dict)
 
         return mime_type, result
       else:
-- 
2.30.9