FormPrintout.py 45.6 KB
Newer Older
Nicolas Delaby's avatar
Nicolas Delaby committed
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
##############################################################################
#
# 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
26 27
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
# USA.
28 29
##############################################################################
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
30
from Products.CMFCore.utils import _checkPermission
31
from Products.ERP5Type import PropertySheet, Permissions
32 33
from Products.ERP5Form.ListBox import ListBox
from Products.ERP5Form.FormBox import FormBox
34
from Products.ERP5Form.ReportBox import ReportBox
35
from Products.ERP5Form.ImageField import ImageField
36
from Products.ERP5OOo.OOoUtils import OOoBuilder
37
from Products.CMFCore.exceptions import AccessControl_Unauthorized
Tatuya Kamada's avatar
Tatuya Kamada committed
38
from Acquisition import Implicit, aq_base
39
from Products.ERP5Type.Globals import InitializeClass, DTMLFile, Persistent
40 41
from AccessControl import ClassSecurityInfo
from AccessControl.Role import RoleManager
42
from OFS.SimpleItem import Item
43
from OFS.PropertyManager import PropertyManager
Tatuya Kamada's avatar
Tatuya Kamada committed
44
from urllib import quote, quote_plus
45 46 47 48
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
49
from DateTime import DateTime
Tatuya Kamada's avatar
Tatuya Kamada committed
50
from decimal import Decimal
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
51
from xml.sax.saxutils import escape
Tatuya Kamada's avatar
Tatuya Kamada committed
52
import re
53 54 55 56 57 58 59

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

60 61 62 63 64 65

DRAW_URI = 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'
TEXT_URI = 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'
XLINK_URI = 'http://www.w3.org/1999/xlink'
SVG_URI = 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'
TABLE_URI = 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'
66 67
OFFICE_URI = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
STYLE_URI = 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'
68 69 70 71 72 73 74 75


NSMAP = {
          'draw': DRAW_URI,
          'text': TEXT_URI,
          'xlink': XLINK_URI,
          'svg': SVG_URI,
          'table': TABLE_URI,
76 77
          'office': OFFICE_URI,
          'style': STYLE_URI,
78 79 80
        }


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

84 85
def addFormPrintout(self, id, title="", form_name='', template='',
                    REQUEST=None, filename='object/title_or_id'):
86 87 88 89 90 91 92 93 94
  """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
95
  id = self._setObject(id, FormPrintout(id, title, form_name, template, filename))
96 97 98 99 100 101 102 103 104
  # 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:
105
  id -- the id of the object we just added
106 107 108 109 110 111 112 113 114 115
  """
  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
116

117
class FormPrintout(Implicit, Persistent, RoleManager, Item, PropertyManager):
118 119
  """Form Printout

Fabien Morin's avatar
Fabien Morin committed
120 121 122
  FormPrintout is one of a reporting system in ERP5.
  It enables to create a Printout, using an Open Document Format(ODF)
  document as its design, an ERP5Form as its contents.
123

Tatuya Kamada's avatar
Tatuya Kamada committed
124
  The functions status:
Fabien Morin's avatar
Fabien Morin committed
125

Tatuya Kamada's avatar
Tatuya Kamada committed
126 127
  Fields -> Paragraphs:      supported
  ListBox -> Table:          supported
128 129
  Report Section
      -> Frames or Sections: supported
Tatuya Kamada's avatar
Tatuya Kamada committed
130 131 132 133
  FormBox -> Frame:          experimentally supported
  ImageField -> Photo:       supported
  styles.xml:                supported
  meta.xml:                  not supported yet
134
  """
Fabien Morin's avatar
Fabien Morin committed
135

136
  meta_type = "ERP5 Form Printout"
137
  icon = "www/form_printout_icon.png"
138 139 140 141 142 143 144 145

  # Declarative Security
  security = ClassSecurityInfo()

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

146 147 148 149 150 151 152 153 154
  _properties = ( {'id': 'template',
                   'type': 'string',
                   'mode': 'w'},
                  {'id': 'form_name',
                   'type': 'string',
                   'mode': 'w'},
                  {'id': 'filename',
                   'type': 'tales',
                   'mode': 'w',},)
155 156 157 158 159 160 161
  # Constructors
  constructors =   (manage_addFormPrintout, addFormPrintout)

  # Tabs in ZMI
  manage_options = ((
    {'label':'Edit', 'action':'manage_editFormPrintout'},
    {'label':'View', 'action': '' }, ) + Item.manage_options)
Nicolas Delaby's avatar
Nicolas Delaby committed
162

163 164
  security.declareProtected('View management screens', 'manage_editFormPrintout')
  manage_editFormPrintout = PageTemplateFile('www/FormPrintout_manageEdit', globals(),
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
165
                                             __name__='manage_editFormPrintout')
166
  manage_editFormPrintout._owner = None
167 168 169 170

  # alias definition to do 'add_and_edit'
  security.declareProtected('View management screens', 'manage_main')
  manage_main = manage_editFormPrintout
Nicolas Delaby's avatar
Nicolas Delaby committed
171

172 173 174
  # default attributes
  template = None
  form_name = None
175
  filename = 'object/title_or_id'
176

177 178
  def __init__(self, id, title='', form_name='', template='',
               filename='object/title_or_id'):
179 180 181 182 183 184 185
    """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
186 187
    filename -- Tales expression which return the filename of
    downloadable file.
188 189 190 191 192
    """
    self.id = id
    self.title = title
    self.form_name = form_name
    self.template = template
