PDFTemplate.py 9.57 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from Products.CMFCore.utils import getToolByName
from Products.CMFCore.FSPageTemplate import FSPageTemplate
from Products.CMFCore.DirectoryView import registerFileExtension, registerMetaType
from Products.Formulator.Form import BasicForm
from Products.Formulator.Form import fields
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
35
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37 38 39 40
from Products.ERP5Type import PropertySheet

from urllib import quote
from Globals import InitializeClass, PersistentMapping, DTMLFile, get_request
from AccessControl import Unauthorized, getSecurityManager, ClassSecurityInfo
41
import urllib2
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43 44 45 46

from Products.ERP5Type.Utils import UpperCase

from zLOG import LOG

47 48 49 50 51 52 53
try:
    from webdav.Lockable import ResourceLockedError
    from webdav.WriteLockInterface import WriteLockInterface
    SUPPORTS_WEBDAV_LOCKS = 1
except ImportError:
    SUPPORTS_WEBDAV_LOCKS = 0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
# Constructors
manage_addPDFTemplate = DTMLFile("dtml/PDFTemplate_add", globals())

def addPDFTemplate(self, id, title="", REQUEST=None):
    """Add form to folder.
    id     -- the id of the new form to add
    title  -- the title of the form to add
    Result -- empty string
    """
    # add actual object
    id = self._setObject(id, PDFTemplate(id, title))
    # respond to the add_and_edit button if necessary
    add_and_edit(self, id, REQUEST)
    return ''

def add_and_edit(self, id, REQUEST):
    """Helper method to point to the object's management screen if
    'Add and Edit' button is pressed.
    id -- id of the object we just added
    """
    if REQUEST is None:
        return
    try:
        u = self.DestinationURL()
    except:
        u = REQUEST['URL1']
    if REQUEST['submit'] == " Add and Edit ":
        u = "%s/%s" % (u, quote(id))
    REQUEST.RESPONSE.redirect(u+'/manage_main')


class PDFTemplate(ZopePageTemplate):
    """
        A Formulator form with a built-in rendering parameter based
        on page templates or DTML.
    """
    meta_type = "ERP5 PDF Template"
    icon = "www/PDF.png"

    # Declarative Security
    security = ClassSecurityInfo()

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.SimpleItem)

    # Constructors
    constructors =   (manage_addPDFTemplate, addPDFTemplate)

    # Default Attributes
    pdf_stylesheet = 'default_pdf_template'
    content_type = 'application/pdf'

    # Management interface
    manage_options =  ( ZopePageTemplate.manage_options +
        (
          {'label':'Stylesheet Setting', 'action':'formSettings',
           'help':('ERPForm', 'pdfStylesheet.txt')},
        )
      )

    security.declareProtected('View management screens', 'formSettings')
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    formSettings = PageTemplateFile('www/formSettings', globals(), __name__='formSettings')
    formSettings._owner = None

    security.declareProtected('Change Page Templates', 'doSettings')
    def doSettings(self, REQUEST, title, pdf_stylesheet):
      """
        Change title and pdf_stylesheet.
      """
      if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
        raise ResourceLockedError, "File is locked via WebDAV"
      self.pdf_stylesheet = pdf_stylesheet
      self.pt_setTitle(title)
      #REQUEST.set('text', self.read()) # May not equal 'text'!
      message = "Saved changes."
      if getattr(self, '_v_warnings', None):
        message = ("<strong>Warning:</strong> <i>%s</i>"
                  % '<br>'.join(self._v_warnings))
      return self.formSettings(manage_tabs_message=message)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
134 135

    # Proxy method to PageTemplate
