PDFForm.py 22.8 KB
Newer Older
1 2 3 4 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
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jerome PERRIN <jerome@nexedi.com>
#
# 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 OFS.Image import File
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
31
from Products.ERP5Type import PropertySheet, Permissions
32 33 34 35 36 37 38 39
from Products.PageTemplates.Expressions import getEngine
from Products.PageTemplates.TALES import SafeMapping

from urllib import quote
from Globals import InitializeClass, PersistentMapping, DTMLFile
from AccessControl import ClassSecurityInfo
from AccessControl.SecurityInfo import allow_class

40
from zLOG import LOG, PROBLEM, WARNING
41

42 43 44 45 46
import types
import popen2
import os
import urllib
import cStringIO
47 48 49
from tempfile import mktemp

try:
Jérome Perrin's avatar
Jérome Perrin committed
50 51
  from webdav.Lockable import ResourceLockedError
  SUPPORTS_WEBDAV_LOCKS = 1
52
except ImportError:
Jérome Perrin's avatar
Jérome Perrin committed
53
  SUPPORTS_WEBDAV_LOCKS = 0
54

Jérome Perrin's avatar
Jérome Perrin committed
55 56 57 58
# Programs linked against mandriva libgcj v 3.4.0 ave a strange issue that make
# them impossible to popen within zope.  That's why we do not use the 'real'
# pdftk but a replacement program, pdftk-emulation available from nexedi's RPM
# repositories.
59
PDFTK_EXECUTABLE = "pdftk-emulation"
60

61 62 63 64 65 66
# With python >= 2.4 and zope >= 2.7.8, pdftk-emulation is no longer needed
import sys, App.version_txt
python_version = sys.version.split(' ')[0].split('.')
python_version = int(python_version[0]) * 100 +\
                 int(python_version[1])
zope_version = App.version_txt.getZopeVersion()
Kevin Deldycke's avatar
Kevin Deldycke committed
67 68 69
zope_version = int(zope_version[0]) * 100 * 100 +\
               int(zope_version[1]) * 100 +\
               int(zope_version[2])
70 71 72 73
if python_version >= 204 and zope_version >= 20708:
  PDFTK_EXECUTABLE = "pdftk"


Jérome Perrin's avatar
Jérome Perrin committed
74 75
class PDFTk:
  """A class to wrapp calls to pdftk executable, found at
Jérome Perrin's avatar
Jérome Perrin committed
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
    http://www.accesspdf.com/pdftk/
  """
  def catPages(self, pdfFile, cat_option) :
    """ limit to a specific range of pages, like pdftk's cat option"""
    return self._getOutput(
      PDFTK_EXECUTABLE+
      " - cat %s output - "%cat_option, pdfFile)

  def dumpDataFields(self, pdfFile) :
    """ returns the output of pdftk dump_data_fields as dict """
    return self._parseDumpDataFields(self.dumpDataFieldsTxt(pdfFile))

  def fillFormWithDict(self, pdfFile, values) :
    """ fill the form with values in """
    return self.fillFormWithFDF(pdfFile, self._createFdf(values))

  def fillFormWithFDF(self, pdfFile, fdfFile) :
    """ fill the form of pdfFile with the FDF data fdfFile """
    pdfFormFileName = mktemp(suffix=".pdf")
    fdfFormFileName = mktemp(suffix=".fdf")

    if hasattr(pdfFile, "read") :
      pdfFile = pdfFile.read()
    tmpPdfFile = open(pdfFormFileName, "w")
    tmpPdfFile.write(pdfFile)
    tmpPdfFile.close()

    if hasattr(fdfFile, "read") :
      fdfFile = fdfFile.read()
    tmpFdfFile = open(fdfFormFileName, "w")
    tmpFdfFile.write(fdfFile)
    tmpFdfFile.close()
108