193
    self.filename = filename
194

195 196 197 198
  security.declareProtected(Permissions.AccessContentsInformation, 'SearchableText')
  def SearchableText(self):
    return ' '.join((self.id, self.title, self.form_name, self.template, self.filename))

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
199
  security.declareProtected('View', 'index_html')
200 201
  def index_html(self, REQUEST, RESPONSE=None, template_relative_url=None,
                 format=None, batch_mode=False):
202 203 204 205 206 207
    """Render and view a printout document.

    format: conversion format requested by User.
            take precedence of format in REQUEST
    batch_mode: if True then avoid overriding response headers.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
208

209 210 211 212 213 214 215 216
    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)
217 218 219 220 221 222
    if template_relative_url:
      printout_template = obj.getPortalObject().\
                                      restrictedTraverse(template_relative_url)
    elif self.template:
      printout_template = getattr(obj, self.template)
    else:
223 224 225 226 227
      raise ValueError, 'Can not create a ODF Document without a printout template'

    report_method = None
    if hasattr(form, 'report_method'):
      report_method = getattr(obj, form.report_method)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
228 229 230 231 232
    extra_context = dict(container=container,
                         printout_template=printout_template,
                         report_method=report_method,
                         form=form,
                         here=obj)
233 234 235 236
    # Never set value when rendering! If you do, then every time
    # writing occur and it creates conflict error which kill ERP5
    # scalability! To get acquisition, you just have to call __of__.
    # Also frequent writing make data.fs very huge so quickly.
237
    content_type = printout_template.content_type
238 239
    strategy = self._createStrategy(content_type).__of__(self)
    printout = strategy.render(extra_context=extra_context)
240
    return self._oooConvertByFormat(printout, content_type,
241 242
                                    extra_context, REQUEST, 
                                    format, batch_mode)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
243

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
244 245
  security.declareProtected('View', '__call__')
  __call__ = index_html
Nicolas Delaby's avatar
Nicolas Delaby committed
246

247
  security.declareProtected('Manage properties', 'doSettings')
248 249
  def doSettings(self, REQUEST, title='', form_name='', template='', filename='object/title_or_id'):
    """Change title, form_name, template, filename."""
250 251 252 253 254
    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
255
    self.filename = filename
256 257 258 259 260 261
    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
262
  def _createStrategy(slef, content_type=''):
263 264
    if guess_extension(content_type) == '.odt':
      return ODTStrategy()
265 266 267
    if guess_extension(content_type) == '.odg':
      return ODGStrategy()
    raise ValueError, 'Template type: %s is not supported' % content_type
268

269 270
  def _oooConvertByFormat(self, printout, content_type, extra_context,
                          REQUEST, format, batch_mode):
271 272 273 274 275 276 277 278
    """
    Convert the ODF document into the given format.

    Keyword arguments:
    printout -- ODF document
    content_type -- the content type of the printout
    extra_context -- extra_context including a format
    REQUEST -- Request object
279 280
    format -- requested output format
    batch_mode -- Disable headers overriding
281
    """
282
    if REQUEST is not None and not format:
283
      format = REQUEST.get('format', None)
284
    filename = self.getProperty('filename')
285 286 287 288 289 290 291 292 293 294 295 296 297
    # Call refresh through cloudooo
    # XXX This is a temporary implementation:
    # Calling a webservice must be done through a WebServiceMethod
    # and a WebServiceConnection
    from Products.ERP5OOo.Document.OOoDocument import OOoServerProxy, enc, dec
    server_proxy = OOoServerProxy(self)
    extension = guess_extension(content_type).strip('.')
    printout = dec(server_proxy.convertFile(enc(printout),
                                        extension, # source_format
                                        extension, # destination_format
                                        False, # zip
                                        True)) # refresh
    # End of temporary implementation
298 299
    if not format:
      if REQUEST is not None and not batch_mode:
300
        REQUEST.RESPONSE.setHeader('Content-Length', len(printout))
301
        REQUEST.RESPONSE.setHeader('Content-Type','%s' % content_type)
302
        REQUEST.RESPONSE.setHeader('Content-disposition',
303 304
                                   'inline;filename="%s%s"' % \
                                     (filename, guess_extension(content_type) or ''))
305 306 307
      return printout
    from Products.ERP5Type.Document import newTempOOoDocument
    tmp_ooo = newTempOOoDocument(self, self.title_or_id())
308
    tmp_ooo.edit(data=printout,
309
                 base_data=printout,
310
                 filename=self.title_or_id(),
311 312
                 content_type=content_type,
                 base_content_type=content_type)
313
    mime, data = tmp_ooo.convert(format)
314
    if REQUEST is not None and not batch_mode:
315
      REQUEST.RESPONSE.setHeader('Content-Length', len(data))
316 317
      REQUEST.RESPONSE.setHeader('Content-type', mime)
      REQUEST.RESPONSE.setHeader('Content-disposition',
318
          'attachment;filename="%s.%s"' % (filename, format))
319
    return str(data)
320

321 322 323 324
InitializeClass(FormPrintout)

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

Tatuya Kamada's avatar
Tatuya Kamada committed
326
  odf_existent_name_list = []
Nicolas Delaby's avatar
Nicolas Delaby committed
327

328
  def render(self, extra_context={}):
329
    """Render a odf document, form as a content, template as a template.
330 331

    Keyword arguments:
