FormPrintout.py 36.5 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
##############################################################################
#
# Copyright (c) 2009 Nexedi KK and Contributors. All Rights Reserved.
#                    Tatuya Kamada <tatuya@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
25 26
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
# USA.
27 28
##############################################################################
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
29
from Products.CMFCore.utils import _checkPermission
30
from Products.ERP5Type import PropertySheet, Permissions
31 32 33
from Products.ERP5Form.ListBox import ListBox
from Products.ERP5Form.FormBox import FormBox
from Products.ERP5Form.ImageField import ImageField
34
from Products.ERP5OOo.OOoUtils import OOoBuilder
35
from Products.CMFCore.exceptions import AccessControl_Unauthorized
Tatuya Kamada's avatar
Tatuya Kamada committed
36
from Acquisition import Implicit, aq_base
37 38 39
from Globals import InitializeClass, DTMLFile, Persistent, get_request
from AccessControl import ClassSecurityInfo
from AccessControl.Role import RoleManager
40
from OFS.SimpleItem import Item
Tatuya Kamada's avatar
Tatuya Kamada committed
41
from urllib import quote, quote_plus
42 43 44 45
from copy import deepcopy
from lxml import etree
from zLOG import LOG, DEBUG, INFO, WARNING
from mimetypes import guess_extension
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
46
from DateTime import DateTime
Tatuya Kamada's avatar
Tatuya Kamada committed
47
from decimal import Decimal
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
48
from xml.sax.saxutils import escape
Tatuya Kamada's avatar
Tatuya Kamada committed
49
import re
50 51 52 53 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

try:
  from webdav.Lockable import ResourceLockedError
  SUPPORTS_WEBDAV_LOCKS = 1
except ImportError:
  SUPPORTS_WEBDAV_LOCKS = 0

# Constructors
manage_addFormPrintout = DTMLFile("dtml/FormPrintout_add", globals())

def addFormPrintout(self, id, title="", form_name='', template='', REQUEST=None):
  """Add form printout to folder.

  Keyword arguments:
  id     -- the id of the new form printout to add
  title  -- the title of the form printout to add
  form_name -- the name of a form which contains data to printout
  template -- the name of a template which describes printout layout
  """
  # add actual object
  id = self._setObject(id, FormPrintout(id, title, form_name, template))
  # 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.

  Keyword arguments:
80
  id -- the id of the object we just added
81 82 83 84 85 86 87 88 89 90
  """
  if REQUEST is None:
    return
  try:
    u = self.DestinationURL()
  except AttributeError:
    u = REQUEST['URL1']
  if REQUEST['submit'] == " Add and Edit ":
    u = "%s/%s" % (u, quote(id))
  REQUEST.RESPONSE.redirect(u+'/manage_main')
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
91

92 93 94 95 96
class FormPrintout(Implicit, Persistent, RoleManager, Item):
  """Form Printout

  The Form Printout enables to create a ODF document.

97
  The Form Printout receives an ERP5 form name, and a template name.
98 99 100 101
  Using their parameters, the Form Printout genereate a ODF document,
  a form as a ODF document content, and a template as a document layout.

  WARNING: The Form Printout currently supports only ODT format document.
Tatuya Kamada's avatar
Tatuya Kamada committed
102 103

  The functions status:
104
  