Jérome Perrin's avatar
Jérome Perrin committed
109 110
    out = self._getOutput(
          PDFTK_EXECUTABLE+
111
          " %s fill_form %s output - flatten "%(
Jérome Perrin's avatar
Jérome Perrin committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
          pdfFormFileName, fdfFormFileName))
    os.remove(fdfFormFileName)
    os.remove(pdfFormFileName)
    return out

  def dumpDataFieldsTxt(self, pdfFile) :
    """ returns the output of pdftk dump_data_fields as text,
      pdf file is either the file object or its content"""
    return self._getOutput(
            PDFTK_EXECUTABLE+" - dump_data_fields", pdfFile,
            assert_not_empty=0)

  def _parseDumpDataFields(self, data_fields_dump) :
    """ parses the output of pdftk X.pdf dump_data_fields and
        returns a sequence of dicts [{key = value}] """
    fields = []
    for txtfield in data_fields_dump.split("---") :
      field = {}
      for line in txtfield.splitlines() :
        if line.strip() == "" :
          continue
        splits = line.split(":", 1)
        if len(splits) == 2 :
          field[splits[0]] = splits[1].strip()
      if field != {} :
        fields += [field]
    return fields

  def _getOutput(self, command, input=None, assert_not_empty=1) :
    """ returns the output of command with sending input through command's
    input stream (if input parameter is given) """
    stdout, stdin = popen2.popen2(command)
    if input:
      if hasattr(input, "read") :
        input = input.read()
      try :
        stdin.write(input)
      except IOError, e:
        raise IOError, str(e) + " ( make sure "\
          "%s exists and is in your $PATH )"%PDFTK_EXECUTABLE
    stdin.close()
    ret = stdout.read()
    stdout.close()
    if assert_not_empty and len(ret) == 0 :
      raise IOError, "Got no output from external program, make sure"\
                   " %s exists and is in your $PATH"%PDFTK_EXECUTABLE
    return ret

  def _escapeString(self, value) :
    if value is None :
      return ""
    string = str(value)
    escaped  = ''
    for c in string :
      if (ord(c) == 0x28 or # open paren
          ord(c) == 0x29 or # close paren
          ord(c) == 0x5c):  # backslash
        escaped += '\\' + c
      elif ord(c) < 32 or 126 < ord(c):
        escaped += "\\%03o" % ord(c)
      else:
        escaped += c
    return escaped

  def _createFdf(self, values, pdfFormUrl=None) :
    """ create an fdf document with the dict values """
    fdf = "%FDF-1.2\x0d%\xe2\xe3\xcf\xd3\x0d\x0a"
    fdf += "1 0 obj\x0d<< \x0d/FDF << /Fields [ "
    for key, value in values.items():
181
      fdf += "<< /T (%s) /V (%s) /ClrF 2 /ClrFf 1 >> \x0d" % (
Jérome Perrin's avatar
Jérome Perrin committed
182 183 184 185 186 187 188 189 190 191 192 193
           self._escapeString(key),
           self._escapeString(value))

    fdf += "] \x0d"

    # the PDF form filename or URL, if any
    if pdfFormUrl not in ("", None) :
      fdf += "/F ("+self._escapeString(pdfFormUrl)+") \x0d"

    fdf += ">> \x0d>> \x0dendobj\x0d";
    fdf += "trailer\x0d<<\x0d/Root 1 0 R \x0d\x0d>>\x0d%%EOF\x0d\x0a"
    return fdf
194

Jérome Perrin's avatar
Jérome Perrin committed
195

196 197 198
# Constructors
manage_addPDFForm = DTMLFile("dtml/PDFForm_add", globals())
def addPDFForm(self, id, title="", pdf_file=None,  REQUEST=None):
Jérome Perrin's avatar
Jérome Perrin committed
199 200 201
  """ Add a pdf form to folder. """
  # add actual object
  id = self._setObject(id, PDFForm(id, title, pdf_file))
202

Jérome Perrin's avatar
Jérome Perrin committed
203 204 205
  # upload content
  if pdf_file:
    self._getOb(id).manage_upload(pdf_file)
Jérome Perrin's avatar
Jérome Perrin committed
206
    self._getOb(id).content_type = "application/pdf"
207

Jérome Perrin's avatar
Jérome Perrin committed
208 209 210 211 212
  if REQUEST :
    u = REQUEST['URL1']
    if REQUEST['submit'] == " Add and Edit ":
      u = "%s/%s" % (u, quote(id))
    REQUEST.RESPONSE.redirect(u+'/manage_main')
213

Jérome Perrin's avatar
Jérome Perrin committed
214