332
    extra_context -- a dictionary, expected:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
333 334 335 336
      '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
337 338 339 340 341
    """
    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']
342 343
    if not extra_context.has_key('printout_template') or \
        extra_context['printout_template'] is None:
344 345 346
      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
347

348
    # First, render the Template if it has a pt_render method
349 350 351 352
    ooo_document = None
    if hasattr(odf_template, 'pt_render'):
      ooo_document = odf_template.pt_render(here, extra_context=extra_context)
    else:
353
      # File object can be a template
354
      ooo_document = odf_template
355 356 357

    # Create a new builder instance
    ooo_builder = OOoBuilder(ooo_document)
Tatuya Kamada's avatar
Tatuya Kamada committed
358
    self.odf_existent_name_list = ooo_builder.getNameList()
Nicolas Delaby's avatar
Nicolas Delaby committed
359

360
    # content.xml
361
    self._replaceContentXml(ooo_builder, extra_context)
362
    # styles.xml
363
    self._replaceStylesXml(ooo_builder, extra_context)
364
    # meta.xml is not supported yet
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
365 366
    # ooo_builder = self._replaceMetaXml(ooo_builder=ooo_builder, extra_context=extra_context)

367
    # Update the META information
368 369
    ooo_builder.updateManifest()

370
    ooo = ooo_builder.render()
371 372
    return ooo

373
  def _replaceContentXml(self, ooo_builder, extra_context):
374 375 376
    """
    Replace the content.xml in an ODF document using an ERP5Form data.
    """
377
    content_xml = ooo_builder.extract('content.xml')
378 379 380 381
    # mapping ERP5Form to ODF
    form = extra_context['form']
    here = getattr(self, 'aq_parent', None)

382
    content_element_tree = etree.XML(content_xml)
383 384
    self._replaceXmlByForm(content_element_tree, form, here, extra_context,
                           ooo_builder)
385
    # mapping ERP5Report report method to ODF
386
    report_method=extra_context.get('report_method')
387 388 389
    base_name = getattr(report_method, '__name__', None)
    self._replaceXmlByReportSection(content_element_tree, extra_context,
                                    report_method, base_name, ooo_builder)
Nicolas Delaby's avatar
Nicolas Delaby committed
390

391
    content_xml = etree.tostring(content_element_tree, encoding='utf-8')
392
    # Replace content.xml in master openoffice template
393
    ooo_builder.replace('content.xml', content_xml)
394 395

  # this method not supported yet
396
  def _replaceStylesXml(self, ooo_builder, extra_context):
397
    """
398
    Replace the styles.xml file in an ODF document.
399
    """
400
    styles_xml = ooo_builder.extract('styles.xml')
401 402
    form = extra_context['form']
    here = getattr(self, 'aq_parent', None)
403
    styles_element_tree = etree.XML(styles_xml)
404 405
    self._replaceXmlByForm(styles_element_tree, form, here, extra_context,
                           ooo_builder)
Tatuya Kamada's avatar
Tatuya Kamada committed
406
    styles_xml = etree.tostring(styles_element_tree, encoding='utf-8')
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
407

408
    ooo_builder.replace('styles.xml', styles_xml)
409 410

  # this method not implemented yet
411
  def _replaceMetaXml(self, ooo_builder, extra_context):
412
    """
413
    Replace meta.xml file in an ODF document.
414 415 416
    """
    return ooo_builder

417 418
  def _replaceXmlByForm(self, element_tree, form, here, extra_context,
                        ooo_builder, iteration_index=0):
419 420 421 422 423 424 425 426 427 428
    """
    Replace an element_tree object using an ERP5 form.

    Keyword arguments:
    element_tree -- the element_tree of a XML file in an ODF document.
    form -- an ERP5 form
    here -- called context
    extra_context -- extra_context
    ooo_builder -- the OOoBuilder object which have an ODF document.
    iteration_index -- the index which is used when iterating the group of items using ReportSection.
Nicolas Delaby's avatar
Nicolas Delaby committed
429

430
    Need to be overloaded in OD?Strategy Class
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
431
    """
432
    raise NotImplementedError
Nicolas Delaby's avatar
Nicolas Delaby committed
433

434 435
  def _replaceXmlByReportSection(self, element_tree, extra_context, report_method,
                                 base_name, ooo_builder):
436 437 438 439 440
    """
    Replace xml using ERP5Report ReportSection.
    Keyword arguments:
    element_tree -- the element tree object which have an xml document in an ODF document.
    extra_context -- the extra context
Fabien Morin's avatar
Fabien Morin committed
441 442
    report_method -- the report method object which is used in an ReportBox
    base_name -- the name of a ReportBox field which is used to specify the target