Tatuya Kamada's avatar
Tatuya Kamada committed
105 106 107 108 109 110 111
  Fields -> Paragraphs:      supported
  ListBox -> Table:          supported
  Report Section -> Frames:  experimentally supported
  FormBox -> Frame:          experimentally supported
  ImageField -> Photo:       supported
  styles.xml:                supported
  meta.xml:                  not supported yet
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
  """
  
  meta_type = "ERP5 Form Printout"

  # Declarative Security
  security = ClassSecurityInfo()

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

  # Constructors
  constructors =   (manage_addFormPrintout, addFormPrintout)

  # Tabs in ZMI
  manage_options = ((
    {'label':'Edit', 'action':'manage_editFormPrintout'},
    {'label':'View', 'action': '' }, ) + Item.manage_options)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
130
  
131 132
  security.declareProtected('View management screens', 'manage_editFormPrintout')
  manage_editFormPrintout = PageTemplateFile('www/FormPrintout_manageEdit', globals(),
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
133
                                             __name__='manage_editFormPrintout')
134
  manage_editFormPrintout._owner = None
135 136 137 138

  # alias definition to do 'add_and_edit'
  security.declareProtected('View management screens', 'manage_main')
  manage_main = manage_editFormPrintout
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  
  # default attributes
  template = None
  form_name = None

  def __init__(self, id, title='', form_name='', template=''):
    """Initialize id, title, form_name, template.

    Keyword arguments:
    id -- the id of a form printout
    title -- the title of a form printout
    form_name -- the name of a form which as a document content
    template -- the name of a template which as a document layout
    """
    self.id = id
    self.title = title
    self.form_name = form_name
    self.template = template

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
158
  security.declareProtected('View', 'index_html')
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  def index_html(self, icon=0, preview=0, width=None, height=None, REQUEST=None):
    """Render and view a printout document."""
    
    obj = getattr(self, 'aq_parent', None)
    if obj is not None:
      container = obj.aq_inner.aq_parent
      if not _checkPermission(Permissions.View, obj):
        raise AccessControl_Unauthorized('This document is not authorized for view.')
      else:
        container = None
    form = getattr(obj, self.form_name)
    if self.template is None or self.template == '':
      raise ValueError, 'Can not create a ODF Document without a printout template'
    printout_template = getattr(obj, self.template)

    report_method = None
    if hasattr(form, 'report_method'):
      report_method = getattr(obj, form.report_method)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
177 178 179 180 181
    extra_context = dict(container=container,
                         printout_template=printout_template,
                         report_method=report_method,
                         form=form,
                         here=obj)
Tatuya Kamada's avatar
Tatuya Kamada committed
182
    # set property to do aquisition
183
    content_type = printout_template.content_type
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
184
    self.strategy = self._createStrategy(content_type)
185
    printout = self.strategy.render(extra_context=extra_context)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
186 187 188 189
    if REQUEST is not None:
      REQUEST.RESPONSE.setHeader('Content-Type','%s; charset=utf-8' % content_type)
      REQUEST.RESPONSE.setHeader('Content-disposition',
                                 'inline;filename="%s%s"' % (self.title_or_id(), guess_extension(content_type)))
190
    return printout
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
191

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
192 193
  security.declareProtected('View', '__call__')
  __call__ = index_html
194
                
195 196 197 198 199 200 201 202 203 204 205 206 207 208
  security.declareProtected('Manage properties', 'doSettings')
  def doSettings(self, REQUEST, title='', form_name='', template=''):
    """Change title, form_name, template."""
    if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
      raise ResourceLockedError, "File is locked via WebDAV"
    self.form_name = form_name
    self.template = template
    self.title = title
    message = "Saved changes."
    if getattr(self, '_v_warnings', None):
      message = ("<strong>Warning:</strong> <i>%s</i>"
                % '<br>'.join(self._v_warnings))
    return self.manage_editFormPrintout(manage_tabs_message=message)

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
209
  def _createStrategy(slef, content_type=''):
210 211 212 213 214 215 216 217
    if guess_extension(content_type) == '.odt':
      return ODTStrategy()
    raise ValueError, 'Do not support the template type:%s' % content_type

InitializeClass(FormPrintout)

class ODFStrategy(Implicit):
  """ODFStrategy creates a ODF Document. """
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
218

Tatuya Kamada's avatar
Tatuya Kamada committed
219 220
  odf_existent_name_list = []
  
221
  def render(self, extra_context={}):
222
    """Render a odf document, form as a content, template as a template.
223 224

    Keyword arguments:
225
    extra_context -- a dictionary, expected:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
226 227 228 229
      'here' : where it call
      'printout_template' : the template object, tipically a OOoTemplate
      'container' : the object which has a form printout object
      'form' : the form as a content