215
class CalculatedValues :
Jérome Perrin's avatar
Jérome Perrin committed
216
  """This class holds a reference to calculated values, for use in TALES,
Jérome Perrin's avatar
Jérome Perrin committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
  because in PDF Form filling, there is lots of references to others cell
  values (sums ...). This class will be in TALES context under the key 'cell'

  It will make possible the use of TALES expressions like :
    cell/a95
    python: cell['a1'] + cell['a2']

  """
  security = ClassSecurityInfo()
  def __init__(self, values, key, not_founds) :
    """ 'values' are a dict of already calculated values
    'key' is the key we are evaluating
    'not_founds' is the list in which we will put not found values  """
    self.__values      = values
    self.__key         = key
    self.__not_founds  = not_founds
  def __getitem__(self, attr) :
    if not self.__values.has_key(attr) :
      self.__not_founds.append(attr)
      return 0 # We do not return None, so that cell['a1'] + cell['a2']
      # doesn't complain that NoneType doesn't support + when a1 not found
    return self.__values[attr]
  __getattr__ = __getitem__
240 241
allow_class(CalculatedValues)

Jérome Perrin's avatar
Jérome Perrin committed
242 243 244 245 246

class CircularReferencyError(ValueError):
  """A circular reference is found trying to evaluate cell TALES."""


247
class EmptyERP5PdfFormError(Exception):
248
  """Error thrown when you try to display an empty Pdf. """
249
allow_class(EmptyERP5PdfFormError)
250

Jérome Perrin's avatar
Jérome Perrin committed
251

252
class PDFForm(File):
Jérome Perrin's avatar
Jérome Perrin committed
253
  """This class allows to fill PDF Form with TALES expressions,
Jérome Perrin's avatar
Jérome Perrin committed
254
    using a TALES expression for each cell.
Jérome Perrin's avatar
Jérome Perrin committed
255 256 257 258 259

  TODO:
    * cache compiled TALES
    * set _v_errors when setting invalid TALES (setCellTALES can raise, but
      not doEditCells)
Jérome Perrin's avatar
Jérome Perrin committed
260
  """
Jérome Perrin's avatar
Jérome Perrin committed
261

Jérome Perrin's avatar
Jérome Perrin committed
262 263 264
  meta_type = "ERP5 PDF Form"
  icon = "www/PDFForm.png"

Jérome Perrin's avatar
Jérome Perrin committed
265 266 267 268 269 270
  # Those 2 are ugly names, but we keep compatibility
  # the page range we want to print (a TALES expr)
  __page_range__ = ''
  # the method to format values (a TALES expr)
  __format_method__ = ''

Jérome Perrin's avatar
Jérome Perrin committed
271 272 273 274
  # Declarative Security
  security = ClassSecurityInfo()

  # Declarative properties
275 276 277 278 279 280 281 282
  _properties = File._properties + (
      {'id' : 'download_url', 'type' : 'lines', 'mode' : 'w' },
      {'id' : 'business_template_include_content',
              'type' : 'boolean', 'mode' : 'w' },
  )
  download_url = ()
  business_template_include_content = 1
  
Jérome Perrin's avatar
Jérome Perrin committed
283 284 285 286 287 288 289 290
  # Constructors
  constructors =   (manage_addPDFForm, addPDFForm)

  manage_options =  ( (
        {'label':'Edit Cell TALES', 'action':'manage_cells'},
        {'label':'Display Cell Names', 'action':'showCellNames'},
        {'label':'Test PDF generation', 'action':'generatePDF'},
        {'label':'View original', 'action':'viewOriginal'},
291
        {'label':'Download PDF content from URL', 'action':'downloadPdfContent'},
Jérome Perrin's avatar
Jérome Perrin committed
292 293 294 295
      ) +
      filter(lambda option:option['label'] != "View", File.manage_options)
  )

Jérome Perrin's avatar
Jérome Perrin committed
296
  # XXX This non thread-safeness is probably a problem under high load
Jérome Perrin's avatar
Jérome Perrin committed
297 298
  pdftk = PDFTk()

Jérome Perrin's avatar
Jérome Perrin committed
299
  def __init__ (self, id, title='', pdf_file=''):
Jérome Perrin's avatar
Jérome Perrin committed
300
    # holds all the cell informations, even those not related to this form