443 444
    ooo_builder -- the OOo Builder object which has ODF document.
    """
445
    if report_method is None:
446
      return
447 448
    report_section_list = report_method()
    portal_object = self.getPortalObject()
Tatuya Kamada's avatar
Tatuya Kamada committed
449

450
    target_tuple = self._pickUpTargetSection(base_name=base_name,
451 452 453
                                             report_section_list=report_section_list,
                                             element_tree=element_tree)
    if target_tuple is None:
454
      return
455 456 457 458
    target_xpath, original_target = target_tuple
    office_body = original_target.getparent()
    target_index = office_body.index(original_target)
    temporary_element_tree = deepcopy(original_target)
459
    for (index, report_item) in enumerate(report_section_list):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
460
      report_item.pushReport(portal_object, render_prefix=None)
461 462 463
      here = report_item.getObject(portal_object)
      form_id = report_item.getFormId()
      form = getattr(here, form_id)
Nicolas Delaby's avatar
Nicolas Delaby committed
464

465
      target_element_tree = deepcopy(temporary_element_tree)
466
      # remove original target in the ODF template
467
      if index == 0:
468
        office_body.remove(original_target)
Tatuya Kamada's avatar
Tatuya Kamada committed
469
      else:
470
        self._setUniqueElementName(base_name=base_name,
471
                                   iteration_index=index,
472 473 474
                                   xpath=target_xpath,
                                   element_tree=target_element_tree)

475 476
      self._replaceXmlByForm(target_element_tree, form, here, extra_context,
                             ooo_builder, iteration_index=index)
477 478
      office_body.insert(target_index, target_element_tree)
      target_index += 1
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
479
      report_item.popReport(portal_object, render_prefix=None)
480

481
  def _pickUpTargetSection(self, base_name='', report_section_list=[], element_tree=None):
482
    """pick up a ODF target object to iterate ReportSection
483
    base_name -- the target name to replace in an ODF document
484 485 486
    report_section_list -- ERP5Form ReportSection List which was created by a report method
    element_tree -- XML ElementTree object
    """
487
    frame_xpath = '//draw:frame[@draw:name="%s"]' % base_name
488 489
    frame_list = element_tree.xpath(frame_xpath, namespaces=element_tree.nsmap)
    # <text:section text:style-name="Sect2" text:name="Section2">
490
    section_xpath = '//text:section[@text:name="%s"]' % base_name
491
    section_list = element_tree.xpath(section_xpath, namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
492 493
    if not frame_list and not section_list:
      return
494 495 496 497

    office_body = None
    original_target = None
    target_xpath = ''
Nicolas Delaby's avatar
Nicolas Delaby committed
498
    if frame_list:
499 500 501
      frame = frame_list[0]
      original_target = frame.getparent()
      target_xpath = frame_xpath
Nicolas Delaby's avatar
Nicolas Delaby committed
502
    elif section_list:
503 504 505 506
      original_target = section_list[0]
      target_xpath = section_xpath
    office_body = original_target.getparent()
    # remove if no report section
Nicolas Delaby's avatar
Nicolas Delaby committed
507
    if not report_section_list:
508
      office_body.remove(original_target)
Nicolas Delaby's avatar
Nicolas Delaby committed
509
      return
Nicolas Delaby's avatar
Nicolas Delaby committed
510

511
    return (target_xpath, original_target)
Nicolas Delaby's avatar
Nicolas Delaby committed
512

513 514 515 516 517 518 519 520 521
  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
    """
522
    if iteration_index == 0:
Tatuya Kamada's avatar
Tatuya Kamada committed
523
      return
524
    def getNameAttribute(target_element):
525 526 527 528 529 530 531
      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)
532
    if not result_list:
533 534 535
      return
    target_element = result_list[0]
    name_attribute = getNameAttribute(target_element)
Nicolas Delaby's avatar
Nicolas Delaby committed
536
    if name_attribute:
537
      target_element.set(name_attribute, odf_element_name)
Nicolas Delaby's avatar
Nicolas Delaby committed
538

539 540
  def _replaceXmlByFormbox(self, element_tree, field, form, extra_context,
                           ooo_builder, iteration_index=0):
541 542
    """
    Replace an ODF frame using an ERP5Form form box field.
543

544
    Note: This method is incompleted yet. This function is intended to
Fabien Morin's avatar
Fabien Morin committed
545
    make an frame hide/show. But it has not such a feature currently.
546
    """
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
547 548
    field_id = field.id
    enabled = field.get_value('enabled')
549
    draw_xpath = '//draw:frame[@draw:name="%s"]/draw:text-box/*' % field_id
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
550
    text_list = element_tree.xpath(draw_xpath, namespaces=element_tree.nsmap)
551 552
    if not text_list:
      return
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
553 554 555 556 557
    target_element = text_list[0]
    frame_paragraph = target_element.getparent()
    office_body = frame_paragraph.getparent()
    if not enabled:
      office_body.remove(frame_paragraph)
558
      return
559
    # set when using report section
560 561 562 563 564
    self._setUniqueElementName(field_id, iteration_index, draw_xpath, element_tree)
    self._replaceXmlByForm(frame_paragraph, form, extra_context['here'], extra_context,
                           ooo_builder, iteration_index=iteration_index)

  def _replaceXmlByImageField(self, element_tree, image_field, ooo_builder, iteration_index=0):
565 566 567
    """
    Replace an ODF draw:frame using an ERP5Form image field.
    """
568 569
    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
570
    image_list = element_tree.xpath(image_xpath, namespaces=element_tree.nsmap)
571 572
    if not image_list:
      return
Tatuya Kamada's avatar
Tatuya Kamada committed
573
    path = image_field.get_value('default')
574 575
    image_node = image_list[0]
    image_frame = image_node.getparent()
Tatuya Kamada's avatar
Tatuya Kamada committed
576 577
    if path is not None:
      path = path.encode()
Tatuya Kamada's avatar
Tatuya Kamada committed
578
    picture = self.getPortalObject().restrictedTraverse(path)
Tatuya Kamada's avatar
Tatuya Kamada committed
579
    picture_data = getattr(aq_base(picture), 'data', None)