230 231 232 233 234 235 236 237 238
    """
    here = extra_context['here']
    if here is None:
      raise ValueError, 'Can not create a ODF Document without a parent acquisition context'
    form = extra_context['form']
    if not extra_context.has_key('printout_template') or extra_context['printout_template'] is None:
      raise ValueError, 'Can not create a ODF Document without a printout template'

    odf_template = extra_context['printout_template']
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
239

240
    # First, render the Template if it has a pt_render method
241 242 243 244
    ooo_document = None
    if hasattr(odf_template, 'pt_render'):
      ooo_document = odf_template.pt_render(here, extra_context=extra_context)
    else:
245
      # File object can be a template
246 247 248 249
      ooo_document = odf_template 

    # Create a new builder instance
    ooo_builder = OOoBuilder(ooo_document)
Tatuya Kamada's avatar
Tatuya Kamada committed
250 251
    self.odf_existent_name_list = ooo_builder.getNameList()
    
252
    # content.xml
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
253
    ooo_builder = self._replaceContentXml(ooo_builder=ooo_builder, extra_context=extra_context)
254
    # styles.xml
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
255
    ooo_builder = self._replaceStylesXml(ooo_builder=ooo_builder, extra_context=extra_context)
256
    # meta.xml is not supported yet
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
257 258
    # ooo_builder = self._replaceMetaXml(ooo_builder=ooo_builder, extra_context=extra_context)

259 260 261 262 263 264
    # Update the META informations
    ooo_builder.updateManifest()

    ooo = ooo_builder.render(name=odf_template.title or odf_template.id)
    return ooo

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
265
  def _replaceContentXml(self, ooo_builder=None, extra_context=None):
266
    content_xml = ooo_builder.extract('content.xml')
267 268 269 270
    # mapping ERP5Form to ODF
    form = extra_context['form']
    here = getattr(self, 'aq_parent', None)

271
    content_element_tree = etree.XML(content_xml)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
272 273 274
    content_element_tree = self._replaceXmlByForm(element_tree=content_element_tree,
                                                  form=form,
                                                  here=here,
Tatuya Kamada's avatar
Tatuya Kamada committed
275 276
                                                  extra_context=extra_context,
                                                  ooo_builder=ooo_builder)
277
    # mapping ERP5Report report method to ODF
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
278
    content_element_tree = self._replaceXmlByReportSection(element_tree=content_element_tree,
Tatuya Kamada's avatar
Tatuya Kamada committed
279 280
                                                           extra_context=extra_context,
                                                           ooo_builder=ooo_builder)
Tatuya Kamada's avatar
Tatuya Kamada committed
281 282
    content_xml = etree.tostring(content_element_tree, encoding='utf-8')
 
283
    # Replace content.xml in master openoffice template
284
    ooo_builder.replace('content.xml', content_xml)
285 286 287
    return ooo_builder

  # this method not supported yet
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
288
  def _replaceStylesXml(self, ooo_builder=None, extra_context=None):
289 290 291
    """
    replacing styles.xml file in a ODF document
    """
292
    styles_xml = ooo_builder.extract('styles.xml')
293 294
    form = extra_context['form']
    here = getattr(self, 'aq_parent', None)
295
    styles_element_tree = etree.XML(styles_xml)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
296 297 298
    styles_element_tree = self._replaceXmlByForm(element_tree=styles_element_tree,
                                                 form=form,
                                                 here=here,
Tatuya Kamada's avatar
Tatuya Kamada committed
299 300
                                                 extra_context=extra_context,
                                                 ooo_builder=ooo_builder)
Tatuya Kamada's avatar
Tatuya Kamada committed
301
    styles_xml = etree.tostring(styles_element_tree, encoding='utf-8')
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
302

303
    ooo_builder.replace('styles.xml', styles_xml)
304 305 306
    return ooo_builder

  # this method not implemented yet
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
307
  def _replaceMetaXml(self, ooo_builder=None, extra_context=None):
308 309 310 311 312
    """
    replacing meta.xml file in a ODF document
    """
    return ooo_builder

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
313
  def _replaceXmlByForm(self, element_tree=None, form=None, here=None,
314
                           extra_context=None, ooo_builder=None, iteration_index=0):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
315
    field_list = form.get_fields(include_disabled=1) 
316
    REQUEST = get_request()
317
    for (count, field) in enumerate(field_list):
318
      if isinstance(field, ListBox):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
319 320
        element_tree = self._appendTableByListbox(element_tree=element_tree,
                                                  listbox=field,
321 322
                                                  REQUEST=REQUEST,
                                                  iteration_index=iteration_index)
323
      elif isinstance(field, FormBox):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
324 325
        if not hasattr(here, field.get_value('formbox_target_id')):
          continue
326
        sub_form = getattr(here, field.get_value('formbox_target_id'))
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
327
        content = self._replaceXmlByFormbox(element_tree=element_tree,
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
328 329 330
                                            field=field,
                                            form=sub_form,
                                            extra_context=extra_context,
331 332
                                            ooo_builder=ooo_builder,
                                            iteration_index=iteration_index)
Tatuya Kamada's avatar
Tatuya Kamada committed
333 334 335
      elif isinstance(field, ImageField):
        element_tree = self._replaceXmlByImageField(element_tree=element_tree,
                                                    image_field=field,
336 337
                                                    ooo_builder=ooo_builder,
                                                    iteration_index=iteration_index)
338
      else:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
339
        element_tree = self._replaceNodeViaReference(element_tree=element_tree,
340
                                                     field=field, iteration_index=iteration_index)
341
    return element_tree
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
342

343
  def _replaceNodeViaReference(self, element_tree=None, field=None, iteration_index=0):
Tatuya Kamada's avatar
Tatuya Kamada committed
344 345 346 347 348
    """replace nodes (e.g. paragraphs) via ODF reference"""
    element_tree = self._replaceNodeViaRangeReference(element_tree=element_tree, field=field)
    element_tree = self._replaceNodeViaPointReference(element_tree=element_tree, field=field)
    return element_tree
  
349 350 351 352 353
  def _renderField(self, field):
    # XXX It looks ugly to use render_pdf to extract text. Probably
    # it should be renamed to render_text.
    return field.render_pdf(field.get_value('default'))

354
  def _replaceNodeViaPointReference(self, element_tree=None, field=None, iteration_index=0):
Tatuya Kamada's avatar
Tatuya Kamada committed
355 356 357 358 359
    """replace via ODF point reference
    
    point reference example:
     <text:reference-mark text:name="invoice-date"/>
    """
360
    field_id = field.id
361
    field_value = self._renderField(field)
Tatuya Kamada's avatar
Tatuya Kamada committed
362
    value = self._toUnicodeString(field_value)
363 364
    # text:reference-mark text:name="invoice-date"
    reference_xpath = '//text:reference-mark[@text:name="%s"]' % field_id
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
365
    reference_list = element_tree.xpath(reference_xpath, namespaces=element_tree.nsmap)
366
    if len(reference_list) > 0:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
367
      target_node = reference_list[0]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
368 369 370
      paragraph_node = reference_list[0].getparent()
      parent_node = paragraph_node.getparent()
      if not isinstance(field_value, list):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
371
        # remove such a "bbb": <text:p>aaa<text:line-break/>bbb</text:p>
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
372 373
        for child in paragraph_node.getchildren():
          child.tail = ''
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
374
        paragraph_node.text = value
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
375
      else:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
376
        self._appendParagraphsWithLineList(target_node=target_node, line_list=field_value)
377 378 379 380 381
    # set when using report section
    self._setUniqueElementName(base_name=field.id,
                               iteration_index=iteration_index,
                               xpath=reference_xpath,
                               element_tree=element_tree)
382
    return element_tree
Tatuya Kamada's avatar
Tatuya Kamada committed
383
  
384
  def _replaceNodeViaRangeReference(self, element_tree=None, field=None, iteration_index=0):
Tatuya Kamada's avatar
Tatuya Kamada committed
385
    """replace via ODF range reference
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
386