Jérome Perrin's avatar
Jérome Perrin committed
301
    self.all_cells = PersistentMapping()
Jérome Perrin's avatar
Jérome Perrin committed
302
    # holds the cells related to this pdf form
Jérome Perrin's avatar
Jérome Perrin committed
303
    self.cells = PersistentMapping()
Jérome Perrin's avatar
Jérome Perrin committed
304

Jérome Perrin's avatar
Jérome Perrin committed
305
    # File constructor will set the file content
Jérome Perrin's avatar
Jérome Perrin committed
306 307
    File.__init__(self, id, title, pdf_file)

308
  security.declareProtected(Permissions.ManagePortal, 'manage_upload')
Jérome Perrin's avatar
Jérome Perrin committed
309 310 311 312 313
  def manage_upload(self, file=None, REQUEST=None) :
    """ Zope calls this when the content of the enclosed file changes.
    The 'cells' attribute is updated, but already defined cells are not
    erased, they are saved in the 'all_cells' attribute so if the pdf
    file is reverted, you do not loose the cells definitions.
314
    """
Jérome Perrin's avatar
Jérome Perrin committed
315 316 317 318 319
    if not file or not hasattr(file, "read") :
      raise ValueError ("The pdf form file should not be empty")

    file.seek(0) # file is always valid here
    values = self.pdftk.dumpDataFields(file)
320
    self.cells = {}
Jérome Perrin's avatar
Jérome Perrin committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334
    for v in values :
      if v["FieldType"] != "Button" :
        k = v["FieldName"]
        if not self.all_cells.has_key(k) :
          self.cells[k] = ""
        else :
          self.cells[k] = self.all_cells[k]
    self.all_cells.update(self.cells)
    file.seek(0)
    File.manage_upload(self, file, REQUEST)
    if REQUEST:
      message = "Saved changes."
      return self.manage_main(self, REQUEST, manage_tabs_message=message)

335
  security.declareProtected(Permissions.ViewManagementScreens, 'manage_cells')
Jérome Perrin's avatar
Jérome Perrin committed
336 337 338
  manage_cells = PageTemplateFile('www/PDFForm_manageCells',
                                   globals(), __name__='manage_cells')

339
  security.declareProtected(Permissions.View, 'manage_FTPget')
340
  def manage_FTPget(self, REQUEST=None, RESPONSE=None) :
Jérome Perrin's avatar
Jérome Perrin committed
341 342 343 344 345 346 347
    """ get this pdf form via webDAV/FTP, it returns an XML
    representation of all the fields, then the pdf itself."""
    from xml.dom.minidom import getDOMImplementation
    impl = getDOMImplementation()
    newdoc = impl.createDocument(None, "pdfform", None)
    top_element = newdoc.documentElement
    cells = newdoc.createElement('cells')
348 349 350
    pdfform_cell_list = self.cells.keys()
    pdfform_cell_list.sort()
    for cell in pdfform_cell_list :
Jérome Perrin's avatar
Jérome Perrin committed
351 352 353 354 355 356 357
      cell_node = newdoc.createElement('cell')
      cell_node.setAttribute('name', cell)
      tales = newdoc.createTextNode(self.cells[cell])
      cell_node.appendChild(tales)
      cells.appendChild(cell_node)

    top_element.appendChild(cells)
Jérome Perrin's avatar
Jérome Perrin committed
358 359 360 361 362
    pdf_data = newdoc.createElement('pdf_data')
    pdf_content = newdoc.createTextNode(str(self.data))
    pdf_data.appendChild(pdf_content)
    top_element.appendChild(pdf_data)
    content = newdoc.toprettyxml('  ')
363 364 365 366 367
    if RESPONSE :
      RESPONSE.setHeader('Content-Type', 'application/x-erp5-pdfform')
      RESPONSE.setHeader('Content-Length', len(content))
      RESPONSE.write(content)
    return content
Jérome Perrin's avatar
Jérome Perrin committed
368
  manage_DAVget = manage_FTPget
369

370
  security.declareProtected(Permissions.ManagePortal, 'PUT')
Jérome Perrin's avatar
Jérome Perrin committed
371 372 373 374 375 376
  def PUT(self, REQUEST, RESPONSE):
    """(does not) Handle HTTP PUT requests."""
    RESPONSE.setStatus(501)
    return RESPONSE
  manage_FTPput = PUT