580 581 582
    if picture_data is None:
      image_frame = image_node.getparent()
      image_frame.remove(image_node)
583
      return
Tatuya Kamada's avatar
Tatuya Kamada committed
584 585 586
    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)
587 588 589 590
    width, height = self._getPictureSize(picture, image_frame)
    image_node.set('{%s}href' % XLINK_URI, picture_path)
    image_frame.set('{%s}width' % SVG_URI, str(width))
    image_frame.set('{%s}height' % SVG_URI, str(height))
591
    # set when using report section
592
    self._setUniqueElementName(image_field.id, iteration_index, image_xpath, element_tree)
593

Tatuya Kamada's avatar
Tatuya Kamada committed
594 595
  def _createOdfUniqueFileName(self, path='', picture_type=''):
    extension = guess_extension(picture_type)
596 597 598
    # here, it's needed to use quote_plus to escape '/' caracters to make valid
    # paths in the odf archive.
    picture_path = 'Pictures/%s%s' % (quote_plus(path), extension)
Tatuya Kamada's avatar
Tatuya Kamada committed
599 600 601 602
    if picture_path not in self.odf_existent_name_list:
      return picture_path
    number = 0
    while True:
603
      picture_path = 'Pictures/%s_%s%s' % (quote_plus(path), number, extension)
Tatuya Kamada's avatar
Tatuya Kamada committed
604 605 606 607
      if picture_path not in self.odf_existent_name_list:
        return picture_path
      number += 1

608 609 610 611
  # XXX this method should not be used anymore. This should be made by the
  # render_od*
  def _getPictureSize(self, picture=None, draw_frame_node=None):
    if picture is None or draw_frame_node is None:
Tatuya Kamada's avatar
Tatuya Kamada committed
612
      return ('0cm', '0cm')
613 614
    svg_width = draw_frame_node.attrib.get('{%s}width' % SVG_URI)
    svg_height = draw_frame_node.attrib.get('{%s}height' % SVG_URI)
Tatuya Kamada's avatar
Tatuya Kamada committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    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
635 636 637 638 639 640
    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
641
    return (str(w) + unit, str(h) + unit)
Nicolas Delaby's avatar
Nicolas Delaby committed
642 643


644
  def _appendTableByListbox(self, element_tree, listbox, REQUEST, iteration_index=0):
645 646 647
    """
    Append a ODF table using an ERP5 Form listbox.
    """
648 649 650
    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
651
    target_table_list = element_tree.xpath(table_xpath, namespaces=element_tree.nsmap)
652
    if not target_table_list:
653
      return element_tree
654 655 656

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

658 659
    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
660
    table_header_rows_list = newtable.xpath(table_header_rows_xpath,  namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
661
    table_row_list = newtable.xpath(table_row_xpath, namespaces=element_tree.nsmap)
662 663 664

    # copy row styles from ODF Document
    has_header_rows = len(table_header_rows_list) > 0
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
665 666
    (row_top, row_middle, row_bottom) = self._copyRowStyle(table_row_list,
                                                           has_header_rows=has_header_rows)
667 668
    # create style-name and table-row dictionary if a reference name is set
    style_name_row_dictionary = self._createStyleNameRowDictionary(table_row_list)
Fabien Morin's avatar
Fabien Morin committed
669
    # clear original table
670
    parent_paragraph = target_table.getparent()
Fabien Morin's avatar
Fabien Morin committed
671
    # clear rows
Nicolas Delaby's avatar
Nicolas Delaby committed
672
    [newtable.remove(table_row) for table_row in table_row_list]
673 674 675

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

704
    self._setUniqueElementName(table_id, iteration_index, table_xpath, newtable)
Nicolas Delaby's avatar
Nicolas Delaby committed
705
    parent_paragraph.replace(target_table, newtable)
Nicolas Delaby's avatar
Nicolas Delaby committed
706

707
  def _copyRowStyle(self, table_row_list=None, has_header_rows=False):
708 709 710
    """
    Copy ODF table row styles.
    """
711 712
    if table_row_list is None:
      table_row_list = []
713 714
    def removeOfficeAttribute(row):
      if row is None or has_header_rows: return
715
      odf_cell_list = row.findall("{%s}table-cell" % TABLE_URI)
716 717
      for odf_cell in odf_cell_list:
        self._removeColumnValue(odf_cell)
Nicolas Delaby's avatar
Nicolas Delaby committed
718

719 720 721
    row_top = None
    row_middle = None
    row_bottom = None
Nicolas Delaby's avatar
Nicolas Delaby committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    len_table_row_list = len(table_row_list)
    if len_table_row_list == 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 == 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 == 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])
739

Fabien Morin's avatar
Fabien Morin committed
740
    # remove office attribute if create a new header row
741
    removeOfficeAttribute(row_top)
742
    return (row_top, row_middle, row_bottom)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
743

744

Nicolas Delaby's avatar
Nicolas Delaby committed
745
  def _createStyleNameRowDictionary(self, table_row_list):
746 747 748
    """create stylename and table row dictionary if a style name reference is set"""
    style_name_row_dictionary = {}
    for table_row in table_row_list:
Nicolas Delaby's avatar
Nicolas Delaby committed
749
      reference_element = table_row.find('.//*[@%s]' % self._name_attribute_name)
750
      if reference_element is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
751
        name = reference_element.attrib[self._name_attribute_name]
752 753
        style_name_row_dictionary[name] = deepcopy(table_row)
    return style_name_row_dictionary