Tatuya Kamada's avatar
Tatuya Kamada committed
387 388 389
    range reference example:
    <text:reference-mark-start text:name="week"/>Monday<text:reference-mark-end text:name="week"/>
    """
390
    field_value = self._renderField(field)
Tatuya Kamada's avatar
Tatuya Kamada committed
391 392 393 394 395 396
    value = self._toUnicodeString(field_value)
    range_reference_xpath = '//text:reference-mark-start[@text:name="%s"]' % field.id
    reference_list = element_tree.xpath(range_reference_xpath, namespaces=element_tree.nsmap)
    if len(reference_list) is 0:
      return element_tree
    target_node = reference_list[0]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
397 398
    if not isinstance(field_value, list):
      target_node.tail = value
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
399
      # clear text until 'reference-mark-end'
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
400 401 402 403 404 405 406 407
      for node in target_node.itersiblings():
        end_tag_name = '{%s}reference-mark-end' % element_tree.nsmap['text']
        name_attribute = '{%s}name' % element_tree.nsmap['text']
        if node.tag == end_tag_name and node.get(name_attribute) == field.id:
          break
        node.tail = ''
    else:
      self._appendParagraphsWithLineList(target_node=target_node, line_list=field_value)
408 409 410 411 412 413

    # set when using report section
    self._setUniqueElementName(base_name=field.id,
                               iteration_index=iteration_index,
                               xpath=range_reference_xpath,
                               element_tree=element_tree)
Tatuya Kamada's avatar
Tatuya Kamada committed
414
    return element_tree
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

  def _appendParagraphsWithLineList(self, target_node=None, line_list=None):
    """create paragraphs 
    
    example:
    --
    first line
    second line
    --
    <p:text>
    first line
    </p:text>
    <p:text>
    second line
    </p:text>
    """
    paragraph_node = target_node.getparent()
    parent_node = paragraph_node.getparent()
    paragraph_list = []
    for line in line_list:
      p = deepcopy(paragraph_node)
      for child in p.getchildren():
        child.tail = ''
      value = self._toUnicodeString(line)
      p.text = value
      paragraph_list.append(p)
    paragraph_node_index = parent_node.index(paragraph_node)
    parent_node.remove(paragraph_node)
    for (index, paragraph) in enumerate(paragraph_list):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
444 445 446
      parent_node.insert(paragraph_node_index, paragraph)
      paragraph_node_index = paragraph_node_index + 1
      
Tatuya Kamada's avatar
Tatuya Kamada committed
447
  def _replaceXmlByReportSection(self, element_tree=None, extra_context=None, ooo_builder=None):
448
    if not extra_context.has_key('report_method') or extra_context['report_method'] is None:
449
      return element_tree
450 451 452 453 454
    report_method = extra_context['report_method']
    report_section_list = report_method()
    portal_object = self.getPortalObject()
    REQUEST = get_request()
    request = extra_context.get('REQUEST', REQUEST)
Tatuya Kamada's avatar
Tatuya Kamada committed
455

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
456 457 458 459 460 461 462 463 464 465 466 467 468
    report_section_frame_xpath = '//draw:frame[@draw:name="%s"]' % report_method.__name__
    frame_list = element_tree.xpath(report_section_frame_xpath, namespaces=element_tree.nsmap)
    if len(frame_list) is 0:
      return element_tree
    frame = frame_list[0]
    frame_paragraph = frame.getparent()
    office_body = frame_paragraph.getparent()
    # remove if no report section
    if len(report_section_list) is 0:
      office_body.remove(frame_paragraph)
      return element_tree
    frame_paragraph_index = office_body.index(frame_paragraph)
    temporary_element_tree = deepcopy(frame_paragraph)
469
    for (index, report_item) in enumerate(report_section_list):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
470
      report_item.pushReport(portal_object, render_prefix=None)
471 472 473
      here = report_item.getObject(portal_object)
      form_id = report_item.getFormId()
      form = getattr(here, form_id)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
474 475 476 477
      
      frame_paragraph_element_tree = deepcopy(temporary_element_tree)
      if index is 0:
        office_body.remove(frame_paragraph)
Tatuya Kamada's avatar
Tatuya Kamada committed
478
      else:
479 480 481 482
        self._setUniqueElementName(base_name=report_method.__name__,
                                   iteration_index=index,
                                   xpath=report_section_frame_xpath,
                                   element_tree=frame_paragraph_element_tree)
Tatuya Kamada's avatar
Tatuya Kamada committed
483 484 485 486 487

      frame_paragraph_element_tree = self._replaceXmlByForm(element_tree=frame_paragraph_element_tree,
                                                            form=form,
                                                            here=here,
                                                            extra_context=extra_context,
488 489
                                                            ooo_builder=ooo_builder,
                                                            iteration_index=index)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
490 491
      office_body.insert(frame_paragraph_index, frame_paragraph_element_tree)
      frame_paragraph_index += 1
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
492
      report_item.popReport(portal_object, render_prefix=None)
493 494
    return element_tree

495 496 497 498 499 500 501 502 503 504
  def _setUniqueElementName(self, base_name='', iteration_index=0, xpath='', element_tree=None):
    """create a unique element name and set it to the element tree

    Keyword arguments:
    base_name -- the base name of the element
    iteration_index -- iteration index
    xpath -- xpath expression which was used to search the element
    element_tree -- element tree
    """
    if iteration_index is 0:
Tatuya Kamada's avatar
Tatuya Kamada committed
505
      return
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    def getNameAttribute(target_element=None):
      if target_element is None:
        return None
      attrib = target_element.attrib
      for key in attrib.keys():
        if key.endswith("}name"):
          return key
      return None
    odf_element_name =  "%s_%s" % (base_name, iteration_index)
    result_list = element_tree.xpath(xpath, namespaces=element_tree.nsmap)
    if len(result_list) is 0:
      return
    target_element = result_list[0]
    name_attribute = getNameAttribute(target_element)
    if name_attribute is not None:
      target_element.set(name_attribute, odf_element_name)
 
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
523 524 525 526 527
  def _replaceXmlByFormbox(self,
                           element_tree=None,
                           field=None,
                           form=None,
                           extra_context=None,
528 529
                           ooo_builder=None,
                           iteration_index=0):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
530 531
    field_id = field.id
    enabled = field.get_value('enabled')
532
    draw_xpath = '//draw:frame[@draw:name="%s"]/draw:text-box/*' % field_id
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
533
    text_list = element_tree.xpath(draw_xpath, namespaces=element_tree.nsmap)
534 535
    if len(text_list) == 0:
      return element_tree
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
536 537 538 539 540 541
    target_element = text_list[0]
    frame_paragraph = target_element.getparent()
    office_body = frame_paragraph.getparent()
    if not enabled:
      office_body.remove(frame_paragraph)
      return element_tree
542 543 544 545 546
    # set when using report section
    self._setUniqueElementName(base_name=field_id,
                               iteration_index=iteration_index,
                               xpath=draw_xpath,
                               element_tree=element_tree)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
547 548 549 550
    self._replaceXmlByForm(element_tree=frame_paragraph,
                           form=form,
                           here=extra_context['here'],
                           extra_context=extra_context,
551 552
                           ooo_builder=ooo_builder,
                           iteration_index=iteration_index)
553 554
    return element_tree

555 556 557 558 559
  def _replaceXmlByImageField(self,
                              element_tree=None,
                              image_field=None,
                              ooo_builder=None,
                              iteration_index=0):
560 561
    alt = image_field.get_value('description') or image_field.get_value('title')
    image_xpath = '//draw:frame[@draw:name="%s"]/*' % image_field.id
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
562
    image_list = element_tree.xpath(image_xpath, namespaces=element_tree.nsmap)
Tatuya Kamada's avatar
Tatuya Kamada committed
563 564 565
    if len(image_list) is 0:
      return element_tree
    path = image_field.get_value('default')
Tatuya Kamada's avatar
Tatuya Kamada committed
566 567
    if path is not None:
      path = path.encode()
Tatuya Kamada's avatar
Tatuya Kamada committed
568
    picture = self.getPortalObject().restrictedTraverse(path)
Tatuya Kamada's avatar
Tatuya Kamada committed
569 570 571 572 573 574 575 576 577 578
    picture_data = getattr(aq_base(picture), 'data', None)
    picture_type = picture.getContentType()
    picture_path = self._createOdfUniqueFileName(path=path, picture_type=picture_type)
    ooo_builder.addFileEntry(picture_path, media_type=picture_type, content=picture_data)
    image_node = image_list[0]
    picture_size = self._getPictureSize(picture, image_node)
    image_node.set('{%s}href' % element_tree.nsmap['xlink'], picture_path)
    image_frame = image_node.getparent()
    image_frame.set('{%s}width' % element_tree.nsmap['svg'], picture_size[0])
    image_frame.set('{%s}height' % element_tree.nsmap['svg'], picture_size[1])
579 580 581 582 583
    # set when using report section
    self._setUniqueElementName(base_name=image_field.id,
                               iteration_index=iteration_index,
                               xpath=image_xpath,
                               element_tree=element_tree)
584
    return element_tree
585

Tatuya Kamada's avatar
Tatuya Kamada committed
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
  def _createOdfUniqueFileName(self, path='', picture_type=''):
    extension = guess_extension(picture_type)
    picture_path = 'Pictures/%s%s' % (quote_plus(path), extension)     
    if picture_path not in self.odf_existent_name_list:
      return picture_path
    number = 0
    while True:
      picture_path = 'Pictures/%s_%s%s' % (path, number, extension)
      if picture_path not in self.odf_existent_name_list:
        return picture_path
      number += 1

  def _getPictureSize(self, picture=None, image_node=None):
    if picture is None or image_node is None:
      return ('0cm', '0cm')
    draw_frame_node = image_node.getparent()
    svg_width = draw_frame_node.attrib.get('{%s}width' % draw_frame_node.nsmap['svg'])
    svg_height = draw_frame_node.attrib.get('{%s}height' % draw_frame_node.nsmap['svg'])
    if svg_width is None or svg_height is None:
      return ('0cm', '0cm')
    # if not match causes exception
    width_tuple = re.match("(\d[\d\.]*)(.*)", svg_width).groups()
    height_tuple = re.match("(\d[\d\.]*)(.*)", svg_height).groups()
    unit = width_tuple[1]
    w = Decimal(width_tuple[0])
    h = Decimal(height_tuple[0])
    aspect_ratio = 1
    try: # try image properties
      aspect_ratio = Decimal(picture.width) / Decimal(picture.height)
    except (TypeError, ZeroDivisionError):
      try: # try ERP5.Document.Image API
        height = Decimal(picture.getHeight())
        if height:
          aspect_ratio = Decimal(picture.getWidth()) / height
      except AttributeError: # fallback to Photo API
        height = float(picture.height())
        if height:
          aspect_ratio = Decimal(picture.width()) / height
Tatuya Kamada's avatar
Tatuya Kamada committed
624 625 626 627 628 629
    resize_w = h * aspect_ratio
    resize_h = w / aspect_ratio
    if resize_w < w:
      w = resize_w
    elif resize_h < h:
      h = resize_h
Tatuya Kamada's avatar
Tatuya Kamada committed
630 631 632
    return (str(w) + unit, str(h) + unit)
   
  
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
633 634 635
  def _appendTableByListbox(self,
                            element_tree=None, 
                            listbox=None,
636 637
                            REQUEST=None,
                            iteration_index=0):
638 639 640
    table_id = listbox.id
    table_xpath = '//table:table[@table:name="%s"]' % table_id
    # this list should be one item list
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
641
    target_table_list = element_tree.xpath(table_xpath, namespaces=element_tree.nsmap)
642
    if len(target_table_list) is 0:
643
      return element_tree
644 645 646

    target_table = target_table_list[0]
    newtable = deepcopy(target_table)
647

648 649
    table_header_rows_xpath = '%s/table:table-header-rows' % table_xpath
    table_row_xpath = '%s/table:table-row' % table_xpath
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
650 651
    table_header_rows_list = newtable.xpath(table_header_rows_xpath,  namespaces=element_tree.nsmap)
    table_row_list = newtable.xpath(table_row_xpath,  namespaces=element_tree.nsmap)
652 653 654

    # copy row styles from ODF Document
    has_header_rows = len(table_header_rows_list) > 0
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
655 656
    (row_top, row_middle, row_bottom) = self._copyRowStyle(table_row_list,
                                                           has_header_rows=has_header_rows)
657 658 659 660

    # clear original table 
    parent_paragraph = target_table.getparent()
    target_index = parent_paragraph.index(target_table)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
661
    parent_paragraph.remove(target_table)
662 663 664 665 666 667 668
    # clear rows 
    for table_row in table_row_list:
      newtable.remove(table_row)

    listboxline_list = listbox.get_value('default',
                                         render_format='list',
                                         REQUEST=REQUEST, 
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
669
                                         render_prefix=None)
670
    
671 672
    # if ODF table has header rows, does not update the header rows
    # if does not have header rows, insert the listbox title line
673
    is_top = True
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
674
    last_index = len(listboxline_list) - 1
675 676 677 678
    for (index, listboxline) in enumerate(listboxline_list):
      listbox_column_list = listboxline.getColumnItemList()
      if listboxline.isTitleLine() and not has_header_rows:
        row = deepcopy(row_top)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
679
        row = self._updateColumnValue(row, listbox_column_list)
680 681 682 683
        newtable.append(row)
        is_top = False       
      elif listboxline.isDataLine() and is_top:
        row = deepcopy(row_top)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
684
        row = self._updateColumnValue(row, listbox_column_list)
685 686
        newtable.append(row)
        is_top = False
Tatuya Kamada's avatar
Tatuya Kamada committed
687
      elif listboxline.isStatLine() or (index is last_index and listboxline.isDataLine()):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
688
        row = deepcopy(row_bottom)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
689
        row = self._updateColumnStatValue(row, listbox_column_list, row_middle)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
690
        newtable.append(row)
691 692
      elif index > 0 and listboxline.isDataLine():
        row = deepcopy(row_middle)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
693
        row = self._updateColumnValue(row, listbox_column_list)
694 695
        newtable.append(row)

696 697 698 699
    self._setUniqueElementName(base_name=table_id,
                               iteration_index=iteration_index,
                               xpath=table_xpath,
                               element_tree=newtable)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
700 701
    parent_paragraph.insert(target_index, newtable)
 
702
    return element_tree
703

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
704
  def _copyRowStyle(self, table_row_list=[], has_header_rows=False):
705 706 707 708 709 710
    def removeOfficeAttribute(row):
      if row is None or has_header_rows: return
      odf_cell_list = row.findall("{%s}table-cell" % row.nsmap['table'])
      for odf_cell in odf_cell_list:
        self._removeColumnValue(odf_cell)
          
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    row_top = None
    row_middle = None
    row_bottom = None
    if len(table_row_list) > 0:
      if len(table_row_list) is 1:
        row_top = deepcopy(table_row_list[0])
        row_middle = deepcopy(table_row_list[0])
        row_bottom = deepcopy(table_row_list[0])
      elif len(table_row_list) is 2 and has_header_rows:
        row_top = deepcopy(table_row_list[0])
        row_middle = deepcopy(table_row_list[0])
        row_bottom = deepcopy(table_row_list[-1])
      elif len(table_row_list) is 2 and not has_header_rows:
        row_top = deepcopy(table_row_list[0])
        row_middle = deepcopy(table_row_list[1])
        row_bottom = deepcopy(table_row_list[-1])
      elif len(table_row_list) >= 2:
        row_top = deepcopy(table_row_list[0])
        row_middle = deepcopy(table_row_list[1])
        row_bottom = deepcopy(table_row_list[-1])
731 732 733

    # remove office attribute if create a new header row 
    removeOfficeAttribute(row_top)
734
    return (row_top, row_middle, row_bottom)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
735 736 737

  def _updateColumnValue(self, row=None, listbox_column_list=[]):
    odf_cell_list = row.findall("{%s}table-cell" % row.nsmap['table'])
738 739 740 741 742 743
    odf_cell_list_size = len(odf_cell_list)
    listbox_column_size = len(listbox_column_list)
    for (column_index, column) in enumerate(odf_cell_list):
      if column_index >= listbox_column_size:
        break
      value = listbox_column_list[column_index][1]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
744
      self._setColumnValue(column, value)
745 746
    return row

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
747
  def _updateColumnStatValue(self, row=None, listbox_column_list=[], row_middle=None):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
748
    """stat line is capable of column span setting"""
749 750
    if row_middle is None:
      return row
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
751 752
    odf_cell_list = row.findall("{%s}table-cell" % row.nsmap['table'])
    odf_column_span_list = self._getOdfColumnSpanList(row_middle)
753 754 755 756 757 758
    listbox_column_size = len(listbox_column_list)
    listbox_column_index = 0
    for (column_index, column) in enumerate(odf_cell_list):
      if listbox_column_index >= listbox_column_size:
        break
      value = listbox_column_list[listbox_column_index][1]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
759 760 761 762 763
      self._setColumnValue(column, value)
      column_span = self._getColumnSpanSize(column)
      listbox_column_index = self._nextListboxColumnIndex(column_span,
                                                          listbox_column_index,
                                                          odf_column_span_list)
764 765
    return row

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
766 767
  def _setColumnValue(self, column, value):
    self._clearColumnValue(column)
768
    if value is None:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
769
      self._removeColumnValue(column)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
770 771 772 773 774 775 776 777 778 779 780 781
    column_value, table_content = self._translateValueIntoColumnContent(value, column)
    for child in column.getchildren():
      column.remove(child)
    if table_content is not None:
      column.append(table_content)
    value_attribute = self._getColumnValueAttribute(column)
    if value_attribute is not None and column_value is not None:
       column.set(value_attribute, column_value)

  def _translateValueIntoColumnContent(self, value, column):
    """translate a value as a table content"""
    table_content = None
782 783
    column_children = column.getchildren()
    if len(column_children) > 0:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
      table_content = deepcopy(column_children[0])
    # create a tempolaly etree object to generate a content paragraph
    fragment = self._valueAsOdfXmlElement(value=value, element_tree=column)
    column_value = None
    if table_content is not None:
      table_content.text = fragment.text
      for element in fragment.getchildren():
        table_content.append(element)
      column_value = " ".join([x for x in table_content.itertext()])
    return (column_value, table_content)

  def _valueAsOdfXmlElement(self, value=None, element_tree=None):
    """values as ODF XML element
    
    replacing:
      \t -> tabs
      \n -> line-breaks
      DateTime -> Y-m-d
    """
    if value is None:
      value = ''
    translated_value = str(value)
    if isinstance(value, DateTime):
      translated_value = value.strftime('%Y-%m-%d')
    translated_value = escape(translated_value)
    text_namespace = element_tree.nsmap['text']
    tab_element_str = '<text:tab xmlns:text="%s"/>' % text_namespace
    line_break_element_str ='<text:line-break xmlns:text="%s"/>' % text_namespace
    translated_value = translated_value.replace('\t', tab_element_str)
    translated_value = translated_value.replace('\r', '')
    translated_value = translated_value.replace('\n', line_break_element_str)
    translated_value = unicode(str(translated_value),'utf-8')
    # create a paragraph
    template = '<text:p xmlns:text="%s">%s</text:p>'
    fragment_element_tree = etree.XML(template % (text_namespace, translated_value))
    return fragment_element_tree
  
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
821
  def _removeColumnValue(self, column):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
822 823 824 825 826
    # to eliminate a default value, remove "office:*" attributes.
    # if remaining these attribetes, the column shows its default value,
    # such as '0.0', '$0'
    attrib = column.attrib
    for key in attrib.keys():
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
827
      if key.startswith("{%s}" % column.nsmap['office']):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
828
        del attrib[key]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
829
    column.text = ''
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
830 831 832 833
    column_children = column.getchildren()
    for child in column_children:
      column.remove(child)

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
834
  def _clearColumnValue(self, column):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
835 836
    attrib = column.attrib
    for key in attrib.keys():
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
837
      value_attribute = self._getColumnValueAttribute(column)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
838 839
      if value_attribute is not None:
        column.set(value_attribute, '')
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
840
    column.text = ''
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
841 842
    column_children = column.getchildren()
    for child in column_children:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
843
      # clear data except style
Tatuya Kamada's avatar
Tatuya Kamada committed
844
      style_attribute_tuple = self._getStyleAttributeTuple(child)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
845
      child.clear()
Tatuya Kamada's avatar
Tatuya Kamada committed
846 847
      if style_attribute_tuple is not None:
        child.set(style_attribute_tuple[0], style_attribute_tuple[1])
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
848 849 850 851 852 853

  def _getStyleAttributeTuple(self, element):
    attrib = element.attrib
    for key in attrib.keys():
      if key.endswith('style-name'):
        return (key, attrib[key])
Tatuya Kamada's avatar
Tatuya Kamada committed
854
    return None
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
855
  
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
856
  def _getColumnValueAttribute(self, column):
857 858 859 860 861
    attrib = column.attrib
    for key in attrib.keys():
      if key.endswith("value"):
        return key
    return None
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
862 863 864

  def _getColumnSpanSize(self, column=None):
    span_attribute = "{%s}number-columns-spanned" % column.nsmap['table']
865 866 867 868
    column_span = 1
    if column.attrib.has_key(span_attribute):
      column_span = int(column.attrib[span_attribute])
    return column_span
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
869 870

  def _nextListboxColumnIndex(self, span=0, current_index=0, column_span_list=[]):
871 872 873 874 875 876 877
    hops = 0
    index = current_index
    while hops < span:
      column_span = column_span_list[index]
      hops += column_span
      index += 1
    return index
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
878 879

  def _getOdfColumnSpanList(self, row_middle=None):
880 881
    if row_middle is None:
      return []
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
882
    odf_cell_list = row_middle.findall("{%s}table-cell" % row_middle.nsmap['table'])
883 884
    column_span_list = []
    for column in odf_cell_list:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
885
      column_span = self._getColumnSpanSize(column)
886 887 888
      column_span_list.append(column_span)
    return column_span_list

Tatuya Kamada's avatar
Tatuya Kamada committed
889 890
  def _toUnicodeString(self, field_value = None):
    value = ''
Tatuya Kamada's avatar
Tatuya Kamada committed
891 892 893
    if isinstance(field_value, unicode):
      value = field_value
    elif field_value is not None:
Tatuya Kamada's avatar
Tatuya Kamada committed
894 895 896
      value = unicode(str(field_value), 'utf-8')
    return value

897 898 899
class ODTStrategy(ODFStrategy):
  """ODTStrategy create a ODT Document from a form and a ODT template"""
  pass