377 378 379 380 381
  security.declareProtected(Permissions.View, 'hasPdfContent')
  def hasPdfContent(self) :
    """Return true if there is an enclosed PDF in this PDF Form."""
    return self.data is not None and len(self.data) > 0

Jérome Perrin's avatar
Jérome Perrin committed
382
  security.declareProtected(Permissions.ManagePortal, 'downloadPdfContent')
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  def downloadPdfContent(self, REQUEST=None) :
    """Download the pdf content from one of `download_url` URL """
    for url in self.getProperty('download_url') :
      try :
        response = urllib.urlopen(url)
      except IOError, e :
        LOG("PDFForm", WARNING, "Unable to download from %s" % url, e)
        continue
      if response.headers.getheader('Content-Type') != 'application/pdf':
        LOG("PDFForm", WARNING, "%s is not application/pdf" % url)
        continue
      self.manage_upload(cStringIO.StringIO(response.read()))
      self.content_type = 'application/pdf'
      if REQUEST is not None :
        return REQUEST.RESPONSE.redirect(
              "%s/manage_main?manage_tabs_message=Content+Downloaded"
              % self.absolute_url())
      return
    raise ValueError, "Unable to download from any url from the "\
                      "`download_url` property."
Jérome Perrin's avatar
Jérome Perrin committed
403

404 405 406 407 408 409 410 411
  security.declareProtected(Permissions.ManagePortal,
                           'deletePdfContent')
  def deletePdfContent(self) :
    """Reset the pdf content. """
    assert self.getProperty('download_url'), "Download URL must be set"\
        " to delete content from PDF Form '%s'" % self.getId()
    self.data = None

412
  security.declareProtected(Permissions.View, 'viewOriginal')
Jérome Perrin's avatar
Jérome Perrin committed
413 414 415 416 417 418 419 420
  def viewOriginal(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
    """ publish original pdf """
    pdf = File.index_html(self, REQUEST, RESPONSE, *args, **kwargs)
    RESPONSE.setHeader('Content-Type', 'application/pdf')
    RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"'
        % (self.title_or_id()))
    return pdf

421
  security.declareProtected(Permissions.View, 'showCellNames')