Nicolas Delaby's avatar
Nicolas Delaby committed
754

Nicolas Delaby's avatar
Nicolas Delaby committed
755
  def _updateColumnValue(self, row, listbox_column_list):
756
    odf_cell_list = row.findall("{%s}table-cell" % TABLE_URI)
757 758 759 760 761 762
    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
763
      self._setColumnValue(column, value)
764

Nicolas Delaby's avatar
Nicolas Delaby committed
765
  def _updateColumnStatValue(self, row, listbox_column_list, row_middle):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
766
    """stat line is capable of column span setting"""
767
    if row_middle is None:
Nicolas Delaby's avatar
Nicolas Delaby committed
768
      return
769
    odf_cell_list = row.findall("{%s}table-cell" % TABLE_URI)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
770
    odf_column_span_list = self._getOdfColumnSpanList(row_middle)
771 772 773 774 775 776
    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
777 778 779 780 781
      self._setColumnValue(column, value)
      column_span = self._getColumnSpanSize(column)
      listbox_column_index = self._nextListboxColumnIndex(column_span,
                                                          listbox_column_index,
                                                          odf_column_span_list)
782

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
783 784
  def _setColumnValue(self, column, value):
    self._clearColumnValue(column)
785
    if value is None:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
786
      self._removeColumnValue(column)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
787
    column_value, table_content = self._translateValueIntoColumnContent(value, column)
Nicolas Delaby's avatar
Nicolas Delaby committed
788
    [column.remove(child) for child in column]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
789 790 791 792 793 794 795 796 797
    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
Nicolas Delaby's avatar
Nicolas Delaby committed
798 799
    if len(column):
      table_content = deepcopy(column[0])
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
800 801 802 803 804
    # 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
Nicolas Delaby's avatar
Nicolas Delaby committed
805
      for element in fragment:
Nicolas Delaby's avatar
Nicolas Delaby committed
806 807
        table_content.append(element)
      column_value = " ".join(table_content.itertext())
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
808 809 810 811
    return (column_value, table_content)

  def _valueAsOdfXmlElement(self, value=None, element_tree=None):
    """values as ODF XML element
Nicolas Delaby's avatar
Nicolas Delaby committed
812

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
813 814 815 816 817 818 819 820 821 822 823
    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)
824 825
    tab_element_str = '<text:tab xmlns:text="%s"/>' % TEXT_URI
    line_break_element_str ='<text:line-break xmlns:text="%s"/>' % TEXT_URI
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
826 827 828 829 830 831
    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>'
832
    fragment_element_tree = etree.XML(template % (TEXT_URI, translated_value))
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
833
    return fragment_element_tree
Nicolas Delaby's avatar
Nicolas Delaby committed
834

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
835
  def _removeColumnValue(self, column):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
836 837 838 839 840
    # 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():
841
      if 'office' in column.nsmap and key.startswith("{%s}" % column.nsmap['office']):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
842
        del attrib[key]
Nicolas Delaby's avatar
Nicolas Delaby committed
843 844
    column.text = None
    [column.remove(child) for child in column]
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
845

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
846
  def _clearColumnValue(self, column):
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
847 848
    attrib = column.attrib
    for key in attrib.keys():
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
849
      value_attribute = self._getColumnValueAttribute(column)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
850 851
      if value_attribute is not None:
        column.set(value_attribute, '')
Nicolas Delaby's avatar
Nicolas Delaby committed
852 853
    column.text = None
    for child in column:
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
854
      # clear data except style
Nicolas Delaby's avatar
Nicolas Delaby committed
855
      style_value = child.attrib.get(self._style_attribute_name)
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
856
      child.clear()
Nicolas Delaby's avatar
Nicolas Delaby committed
857
      if style_value:
Nicolas Delaby's avatar
Nicolas Delaby committed
858
        child.set(self._style_attribute_name, style_value)
Nicolas Delaby's avatar
Nicolas Delaby committed
859

Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
860
  def _getColumnValueAttribute(self, column):
861 862 863 864 865
    attrib = column.attrib
    for key in attrib.keys():
      if key.endswith("value"):
        return key
    return None
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
866 867

  def _getColumnSpanSize(self, column=None):
868
    span_attribute = "{%s}number-columns-spanned" % TABLE_URI
Nicolas Delaby's avatar
Nicolas Delaby committed
869
    return int(column.attrib.get(span_attribute, 1))
Tatuya Kamada's avatar
* Fix  
Tatuya Kamada committed
870 871

  def _nextListboxColumnIndex(self, span=0, current_index=0, column_span_list=[]):
872 873 874 875 876 877 878
    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
879 880

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

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

898 899
class ODTStrategy(ODFStrategy):
  """ODTStrategy create a ODT Document from a form and a ODT template"""
Nicolas Delaby's avatar
Nicolas Delaby committed
900 901

  _style_attribute_name = '{urn:oasis:names:tc:opendocument:xmlns:text:1.0}style-name'
Nicolas Delaby's avatar
Nicolas Delaby committed
902
  _name_attribute_name = '{urn:oasis:names:tc:opendocument:xmlns:text:1.0}name'
Nicolas Delaby's avatar
Nicolas Delaby committed
903

904 905
  def _replaceXmlByForm(self, element_tree, form, here, extra_context,
                        ooo_builder, iteration_index=0):
906 907 908 909 910 911 912 913 914 915 916
    """
    Replace an element_tree object using an ERP5 form.

    Keyword arguments:
    element_tree -- the element_tree of a XML file in an ODF document.
    form -- an ERP5 form
    here -- called context
    extra_context -- extra_context
    ooo_builder -- the OOoBuilder object which have an ODF document.
    iteration_index -- the index which is used when iterating the group of items using ReportSection.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