136 137 138 139 140 141 142 143 144 145 146 147
    def pt_render(self, source=0, extra_context={}):
      doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context)
      
      # Unmarshall arguments to __call__ API
      args = extra_context.get('options', None)      
      kwargs = extra_context.copy()
      if kwargs.has_key('options'): del kwargs['options']
      if kwargs.has_key('context'): del kwargs['context']

      batch_mode = extra_context.get('batch_mode', 0)

      request = extra_context.get('REQUEST', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
148 149 150 151 152 153 154 155
      if not request:
        request = get_request()

      if request.get('debug',0):
        return doc_xml

      report_tool = getToolByName(self, 'portal_report')
      pdf = report_tool.renderPDF(self.pdf_stylesheet, doc_xml, context=self.pt_getContext()['here'], *args, **kwargs)
156
      if request and not batch_mode:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        request.RESPONSE.setHeader('Content-Type','application/pdf')
        request.RESPONSE.setHeader('Content-Length',len(pdf))
        request.RESPONSE.setHeader('Content-Disposition','inline;filename=%s.pdf' % self.id)

      return pdf

    #def _exec(self, bound_names, args, kw):
    #    pt = getattr(self,self.pt)
    #    return pt._exec(self, bound_names, args, kw)

InitializeClass(PDFTemplate)

class FSPDFTemplate(FSPageTemplate, PDFTemplate):

    meta_type = "ERP5 Filesystem PDF Template"
    icon = "www/PDF.png"

    def __call__(self, *args, **kwargs):
      return PDFTemplate.__call__(self, *args, **kwargs)

InitializeClass(FSPDFTemplate)

179
registerFileExtension('pdft', FSPDFTemplate)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
180 181 182
registerMetaType('ERP5 PDF Template', FSPDFTemplate)

# Dynamic Patch
183 184 185 186 187 188 189 190
from Products.CMFReportTool.ReportTool import ReportTool
try:
  from Products.CMFReportTool.ReportTool import ZODBResourceHandler
  HAS_ZODB_RESOURCE_HANDLER=1
except ImportError:
  from Products.CMFReportTool.ReportTool import ZODBHandler, ResourceHandler
  HAS_ZODB_RESOURCE_HANDLER=0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
191 192 193 194 195 196 197
from Products.CMFReportTool.RenderPDF.Parser import TemplateParser,DocumentParser
from Products.PageTemplates.Expressions import restrictedTraverse
from StringIO import StringIO
import xml.dom.minidom
import urllib,os.path


198 199 200 201 202 203 204 205 206 207
if HAS_ZODB_RESOURCE_HANDLER:
  class ERP5ResourceHandler(ZODBResourceHandler):
    ''' Wrapper for ZODB Resources and files'''

    def handleZODB(self,path):

      path = path.split('/')
      obj = restrictedTraverse(self.context,path,getSecurityManager())

      # check type and e.g. call object if script ...
208 209 210 211 212
      if callable(obj):
        try:
          obj = obj()
        except:
          pass
213 214 215

      ## for OFS.Image-like objects
      if hasattr(obj,'_original'):
216
        obj = obj._original._data()
217 218 219 220 221 222 223 224 225 226 227 228
      elif hasattr(obj,'_data'):
        obj = obj._data
      elif hasattr(obj,'data'):
        obj = obj.data

      return StringIO(str(obj))
else:
  class ERP5ResourceHandler(ResourceHandler):
    ''' Wrapper for ZODB Resources and files'''
    def __init__(self, context=None, resource_path=None):
        zodbhandler = ERP5ZODBHandler(context)
        self.opener = urllib2.build_opener(zodbhandler)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
229

230 231 232 233 234
  class ERP5ZODBHandler(ZODBHandler):
    def zodb_open(self, req):
      path = req.get_selector()
      path = path.split('/')
      obj = restrictedTraverse(self.context,path,getSecurityManager())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
235

236
      # check type and e.g. call object if script ...
237 238 239 240 241
      if callable(obj):
        try:
          obj = obj()
        except:
          pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
242

243 244
      ## for OFS.Image-like objects
      if hasattr(obj,'_original'):
245
        obj = obj._original._data()
246 247 248 249
      elif hasattr(obj,'_data'):
        obj = obj._data
      elif hasattr(obj,'data'):
        obj = obj.data
Jean-Paul Smets's avatar
Jean-Paul Smets committed
250

251
      return StringIO(str(obj))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
252 253 254 255 256 257 258 259 260 261



class ERP5ReportTool(ReportTool):

  def renderPDF(self, templatename, document_xml, *args, **kwargs):
    """
      Render document using template
    """

262 263 264 265
    context = kwargs.get('context',None)
    if context is None:
      context = self

Jean-Paul Smets's avatar
Jean-Paul Smets committed
266
    encoding = kwargs.get('encoding') or 'iso-8859-1'
267
    rhandler = ERP5ResourceHandler(context, getattr(self, 'resourcePath', None))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
268 269 270 271 272

    #template = self._v_templatecache.get(templatename,None)
    #if not template:
    if 1:
      template_xml = getattr(context, templatename)(*args, **kwargs)
273 274 275
      if type(template_xml) is not type(u'a'):
        template_xml = unicode(template_xml,encoding=encoding)
      template_xml = template_xml.encode('utf-8')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
276 277
      template_dom = xml.dom.minidom.parseString(template_xml)
      template = TemplateParser(template_dom,encoding,resourceHandler=rhandler)()
278
      #self._v_templatecache[templatename] = template
Jean-Paul Smets's avatar
Jean-Paul Smets committed
279 280 281 282 283 284 285 286 287 288 289

    document_dom = xml.dom.minidom.parseString(document_xml)
    document = DocumentParser(document_dom,encoding,resourceHandler=rhandler)

    buf = StringIO()
    document(template,buf)
    buf.seek(0)
    return buf.read()


ReportTool.renderPDF = ERP5ReportTool.renderPDF