Jérome Perrin's avatar
Jérome Perrin committed
422 423 424
  def showCellNames(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
    """ generates a pdf with fields filled-in by their names,
     usefull to fill in settings.
425
    """
Jérome Perrin's avatar
Jérome Perrin committed
426 427 428 429 430 431 432 433 434 435 436 437
    values = {}
    for cell in self.cells.keys() :
      values[cell] = cell
    pdf = self.pdftk.fillFormWithDict(str(self.data), values)
    if RESPONSE :
      RESPONSE.setHeader('Content-Type', 'application/pdf')
      RESPONSE.setHeader('Content-Length', len(pdf))
      RESPONSE.setHeader('Content-Disposition',
                         'inline;filename="%s.template.pdf"' % (
                              self.title_or_id()))
    return pdf

438
  security.declareProtected(Permissions.ManagePortal, 'doEditCells')
Jérome Perrin's avatar
Jérome Perrin committed
439
  def doEditCells(self, REQUEST, RESPONSE=None):
Jérome Perrin's avatar
Jérome Perrin committed
440 441 442 443 444 445 446 447
    """ This is the action to the 'Edit Cell TALES' tab. """
    if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
      raise ResourceLockedError, "File is locked via WebDAV"

    for k, v in self.cells.items() :
      self.setCellTALES(k, REQUEST.get(str(k), v))
    self.__format_method__ = REQUEST.get("__format_method__")
    self.__page_range__ = REQUEST.get("__page_range__")
Jérome Perrin's avatar
Jérome Perrin committed
448 449 450
    
    if RESPONSE:
      return self.manage_cells(manage_tabs_message="Saved changes.")
Jérome Perrin's avatar
Jérome Perrin committed
451

452
  security.declareProtected(Permissions.View, 'generatePDF')
Jérome Perrin's avatar
Jérome Perrin committed
453 454
  def generatePDF(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
    """ generates the PDF with form filled in """
455
    if not self.hasPdfContent() :
456
      raise EmptyERP5PdfFormError, 'Pdf content must be downloaded first'
Jérome Perrin's avatar
Jérome Perrin committed
457
    values = self.calculateCellValues(REQUEST, *args, **kwargs)
458 459 460
    context = { 'here' : self.aq_parent,
                'context' : self.aq_parent,
                'request' : REQUEST }
Jérome Perrin's avatar
Jérome Perrin committed
461
    if self.__format_method__:
Jérome Perrin's avatar
Jérome Perrin committed
462 463 464 465 466 467 468 469 470
      compiled_tales = getEngine().compile(self.__format_method__)
      format_method = getEngine().getContext(context).evaluate(compiled_tales)
      # try to support both method name and method object
      if not callable(format_method) :
        format_method = self.restrictedTraverse(format_method)
      if callable(format_method) :
        for k, v in values.items() :
          values[k] = format_method(v, cell_name=k)
      else :
Jérome Perrin's avatar
Jérome Perrin committed
471 472
        LOG("PDFForm", PROBLEM,
            'format method (%r) is not callable' % format_method)
Jérome Perrin's avatar
Jérome Perrin committed
473
    data = str(self.data)
474
    pdf = self.pdftk.fillFormWithDict(data, values)
Jérome Perrin's avatar
Jérome Perrin committed
475
    if self.__page_range__:
Jérome Perrin's avatar
Jérome Perrin committed
476 477 478
      compiled_tales = getEngine().compile(self.__page_range__)
      page_range = getEngine().getContext(context).evaluate(compiled_tales)
      if page_range :
479
        pdf = self.pdftk.catPages(pdf, page_range)
Jérome Perrin's avatar
Jérome Perrin committed
480 481 482 483
    if RESPONSE :
      RESPONSE.setHeader('Content-Type', 'application/pdf')
      RESPONSE.setHeader('Content-Length', len(pdf))
      RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"'
484
            % (self.title_or_id()))
Jérome Perrin's avatar
Jérome Perrin committed
485 486 487 488
    return pdf
  index_html = generatePDF
  __call__ = generatePDF

489
  security.declareProtected(Permissions.View, 'calculateCellValues')
Jérome Perrin's avatar
Jérome Perrin committed
490 491 492 493 494 495 496
  def calculateCellValues(self, REQUEST=None, *args, **kwargs) :
    """ returns a dict of cell values """
    # values to be returned
    values = {}
    # list of values that need to be reevaluated (i.e. they depend on the
    # value of a cell that was not already evaluated when evaluating them )
    uncalculated_values = []
497 498 499 500
    # cleanup kw arguments, not to pass `cell` twice to evaluateCell
    if 'cell' in kwargs:
      del kwargs['cell']

Jérome Perrin's avatar
Jérome Perrin committed
501 502 503 504
    for cell_name in self.cells.keys() :
      not_founds = []
      value = self.evaluateCell(cell_name, REQUEST = REQUEST,
              cell = SafeMapping(CalculatedValues(
505
                              values, cell_name, not_founds)), **kwargs)
Jérome Perrin's avatar
Jérome Perrin committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
      if len(not_founds) != 0 :
        uncalculated_values.append(cell_name)
      else :
        values[cell_name] = value
    # now we iterate on the list of uncalculated values, trying
    # to evaluate them again, if an iteration doesn't decrement
    # the length of this list, there are some circular references
    # and we cannot continue.
    while 1 :
      uncalculated_values_len = len(uncalculated_values)
      if uncalculated_values_len == 0 :
        return values
      for cell_name in uncalculated_values :
        not_founds = []
        value = self.evaluateCell(cell_name, REQUEST = REQUEST,
                cell = SafeMapping(CalculatedValues(
522
                                values, cell_name, not_founds)), **kwargs)
Jérome Perrin's avatar
Jérome Perrin committed
523 524 525 526
        if len(not_founds) == 0 :
          uncalculated_values.remove(cell_name)
          values[cell_name] = value
      if len(uncalculated_values) == uncalculated_values_len :
Jérome Perrin's avatar
Jérome Perrin committed
527 528
        raise CircularReferencyError("Unable to evaluate cells: %r"
                                       % (uncalculated_values, ))
Jérome Perrin's avatar
Jérome Perrin committed
529

530
  security.declareProtected(Permissions.View, 'getCellNames')
Jérome Perrin's avatar
Jérome Perrin committed
531 532 533 534 535 536
  def getCellNames(self, REQUEST=None) :
    """ returns a list of cell names """
    names = self.cells.keys()
    names.sort()
    return names

537 538
  security.declareProtected(Permissions.ManagePortal, 'deleteCell')
  def deleteCell(self, cell_name):
539
    """ Delete a cell.
540 541 542 543
    As setCellTALES add the cell if it is not present, we must have a
    way to remove cells created by mistake. """
    del self.all_cells[cell_name]
    del self.cells[cell_name]
544

545
  security.declareProtected(Permissions.ManagePortal, 'setCellTALES')
Jérome Perrin's avatar
Jérome Perrin committed
546 547 548 549
  def setCellTALES(self, cell_name, TALES):
    """ changes the TALES expression that will be used to evaluate
    cell value """
    if type(TALES) != types.StringType :
550
      LOG("PDFForm", PROBLEM,
Jérome Perrin's avatar
Jérome Perrin committed
551 552 553 554
         'TALES is not a string for cell "%s", it is = "%s"'
          %(cell_name, `TALES`))
      raise ValueError, 'TALES must be a string'
    self.all_cells[str(cell_name)] = self.cells[str(cell_name)] = TALES
555 556
    # invalidate for persistence
    self.all_cells = self.all_cells
557

558
  security.declareProtected(Permissions.View, 'getCellTALES')
Jérome Perrin's avatar
Jérome Perrin committed
559 560 561 562
  def getCellTALES(self, cell_name):
    """ returns the TALES expression associated with this cell """
    return self.cells[str(cell_name)]

563
  security.declareProtected(Permissions.View, 'evaluateCell')
Jérome Perrin's avatar
Jérome Perrin committed
564 565 566 567 568 569 570
  def evaluateCell(self, cell_name, REQUEST=None, **kwargs):
    """ evaluate the TALES expression for this cell """
    cell_name = str(cell_name)
    # we don't pass empty strings in TALES engine
    # (and this also raises the KeyError for non existant cells)
    if not self.cells[cell_name] :
      return None
Jérome Perrin's avatar
Jérome Perrin committed
571 572 573
    context = { 'here' : self.aq_parent,
                'context' : self.aq_parent,
                'request' : REQUEST }
574 575 576 577 578
    context.update (kwargs)
    __traceback_info__ = 'Evaluating cell "%s"' % cell_name
    compiled_tales = getEngine().compile(self.cells[cell_name])
    value = getEngine().getContext(context).evaluate(compiled_tales)
    return value
Jérome Perrin's avatar
Jérome Perrin committed
579

580
  security.declareProtected(Permissions.ManagePortal, 'setAllCellTALES')
Jérome Perrin's avatar
Jérome Perrin committed
581 582 583 584 585
  def setAllCellTALES(self, new_cells) :
    """ set all cell values from a dict containing { name: TALES } """
    for cell_name, cell_TALES in new_cells.items() :
      self.setCellTALES(cell_name, cell_TALES)

586
  security.declareProtected(Permissions.View, 'getFormatMethodTALES')
Jérome Perrin's avatar
Jérome Perrin committed
587 588 589 590
  def getFormatMethodTALES(self):
    """ returns the TALES expression for the format method attribute """
    return self.__format_method__

591
  security.declareProtected(Permissions.ManagePortal, 'setFormatMethodTALES')
Jérome Perrin's avatar
Jérome Perrin committed
592 593 594 595
  def setFormatMethodTALES(self, TALES):
    """ sets TALES expression for the format method attribute """
    self.__format_method__ = str(TALES)

596
  security.declareProtected(Permissions.View, 'getPageRangeTALES')
Jérome Perrin's avatar
Jérome Perrin committed
597 598 599 600
  def getPageRangeTALES(self):
    """ returns the TALES expression for the page range attribute """
    return self.__page_range__

601
  security.declareProtected(Permissions.ManagePortal, 'setPageRangeTALES')
Jérome Perrin's avatar
Jérome Perrin committed
602 603 604
  def setPageRangeTALES(self, TALES):
    """ sets TALES expression for the page range attribute """
    self.__page_range__ = str(TALES)
605

606 607
InitializeClass(PDFForm)