917
    field_list = form.get_fields()
918
    REQUEST = here.REQUEST
919 920
    for (count, field) in enumerate(field_list):
      if isinstance(field, ListBox):
921 922
        self._appendTableByListbox(element_tree, field, REQUEST,
                                   iteration_index=iteration_index)
923 924 925 926
      elif isinstance(field, FormBox):
        if not hasattr(here, field.get_value('formbox_target_id')):
          continue
        sub_form = getattr(here, field.get_value('formbox_target_id'))
927 928
        content = self._replaceXmlByFormbox(element_tree, field, sub_form,
                                            extra_context, ooo_builder,
929 930 931
                                            iteration_index=iteration_index)
      elif isinstance(field, ReportBox):
         report_method = getattr(field, field.get_value('report_method'), None)
932 933
         self._replaceXmlByReportSection(element_tree, extra_context,
                                         report_method, field.id, ooo_builder)
934
      elif isinstance(field, ImageField):
935 936
        self._replaceXmlByImageField(element_tree, field,
                                     ooo_builder, iteration_index=iteration_index)
937
      else:
938
        self._replaceNodeViaReference(element_tree, field)
939

940
  def _replaceNodeViaReference(self, element_tree, field):
941
    """replace nodes (e.g. paragraphs) via ODF reference"""
942 943
    self._replaceNodeViaRangeReference(element_tree, field)
    self._replaceNodeViaPointReference(element_tree, field)
944
    self._replaceNodeViaFormName(element_tree, field)
945
    self._replaceNodeViaVariable(element_tree, field)
946

947
  def _replaceNodeViaPointReference(self, element_tree, field, iteration_index=0):
948 949 950 951 952 953 954 955
    """Replace text node via an ODF point reference.

    point reference example:
     <text:reference-mark text:name="invoice-date"/>
    """
    field_id = field.id
    reference_xpath = '//text:reference-mark[@text:name="%s"]' % field_id
    reference_list = element_tree.xpath(reference_xpath, namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
956 957 958 959 960 961
    for target_node in reference_list:
      node_to_replace = target_node.xpath('ancestor::text:p[1]', namespaces=element_tree.nsmap)[0]
      attr_dict = {}
      style_value = node_to_replace.attrib.get(self._style_attribute_name)
      if style_value:
        attr_dict.update({self._style_attribute_name: style_value})
962
      new_node = field.render_odt(as_string=False, attr_dict=attr_dict)
Nicolas Delaby's avatar
Nicolas Delaby committed
963
      node_to_replace.getparent().replace(node_to_replace, new_node)
964 965 966 967 968 969
    # set when using report section
    self._setUniqueElementName(base_name=field.id,
                               iteration_index=iteration_index,
                               xpath=reference_xpath,
                               element_tree=element_tree)

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
  def _replaceNodeViaVariable(self, element_tree, field, iteration_index=0):
    """Replace text node via an ODF variable name.
    <text:variable-set text:name="my_title" 
                    office:value-type="string">Title</text:variable-set>
    """
    field_id = field.id
    reference_xpath = '//text:variable-set[@text:name="%s"]' % field_id
    node_list = element_tree.xpath(reference_xpath,
                                   namespaces=element_tree.nsmap)
    for target_node in node_list:
      attr_dict = {}
      style_attribute_id = '{%s}data-style-name' % STYLE_URI
      style_value = target_node.attrib.get(style_attribute_id)
      if style_value:
        attr_dict.update({style_attribute_id: style_value})
985 986 987 988
      display_attribute_id = '{%s}display' % TEXT_URI
      display_value = target_node.attrib.get(display_attribute_id)
      if display_value:
        attr_dict.update({display_attribute_id: display_value})
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
      formula_attribute_id = '{%s}formula' % TEXT_URI
      formula_value = target_node.attrib.get(formula_attribute_id)
      if formula_value:
        attr_dict.update({formula_attribute_id: formula_value})
      name_attribute_id = '{%s}name' % TEXT_URI
      attr_dict[name_attribute_id] = target_node.get(name_attribute_id)
      value_type_attribute_id = '{%s}value-type' % OFFICE_URI
      attr_dict[value_type_attribute_id] = target_node.get(
                                                       value_type_attribute_id)
      new_node = field.render_odt_variable(as_string=False,
                                           attr_dict=attr_dict)
      target_node.getparent().replace(target_node, new_node)
    # set when using report section
    self._setUniqueElementName(base_name=field_id,
                               iteration_index=iteration_index,
                               xpath=reference_xpath,
                               element_tree=element_tree)

1007
  def _replaceNodeViaRangeReference(self, element_tree, field, iteration_index=0):
1008 1009 1010 1011 1012
    """Replace text node via an ODF ranged reference.

    range reference example:
    <text:reference-mark-start text:name="week"/>Monday<text:reference-mark-end text:name="week"/>
    or
Nicolas Delaby's avatar
Nicolas Delaby committed
1013 1014
    <text:reference-mark-start text:name="my_title"/>
      <text:span text:style-name="T1">title</text:span>
1015 1016 1017
    <text:reference-mark-end text:name="my_title"/>

    """
Nicolas Delaby's avatar
Nicolas Delaby committed
1018
    field_id = field.id
1019 1020
    range_reference_xpath = '//text:reference-mark-start[@text:name="%s"]' % (field_id,)
    node_to_remove_list_xpath = '//text:reference-mark-start[@text:name="%s"]/'\
Nicolas Delaby's avatar
Nicolas Delaby committed
1021 1022
                            'following-sibling::*[node()/'\
                            'following::text:reference-mark-end[@text:name="%s"]]' % (field_id, field_id)
1023
    node_to_remove_list = element_tree.xpath(node_to_remove_list_xpath, namespaces=element_tree.nsmap)
1024
    reference_list = element_tree.xpath(range_reference_xpath, namespaces=element_tree.nsmap)
Nicolas Delaby's avatar
Nicolas Delaby committed
1025
    if not reference_list:
1026
      return element_tree
1027
    referenced_node = reference_list[0]
1028
    referenced_node.tail = None
1029
    parent_node = referenced_node.getparent()
1030
    text_reference_position = parent_node.index(referenced_node)
Nicolas Delaby's avatar
Nicolas Delaby committed
1031 1032 1033 1034

    #Delete all contents between <text:reference-mark-start/> and <text:reference-mark-end/>
    #Try to fetch style-name
    attr_dict = {}
1035
    [(attr_dict.update(target_node.attrib), parent_node.remove(target_node)) for target_node in node_to_remove_list]
1036 1037
    new_node = field.render_odt(local_name='span', attr_dict=attr_dict,
                                as_string=False)
Nicolas Delaby's avatar
Nicolas Delaby committed
1038
    parent_node.insert(text_reference_position+1, new_node)
1039 1040 1041 1042 1043
    # set when using report section
    self._setUniqueElementName(base_name=field.id,
                               iteration_index=iteration_index,
                               xpath=range_reference_xpath,
                               element_tree=element_tree)
1044

1045 1046 1047 1048 1049 1050
  def _replaceNodeViaFormName(self, element_tree, field, iteration_index=0):
    """
    Used to replace field in ODT document like checkboxes
    """
    field_id = field.id
    reference_xpath = '//*[@form:name = "%s"]' % field_id
1051 1052 1053 1054
    # if form name space is not in the name space dict of element tree,
    # it means that there is no form in the tree. Then do nothing and return.
    if not 'form' in element_tree.nsmap:
      return
1055 1056 1057 1058
    reference_list = element_tree.xpath(reference_xpath, namespaces=element_tree.nsmap)
    for target_node in reference_list:
      attr_dict = {}
      attr_dict.update(target_node.attrib)
1059
      new_node = field.render_odt(as_string=False, attr_dict=attr_dict)
1060 1061
      target_node.getparent().replace(target_node, new_node)

1062 1063 1064
class ODGStrategy(ODFStrategy):
  """ODGStrategy create a ODG Document from a form and a ODG template"""

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  def _recursiveGetAttributeDict(self, node, attr_dict):
    '''return a dictionnary corresponding with node attributes. Tag as key
       and a list corresponding to the atributes values by apparence order.
       Example, for a listbox, you will have something like :
       { tabe.tag: [table.attrib,],
         row.tag: [row.attrib,
                   row.attrib],
         cell.tag: [cell.attrib,
                    cell.attrib,
                    cell.attrib,
                    cell.attrib,
                    cell.attrib,
                    cell.attrib,],

    '''
    attr_dict.setdefault(node.tag, []).append(dict(node.attrib))
    for child in node:
      self._recursiveGetAttributeDict(child, attr_dict)

  def _recursiveApplyAttributeDict(self, node, attr_dict):
    '''recursively apply given attributes to node
    '''
    image_tag_name = '{%s}%s' % (DRAW_URI, 'image')
    if len(attr_dict[node.tag]):
      attribute_to_update_dict = attr_dict[node.tag].pop(0)
      # in case of images, we don't want to update image path
      # because they were calculated by render_odg
      if node.tag != image_tag_name:
        node.attrib.update(attribute_to_update_dict)
    for child in node:
      self._recursiveApplyAttributeDict(child, attr_dict)

Fabien Morin's avatar
Fabien Morin committed
1097 1098
  def _replaceXmlByForm(self, element_tree, form, here, extra_context,
                        ooo_builder, iteration_index=0):
Nicolas Delaby's avatar
Nicolas Delaby committed
1099
    field_list = form.get_fields()
1100
    for (count, field) in enumerate(field_list):
1101
      text_xpath = '//draw:frame[@draw:name="%s"]' % field.id
1102
      node_list = element_tree.xpath(text_xpath, namespaces=element_tree.nsmap)
1103
      value = field.get_value('default')
1104 1105
      if isinstance(value, str):
        value = value.decode('utf-8')
Fabien Morin's avatar
Fabien Morin committed
1106
      for target_node in node_list:
1107
        # render the field in odg xml node format
1108 1109 1110 1111 1112
        attr_dict = {}
        self._recursiveGetAttributeDict(target_node, attr_dict)
        new_node = field.render_odg(value=value, as_string=False, ooo_builder=ooo_builder,
            REQUEST=self.REQUEST, attr_dict=attr_dict)

1113
        if new_node is not None:
1114
          # replace the target node by the generated node
1115 1116 1117 1118
          target_node.getparent().replace(target_node, new_node)
        else:
          # if the render return None, remove the node
          target_node.getparent().remove(target_node)