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

29
import string, types, sys
30
from AccessControl import ClassSecurityInfo
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32 33 34
from Products.Formulator.DummyField import fields
from Products.Formulator import Widget, Validator
from Products.Formulator.Field import ZMIField
from Products.Formulator.Form import BasicForm
35
from Products.Formulator.Errors import FormValidationError, ValidationError
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36
from Products.Formulator.MethodField import BoundMethod
37
from Selection import Selection, DomainSelection
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38 39
from DateTime import DateTime
from Products.ERP5Type.Utils import getPath
40
from Products.ERP5Type.Document import newTempBase
41
from Products.CMFCore.utils import getToolByName
Sebastien Robin's avatar
Sebastien Robin committed
42
from copy import copy
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43 44 45 46

from Acquisition import aq_base, aq_inner, aq_parent, aq_self
from zLOG import LOG

47
import random
48 49
import md5

50 51 52 53 54 55
def getAsList(a):
  l = []
  for e in a:
    l.append(e)
  return l

56 57 58
def makeTreeBody(form, root_dict, domain_path, depth, total_depth, unfolded_list, form_id, selection_name):
  """
    This method builds a report tree
59

60
    domain_path  --    ('region', 'skill', 'group', 'group', 'region')
61

62
    root -- {'region': <instance>, 'group'; instance}
63 64

  """
65 66 67
  LOG('makeTreeBody root_dict', 0, str(root_dict))
  LOG('makeTreeBody domain_path', 0, str(domain_path))
  LOG('makeTreeBody unfolded_list', 0, str(unfolded_list))
68

69 70
  if total_depth is None:
    total_depth = max(1, len(unfolded_list))
71

72
  if type(domain_path) is type('a'): domain_path = domain_path.split('/')
73

74
  portal_categories = getattr(form, 'portal_categories', None)
75
  portal_domains = getattr(form, 'portal_domains', None)
76
  portal_object = form.portal_url.getPortalObject()
77

78 79 80
  if len(domain_path):
    base_category = domain_path[0]
  else:
81 82
    base_category = None

83 84
  if root_dict is None:
    root_dict = {}
85 86

  is_empty_level = 1
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  while is_empty_level:
    if not root_dict.has_key(base_category):
      root = None
      if portal_categories is not None:
        if base_category in portal_categories.objectIds():
          root = root_dict[base_category] = root_dict[None] = portal_categories[base_category]
          domain_path = domain_path[1:]
      if root is None and portal_domains is not None:
        if base_category in portal_domains.objectIds():
          root = root_dict[base_category] = root_dict[None] = portal_domains[base_category]
          domain_path = domain_path[1:]
      if root is None:
        try:
          root = root_dict[None] = portal_object.unrestrictedTraverse(domain_path)
        except KeyError:
          root = None
        domain_path = ()
104 105
    else:
      root = root_dict[None] = root_dict[base_category]
106
      if len(domain_path) >= 1:
107
        domain_path = domain_path[1:]
108 109 110
      else:
        domain_path = ()
    is_empty_level = (len(root.objectIds()) == 0) and (domain_path is not ())
111 112
    if is_empty_level: base_category = domain_path[0]

Jean-Paul Smets's avatar
Jean-Paul Smets committed
113
  tree_body = ''
114
  if root is None: return tree_body
Jean-Paul Smets's avatar
Jean-Paul Smets committed
115 116 117

  for o in root.objectValues():
    tree_body += '<TR>' + '<TD WIDTH="16" NOWRAP>' * depth
118
    if o.getRelativeUrl() in unfolded_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
119
      tree_body += """<TD NOWRAP VALIGN="TOP" ALIGN="LEFT" COLSPAN="%s">
120 121 122 123 124
<a href="portal_selections/foldDomain?domain_url=%s&form_id=%s&list_selection_name=%s&domain_depth:int=%s" >- <b>%s</b></a>
</TD>""" % (total_depth - depth + 1, o.getRelativeUrl() , form_id, selection_name, depth, o.id)
      new_root_dict = root_dict.copy()
      new_root_dict[None] = new_root_dict[base_category] = o
      tree_body += makeTreeBody(form, new_root_dict, domain_path, depth + 1, total_depth, unfolded_list, form_id, selection_name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
125 126
    else:
      tree_body += """<TD NOWRAP VALIGN="TOP" ALIGN="LEFT" COLSPAN="%s">
127 128
<a href="portal_selections/unfoldDomain?domain_url=%s&form_id=%s&list_selection_name=%s&domain_depth:int=%s" >+ %s</a>
</TD>""" % (total_depth - depth + 1, o.getRelativeUrl() , form_id, selection_name, depth, o.id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
129 130 131

  return tree_body

132
def makeTreeList(form, root_dict, report_path, depth, unfolded_list, form_id, selection_name, report_depth):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
133
  """
134
    (object, is_pure_summary, depth, is_open, select_domain_dict)
135

136
    select_domain_dict is a dictionary of  associative list of (id, domain)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
137
  """
138
  if type(report_path) is type('a'): report_path = report_path.split('/')
139

140
  portal_categories = getattr(form, 'portal_categories', None)
141
  portal_domains = getattr(form, 'portal_domains', None)
142
  portal_object = form.portal_url.getPortalObject()
143

144 145 146
  if len(report_path):
    base_category = report_path[0]
  else:
147 148
    base_category = None

149 150
  if root_dict is None:
    root_dict = {}
151 152

  is_empty_level = 1
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  while is_empty_level:
    if not root_dict.has_key(base_category):
      root = None
      if portal_categories is not None:
        if base_category in portal_categories.objectIds():
          root = root_dict[base_category] = root_dict[None] = portal_categories[base_category]
          report_path = report_path[1:]
      if root is None and portal_domains is not None:
        if base_category in portal_domains.objectIds():
          root = root_dict[base_category] = root_dict[None] = portal_domains[base_category]
          report_path = report_path[1:]
      if root is None:
        try:
          root = root_dict[None] = portal_object.unrestrictedTraverse(report_path)
        except KeyError:
          root = None
        report_path = ()
170 171
    else:
        root = root_dict[None] = root_dict[base_category]
172 173 174 175
        if len(report_path) >= 1:
          report_path = report_path[1:]
        else:
          report_path = ()
176
          is_empty_level = 0 # Stop infinite loop
177
    is_empty_level = (len(root.objectIds()) == 0) and (report_path is not ())
178 179
    if is_empty_level: base_category = report_path[0]

Jean-Paul Smets's avatar
Jean-Paul Smets committed
180
  tree_list = []
181
  if root is None: return tree_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
182 183

  for o in root.objectValues():
184 185 186 187 188 189 190
    new_root_dict = root_dict.copy()
    new_root_dict[None] = new_root_dict[base_category] = o
    selection_domain = DomainSelection(domain_dict = new_root_dict)
    if (report_depth is not None and depth <= (report_depth - 1)) or o.getRelativeUrl() in unfolded_list:
      tree_list += [(o, 1, depth, 1, selection_domain)] # Summary (open)
      tree_list += [(o, 0, depth, 0, selection_domain)] # List (contents, closed, must be strict selection)
      tree_list += makeTreeList(form, new_root_dict, report_path, depth + 1, unfolded_list, form_id, selection_name, report_depth)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
191
    else:
192
      tree_list += [(o, 1, depth, 0, selection_domain)] # Summary (closed)
193

Jean-Paul Smets's avatar
Jean-Paul Smets committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
  return tree_list


class ListBoxWidget(Widget.Widget):
    """
        ListBox widget

        The ListBox widget allows to display a collection of objects in a form.
        The ListBox widget can be used for many applications:

        1- show the content of a folder by providing a list of meta_types
           and eventually a sort order

        2- show the content of a relation by providing the name of the relation,
           a list of meta_types and eventually a sort order

        3- show the result of a search request by selecting a query and
           providing parameters for that query (and eventually a sort order)

        In all 3 cases, a parameter to hold the current start item must be
        stored somewhere, typically in a selection object.

        Parameters in case 3 should stored in a selection object which allows a per user
        per PC storage.

        ListBox uses the following control variables

        - sort_by -- the id to sort results

        - sort_order -- the order of sorting
    """
    property_names = Widget.Widget.property_names +\
226
                     ['lines', 'columns', 'all_columns', 'search_columns', 'sort_columns', 'sort',
Yoshinori Okuji's avatar
Yoshinori Okuji committed
227
                      'editable_columns', 'all_editable_columns', 'stat_columns', 'url_columns', 'global_attributes',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
                      'list_method', 'stat_method', 'selection_name',
                      'meta_types', 'portal_types', 'default_params',
                      'search', 'select',
                      'domain_tree', 'domain_root_list',
                      'report_tree', 'report_root_list',
                      'list_action' ]

    default = fields.TextAreaField('default',
                                   title='Default',
                                   description=(
        "Default value of the text in the widget."),
                                   default="",
                                   width=20, height=3,
                                   required=0)

    lines = fields.IntegerField('lines',
                                title='Lines',
                                description=(
        "The number of lines of this list. Required."),
                                default=10,
                                required=1)

    columns = fields.ListTextAreaField('columns',
                                 title="Columns",
                                 description=(
        "A list of attributes names to display. Required."),
                                 default=[],
                                 required=1)

    all_columns = fields.ListTextAreaField('all_columns',
                                 title="More Columns",
                                 description=(
        "An optional list of attributes names to display."),
                                 default=[],
                                 required=0)

    search_columns = fields.ListTextAreaField('search_columns',
                                 title="Searchable Columns",
                                 description=(
        "An optional list of columns to search."),
                                 default=[],
                                 required=0)

271 272 273 274 275 276 277
    sort_columns = fields.ListTextAreaField('sort_columns',
                                 title="Sortable Columns",
                                 description=(
        "An optional list of columns to sort."),
                                 default=[],
                                 required=0)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    sort = fields.ListTextAreaField('sort',
                                 title='Default Sort',
                                 description=('The default sort keys and order'),
                                 default=[],
                                 required=0)

    list_method = fields.MethodField('list_method',
                                 title='List Method',
                                 description=('The method to use to list'
                                              'objects'),
                                 default='',
                                 required=0)

    stat_method = fields.MethodField('stat_method',
                                 title='Stat Method',
                                 description=('The method to use to count'
                                              'objects'),
                                 default='',
                                 required=0)

    selection_name = fields.StringField('selection_name',
                                 title='Selection Name',
                                 description=('The name of the selection to store'
                                              'params of selection'),
                                 default='',
                                 required=0)

    meta_types = fields.ListTextAreaField('meta_types',
                                 title="Meta Types",
                                 description=(
        "Meta Types of objects to list. Required."),
                                 default=[],
                                 required=0)

    portal_types = fields.ListTextAreaField('portal_types',
                                 title="Portal Types",
                                 description=(
        "Portal Types of objects to list. Required."),
                                 default=[],
                                 required=0)

    default_params = fields.ListTextAreaField('default_params',
                                 title="Default Parameters",
                                 description=(
        "Default Parameters for the List Method."),
                                 default=[],
                                 required=0)

    search = fields.CheckBoxField('search',
                                 title='Search Row',
                                 description=('Search Row'),
                                 default='',
                                 required=0)

    select = fields.CheckBoxField('select',
                                 title='Select Column',
                                 description=('Select Column'),
                                 default='',
                                 required=0)

    editable_columns = fields.ListTextAreaField('editable_columns',
                                 title="Editable Columns",
                                 description=(
        "An optional list of columns which can be modified."),
                                 default=[],
                                 required=0)

    all_editable_columns = fields.ListTextAreaField('all_editable_columns',
                                 title="All Editable Columns",
                                 description=(
        "An optional list of columns which can be modified."),
                                 default=[],
                                 required=0)

352 353 354 355 356 357 358 359 360 361 362 363 364 365
    stat_columns = fields.ListTextAreaField('stat_columns',
                                 title="Stat Columns",
                                 description=(
        "An optional list of columns which can be used for statistics."),
                                 default=[],
                                 required=0)

    url_columns = fields.ListTextAreaField('url_columns',
                                 title="URL Columns",
                                 description=(
        "An optional list of columns which can provide a custom URL."),
                                 default=[],
                                 required=0)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    global_attributes = fields.ListTextAreaField('global_attributes',
                                 title="Global Attributes",
                                 description=(
        "An optional list of attributes which are set by hidden fields and which are applied to each editable column."),
                                 default=[],
                                 required=0)

    domain_tree = fields.CheckBoxField('domain_tree',
                                 title='Domain Tree',
                                 description=('Selection Tree'),
                                 default='',
                                 required=0)

    domain_root_list = fields.ListTextAreaField('domain_root_list',
                                 title="Domain Root",
                                 description=(
        "A list of domains which define the possible root."),
                                 default=[],
                                 required=0)

    report_tree = fields.CheckBoxField('report_tree',
                                 title='Report Tree',
                                 description=('Report Tree'),
                                 default='',
                                 required=0)



    report_root_list = fields.ListTextAreaField('report_root_list',
                                 title="Report Root",
                                 description=(
        "A list of domains which define the possible root."),
                                 default=[],
                                 required=0)

    list_action = fields.StringField('list_action',
                                 title='List Action',
                                 description=('The id of the object action'
                                              'to display the current list'),
                                 default='',
                                 required=1)

408
    def render(self, field, key, value, REQUEST, render_format='html'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
409 410 411 412
        """
          This is where most things happen. This method renders a list
          of items
        """
413 414 415 416 417
        ###############################################################
        #
        # First, grasp and intialize the variables we may need later
        #
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
418

Jean-Paul Smets's avatar
Jean-Paul Smets committed
419 420 421
        here = REQUEST['here']
        reset = REQUEST.get('reset', 0)
        form = field.aq_parent
422
        field_errors = REQUEST.get('field_errors',{});
Jean-Paul Smets's avatar
Jean-Paul Smets committed
423 424 425 426 427 428 429 430 431 432 433 434
        field_title = field.get_value('title')
        lines = field.get_value('lines')
        meta_types = field.get_value('meta_types')
        portal_types= field.get_value('portal_types')
        columns = field.get_value('columns')
        all_columns = field.get_value('all_columns')
        default_params = field.get_value('default_params')
        search = field.get_value('search')
        select = field.get_value('select')
        sort = field.get_value('sort')
        editable_columns = field.get_value('editable_columns')
        all_editable_columns = field.get_value('all_editable_columns')
435
        stat_columns = field.get_value('stat_columns')
Yoshinori Okuji's avatar
Yoshinori Okuji committed
436
        url_columns = field.get_value('url_columns')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
437
        search_columns = field.get_value('search_columns')
438
        sort_columns = field.get_value('sort_columns')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
439 440 441 442 443 444
        domain_tree = field.get_value('domain_tree')
        report_tree = field.get_value('report_tree')
        domain_root_list = field.get_value('domain_root_list')
        report_root_list = field.get_value('report_root_list')
        list_method = field.get_value('list_method')
        stat_method = field.get_value('stat_method')
Sebastien Robin's avatar
Sebastien Robin committed
445
        selection_index = REQUEST.get('selection_index')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
446
        selection_name = field.get_value('selection_name')
Sebastien Robin's avatar
Sebastien Robin committed
447
        portal_url_string = getToolByName(here, 'portal_url')()
448
        portal_categories = getattr(form, 'portal_categories', None)
449 450
        portal_domains = getattr(form, 'portal_domains', None)
        portal_object = form.portal_url.getPortalObject()
Sebastien Robin's avatar
Sebastien Robin committed
451 452 453
        #selection_name = REQUEST.get('selection_name',None)
        #if selection_name is None:
        #  selection_name = str(random.randrange(1,2147483600))
454
        current_selection_name = REQUEST.get('selection_name','default')
455 456
        current_selection_index = REQUEST.get('selection_index', 0)
        report_depth = REQUEST.get('report_depth', None)
457 458 459 460 461
        list_action = here.absolute_url() + '/' + field.get_value('list_action')
        if list_action.find('?') < 0:
          list_action += '?reset=1'
        else:
          list_action += '&reset=1'
Sebastien Robin's avatar
Sebastien Robin committed
462
        object_list = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
463
        translate = portal_object.translation_service.translate
Jean-Paul Smets's avatar
Jean-Paul Smets committed
464

465
        #LOG('Listbox',0,'search_columns1: %s' % str(search_columns))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
466 467 468
        if search_columns == [] or search_columns is None or search_columns == '':
          # We will set it as the schema
          search_columns = map(lambda x: [x,x],here.portal_catalog.schema())
469
          #LOG('Listbox',0,'search_columns2: %s' % str(search_columns))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
470 471
        search_columns_id_list = map(lambda x: x[0], search_columns)

472 473 474
        if sort_columns == [] or sort_columns is None or sort_columns == '':
          sort_columns = search_columns
        sort_columns_id_list = map(lambda x: x[0], sort_columns)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
475

476
        # Display statistics if the button Parameter exists or stat columns are defined explicitly.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
477 478
        filtered_actions = here.portal_actions.listFilteredActionsFor(here);
        object_ui = filtered_actions.has_key('object_ui')
479 480 481 482 483 484 485 486
        show_stat = (object_ui or stat_columns)

        # If nothing is specified to stat_columns, assume that all columns are available.
        # For compatibility, because there was no stat_columns before.
        if not stat_columns:
          stat_columns = []
          for column in all_columns:
            stat_columns.append((column[0], column[0]))
487 488
          for column in columns: # Sometimes, all_columns is not defined
            stat_columns.append((column[0], column[0]))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
489

Yoshinori Okuji's avatar
Yoshinori Okuji committed
490 491 492
        if not url_columns:
          url_columns = []

Jean-Paul Smets's avatar
Jean-Paul Smets committed
493 494 495 496 497 498
        has_catalog_path = None
        for (k, v) in all_columns:
          if k == 'catalog.path' or k == 'path':
            has_catalog_path = k
            break

499 500
        selection = here.portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST)
        # Create selection if needed, with default sort order
Jean-Paul Smets's avatar
Jean-Paul Smets committed
501
        if selection is None:
502
          selection = Selection(params=default_params, default_sort_on = sort)
503 504
        # Or make sure all sort arguments are valid
        else:
505 506 507
          # Reset Selection is needed
          if reset is not 0 and reset is not '0':
            here.portal_selections.setSelectionToAll(selection_name)
508 509 510 511
            here.portal_selections.setSelectionSortOrder(selection_name, sort_on = [])

          # Modify the default sort index every time, because it may change immediately.
          selection.edit(default_sort_on = sort)
512

513
          # Filter non searchable items
514
          sort_list = []
515
          fix_sort = 0
516
          for (k , v) in selection.sort_on:
517
            if k in sort_columns_id_list:
518
              sort_list.append((k,v))
519 520
            else:
              fix_sort = 1
521
          if fix_sort: selection.sort_on = sort_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
522

523
        if not hasattr(selection, 'flat_list_mode'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
524 525 526
          selection.edit(flat_list_mode=(not (domain_tree or
           report_tree)),domain_tree_mode=domain_tree,report_tree_mode= report_tree)

527
        #LOG('ListBox', 0, 'sort = %s, selection.selection_sort_on = %s' % (repr(sort), repr(selection.selection_sort_on)))
528
        # Selection
Yoshinori Okuji's avatar
Yoshinori Okuji committed
529
        #LOG("Selection",0,str(selection.__dict__))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
530 531 532

        # Display choosen by the user

533
        if selection.flat_list_mode is not None:
534
          if selection.flat_list_mode == 1:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
535 536
            domain_tree = 0
            report_tree = 0
537
          elif selection.domain_tree_mode == 1:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
538 539
            domain_tree = 1
            report_tree = 0
540
          elif selection.report_tree_mode == 1:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
541 542 543
            domain_tree = 0
            report_tree = 1

544
        checked_uids = selection.getCheckedUids()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        columns = here.portal_selections.getSelectionColumns(selection_name,
                                                columns=columns, REQUEST=REQUEST)


        editable_column_ids = map(lambda x: x[0], editable_columns)
        all_editable_column_ids = map(lambda x: x[0], all_editable_columns)

        url = REQUEST.URL

        # Build the list of meta_types
        filtered_meta_types = map(lambda x: x[0], meta_types)
        if len(filtered_meta_types) == 0:
          filtered_meta_types = None

        # Build the list of meta_types
        filtered_portal_types = map(lambda x: x[0], portal_types)
        if len(filtered_portal_types) == 0:
            filtered_portal_types = None

        # Combine default values, selection values and REQUEST
565
        params = selection.getParams()
566 567 568 569 570 571 572 573 574
        if list_method not in (None, ''):
          # Only update params if list_method is defined
          # (ie. do not update params in listboxed intended to show a previously defined selection
          params.update(REQUEST.form)
          for (k,v) in default_params:
            if REQUEST.form.has_key(k):
              params[k] = REQUEST.form[k]
            elif not params.has_key(k):
              params[k] = eval(v)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
575

576 577 578 579 580 581 582 583 584 585 586 587
        # Allow overriding list_method and stat_method by params
        if params.has_key('list_method_id'):
          #try:
          list_method = getattr(here.portal_skins.local_list_method , params['list_method_id']) # Coramy specific
          #except:
          #  list_method = list_method
        if params.has_key('stat_method_id'):
          #try:
          list_method = getattr(here.portal_skins.local_list_method , params['stat_method_id']) # Coramy specific
          #except:
          #  list_method = list_method

Jean-Paul Smets's avatar
Jean-Paul Smets committed
588
        # Set the params spec (this should change in the future)
589 590 591 592 593
        if list_method not in (None, ''):
          # Only update params if list_method is defined
          # (ie. do not update params in listboxed intended to show a previously defined selection
          params['meta_type'] = filtered_meta_types
          params['portal_type'] = filtered_portal_types
Jean-Paul Smets's avatar
Jean-Paul Smets committed
594

595
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
596
        #
Jean-Paul Smets's avatar
Jean-Paul Smets committed
597
        # Build the columns selections
598
        #
Jean-Paul Smets's avatar
Jean-Paul Smets committed
599 600 601
        # The idea is: instead of selecting *, listbox is able to
        # provide what should be selected. This should allow to reduce
        # the quantity of data transfered between MySQL and Zope
602 603
        #
        ###############################################################
Jean-Paul Smets's avatar
Jean-Paul Smets committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
        extended_columns = []
        sql_columns = []
        for (sql, title) in columns:
          # original SQL id, Title, alias
          alias = string.split(sql,'.')
          alias = string.join(alias, '_')
          extended_columns += [(sql, title, alias)]
          if alias != sql:
            sql_columns += ['%s AS %s' % (sql, alias)]
          else:
            sql_columns += [alias]
        if has_catalog_path:
          alias = string.split(has_catalog_path,'.')
          alias = string.join(alias, '_')
          if alias != has_catalog_path:
            sql_columns += ['%s AS %s' % (has_catalog_path, alias)]
          else:
            sql_columns += [alias]
        sql_columns_string = string.join(sql_columns,' , ')
        params['select_columns'] = sql_columns_string

625
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
626
        #
Jean-Paul Smets's avatar
Jean-Paul Smets committed
627
        # Execute the query
Yoshinori Okuji's avatar
Yoshinori Okuji committed
628
        #
629
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
630

Jean-Paul Smets's avatar
Jean-Paul Smets committed
631
        kw = params
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

        # XXX Remove selection_expression if present.
        # This is necessary for now, because the actual selection expression in
        # search catalog does not take the requested columns into account. If
        # select_expression is passed, this can raise an exception, because stat
        # method sets select_expression, and this might cause duplicated column
        # names.
        #
        # In the future, this must be addressed in a clean way. selection_expression
        # should be used for search catalog, and search catalog should not use
        # catalog.* but only selection_expression. But this is a bit difficult,
        # because there is no simple way to distinguish queried columns from callable
        # objects in the current ListBox configuration.
        if 'select_expression' in kw:
          del kw['select_expression']

Jean-Paul Smets's avatar
Jean-Paul Smets committed
648 649 650 651 652
        if hasattr(list_method, 'method_name'):
          if list_method.method_name == 'objectValues':
            list_method = here.objectValues
            kw = copy(params)
            kw['spec'] = filtered_meta_types
653
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
            # The Catalog Builds a Complex Query
            # So we should not pass too many variables
            kw = {}
            if REQUEST.form.has_key('portal_type'):
              kw['portal_type'] = REQUEST.form['portal_type']
            elif REQUEST.has_key('portal_type'):
              kw['portal_type'] = REQUEST['portal_type']
            elif filtered_portal_types is not None:
              kw['portal_type'] = filtered_portal_types
            elif filtered_meta_types is not None:
              kw['meta_type'] = filtered_meta_types
            elif kw.has_key('portal_type'):
              if kw['portal_type'] == '':
                del kw['portal_type']

            # Remove useless matter
            for cname in params.keys():
              if params[cname] != '' and params[cname]!=None:
                kw[cname] = params[cname]

            # Try to get the method through acquisition
            try:
              list_method = getattr(here, list_method.method_name)
            except:
              pass
679 680 681 682
        elif list_method in (None, ''): # Use current selection
          # Use previously used list method
          list_method = None

Jean-Paul Smets's avatar
Jean-Paul Smets committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702

        # Lookup the stat_method
        if hasattr(stat_method, 'method_name'):
          if stat_method.method_name == 'objectValues':
            stat_method = None # Nothing to do in this case
            show_stat = 0
          elif stat_method.method_name == 'portal_catalog':
            # We use the catalog count results
            stat_method = here.portal_catalog.countResults
          else:
            # Try to get the method through acquisition
            try:
              stat_method = getattr(here, stat_method.method_name)
              show_stat = 1
            except:
              show_stat = 0
              pass
        else:
          stat_method = here.portal_catalog.countResults

703
        #LOG('ListBox', 0, 'domain_tree = %s, selection.getDomainPath() = %s, selection.getDomainList() = %s' % (repr(domain_tree), repr(selection.getDomainPath()), repr(selection.getDomainList())))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
704
        if domain_tree:
705 706
          selection_domain_path = selection.getDomainPath()
          selection_domain_current = selection.getDomainList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
707
          if len(selection_domain_current) > 0:
708
            root_dict = {}
709 710
            for domain in selection_domain_current:
              if type(domain) != type(''): continue # XXX workaround for a past bug in Selection
711 712 713 714 715 716 717 718 719 720 721 722 723
              root = None
              base_category = domain.split('/')[0]
              if portal_categories is not None:
                if base_category in portal_categories.objectIds():
                  root = root_dict[base_category] = portal_categories.restrictedTraverse(domain)
              if root is None and portal_domains is not None:
                if base_category in portal_domains.objectIds():
                  root = root_dict[base_category] = portal_domains.restrictedTraverse(domain)
              if root is None:
                try:
                  root_dict[None] = portal_object.restrictedTraverse(domain)
                except KeyError:
                  root = None
724 725 726
              #LOG('domain_tree root aq_parent', 0, str(root_dict[base_category].aq_parent))
            selection.edit(domain = DomainSelection(domain_dict = root_dict))
            #LOG('selection.domain', 0, str(selection.domain.__dict__))
727 728
        else:
          selection.edit(domain = None)
729

730 731
        #LOG('ListBox', 0, 'list_method = %s, list_method.__dict__ = %s' % (repr(list_method), repr((list_method.__dict__))))

732
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
733
        #
734
        # Prepare the stat select_expression
Yoshinori Okuji's avatar
Yoshinori Okuji committed
735 736
        #
        ###############################################################
737
        select_expression = ''
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        if show_stat:
          stats = here.portal_selections.getSelectionStats(selection_name, REQUEST=REQUEST)
          index = 0

          for (sql,title,alias) in extended_columns:
            # XXX This might be slow.
            for column in stat_columns:
              if column[0] == sql:
                break
            else:
              column = None
            if column is not None and column[0] == column[1]:
              try:
                if stats[index] != ' ':
                  select_expression += stats[index] + '(' + sql + ') AS ' + alias + ','
                else:
                  select_expression += '\'&nbsp;\' AS ' + alias + ','
              except:
                select_expression += '\'&nbsp;\' AS ' + alias + ','
            index = index + 1

          select_expression = select_expression[:len(select_expression) - 1]
Yoshinori Okuji's avatar
Yoshinori Okuji committed
760

761
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
762
        #
763 764 765 766 767
        # Build the report tree
        #
        # When we build the body, we have to go through all report lines
        #
        # Each report line is a tuple of the form:
768 769
        #
        # (section_id, is_summary, depth, object_list, object_list_size, is_open)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
770 771
        #
        ###############################################################
Jean-Paul Smets's avatar
Jean-Paul Smets committed
772
        if report_tree:
773 774 775
          selection_report_path = selection.getReportPath()
          if report_depth is not None:
            selection_report_current = ()
776
          else:
777 778 779
            selection_report_current = selection.getReportList()
          report_tree_list = makeTreeList(form, None, selection_report_path,
                                          0, selection_report_current, form.id, selection_name, report_depth )
780 781

          # Update report list if report_depth was specified
782 783 784
          if report_depth is not None:
            report_list = map(lambda s:s[0].getRelativeUrl(), report_tree_list)
            selection.edit(report_list=report_list)
785

Jean-Paul Smets's avatar
Jean-Paul Smets committed
786 787 788
          report_sections = []
          #LOG("Report Tree",0,str(report_tree_list))
          for s in report_tree_list:
789 790
            # Prepare query
            selection.edit(report = s[4])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
791
            if s[1]:
792 793 794
              # Push new select_expression
              original_select_expression = kw.get('select_expression')
              kw['select_expression'] = select_expression
Jean-Paul Smets's avatar
Jean-Paul Smets committed
795
              selection.edit( params = kw )
796
              #LOG('ListBox 569', 0, str((selection_name, selection.__dict__)))
797
              stat_temp = selection(method = stat_method,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
798
                        context=here, REQUEST=REQUEST)
799 800 801 802 803
              # Pop new select_expression
              if original_select_expression is None:
                del kw['select_expression']
              else:
                kw['select_expression'] = original_select_expression
Jean-Paul Smets's avatar
Jean-Paul Smets committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822



              # stat_result is a list
              # we want now to make it a dictionnary
              # Is this a report line
              # object_stat = ....
              stat_result = {}
              index = 1

              for (k,v) in columns:
                try:
                  stat_result[k] = str(stat_temp[0][index])
                except IndexError:
                  stat_result[k] = ''
                index = index + 1

              stat_context = s[0].asContext(**stat_result)
              stat_context.absolute_url = lambda x: s[0].absolute_url()
823 824
              stat_context.domain_url = s[0].getRelativeUrl()
              report_sections += [(s[0].id, 1, s[2], [stat_context], 1, s[3], s[4])]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
825 826 827
            else:
              # Prepare query
              selection.edit( params = kw )
828
              if list_method not in (None, ''):
829
                object_list = selection(method = list_method, context=here, REQUEST=REQUEST)
830 831 832
              else:
                # If list_method is None, use already selected values.
                object_list = here.portal_selections.getSelectionValueList(selection_name, context=here, REQUEST=REQUEST)
833
#               # PERFORMANCE ? is len(object_list) fast enough ?
834
              report_sections += [ (None, 0, s[2], object_list, len(object_list), s[3], s[4]) ]
835 836 837

          # Reset original value
          selection.edit(report = None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
838
        else:
839
          selection.edit( params = kw, report = None )
840
          #LOG('ListBox 612', 0, str((selection_name, selection.__dict__)))
841
          if list_method not in (None, ''):
842
            object_list = selection(method = list_method, context=here, REQUEST=REQUEST)
843 844 845
          else:
            # If list_method is None, use already selected values.
            object_list = here.portal_selections.getSelectionValueList(selection_name, context=here, REQUEST=REQUEST)
846
          # PERFORMANCE PROBLEM ? is len(object_list) fast enough ?
Jean-Paul Smets's avatar
Jean-Paul Smets committed
847 848
          report_sections = ( (None, 0, 0, object_list, len(object_list), 0),  )

Yoshinori Okuji's avatar
Yoshinori Okuji committed
849

850
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
851 852 853
        #
        # Build an md5 signature of the selection
        #
854
        # It is calculated based on the selection uid list
Sebastien Robin's avatar
Sebastien Robin committed
855 856 857 858 859 860
        # It is used in order to do some checks in scripts.
        # For example, if we do delete objects, then we do have a list of
        # objects to delete, but it is possible that on another tab the selection
        # change, and then when we confirm the deletion, we don't delete what
        # we want, so this is really dangerous. with this md5 we can check if the
        # selection is the same
Yoshinori Okuji's avatar
Yoshinori Okuji committed
861 862 863
        #
        ###############################################################

864 865
        object_uid_list = map(lambda x: getattr(x, 'uid', None), object_list)
        #LOG('ListBox.render, object_uid_list:',0,object_uid_list)
Sebastien Robin's avatar
Sebastien Robin committed
866 867
        sorted_object_uid_list = copy(object_uid_list)
        sorted_object_uid_list.sort()
868
        md5_string = md5.new(str(sorted_object_uid_list)).hexdigest()
Sebastien Robin's avatar
Sebastien Robin committed
869 870
        #md5_string = md5.new(str(object_uid_list)).digest()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
871

872
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
873
        #
874
        # Calculate list start and stop
Yoshinori Okuji's avatar
Yoshinori Okuji committed
875
        #
Jean-Paul Smets's avatar
Jean-Paul Smets committed
876 877 878
        # Build the real list by slicing it
        # PERFORMANCE ANALYSIS: the result of the query should be
        # if possible a lazy sequence
879
        #
Yoshinori Okuji's avatar
Yoshinori Okuji committed
880 881
        ###############################################################

882
        #LOG("Selection", 0, str(selection.__dict__))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
883 884 885
        total_size = 0
        for s in report_sections:
          total_size += s[4]
886 887
        if render_format == 'list':
          start = 0
Yoshinori Okuji's avatar
Yoshinori Okuji committed
888 889
          end = total_size
          total_pages = 1
890
          current_page = 0
Yoshinori Okuji's avatar
Yoshinori Okuji committed
891
        else:
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
          try:
            start = REQUEST.get('list_start')
            start = int(start)
          except:
            start = params.get('list_start',0)
            start = int(start)
          end = min(start + lines, total_size)
          #object_list = object_list[start:end]
          total_pages = int(max(total_size-1,0) / lines) + 1
          current_page = int(start / lines)
          start = max(start, 0)
          start = min(start, max(0, total_pages * lines - lines) )
          kw['list_start'] = start
          kw['list_lines'] = lines

        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
908
        #
909
        # Store new selection values
Yoshinori Okuji's avatar
Yoshinori Okuji committed
910
        #
911 912
        # Store the resulting selection if list_method is not None and render_format is not list
        #
Yoshinori Okuji's avatar
Yoshinori Okuji committed
913
        ###############################################################
914
        if list_method is not None and render_format != 'list':
915 916
          try:
            method_path = getPath(here) + '/' + list_method.method_name
917
            #LOG('ListBox', 0, 'method_path = %s, getPath = %s, list_method.method_name = %s' % (repr(method_path), repr(getPath(here)), repr(list_method.method_name)))
918 919
          except:
            method_path = getPath(here) + '/' + list_method.__name__
920
            #LOG('ListBox', 0, 'method_path = %s, getPath = %s, list_method.__name__ = %s' % (repr(method_path), repr(getPath(here)), repr(list_method.__name__)))
921 922 923 924 925
          # Sometimes the seltion name is a list ??? Why ????
          if type(current_selection_name) in (type(()),type([])):
            current_selection_name = current_selection_name[0]
          list_url =  url+'?selection_name='+current_selection_name+'&selection_index='+str(selection_index)
          selection.edit( method_path= method_path, params = kw, list_url = list_url)
926 927
          #LOG("Selection kw", 0, str(selection.selection_params))
          here.portal_selections.setSelectionFor(selection_name, selection, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
928

929
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
930
        #
931
        # Build HTML header and footer
Yoshinori Okuji's avatar
Yoshinori Okuji committed
932
        #
933
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
934

Jean-Paul Smets's avatar
Jean-Paul Smets committed
935 936 937 938
        # Provide the selection name
        selection_line = """\
<input type="hidden" name="list_selection_name" value="%s" />
""" % selection_name
Sebastien Robin's avatar
Sebastien Robin committed
939 940 941
        selection_line +="""\
<input type="hidden" name="md5_object_uid_list" value="%s" />
""" % md5_string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
942 943 944 945 946 947 948

        # Create the Page Selector
        if start == 0:
          pages = """\
   <td nowrap valign="middle" align="center">
   </td>
   <td nowrap valign="middle" align="center">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
949
    <select name="list_start" title="%s" size="1"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
950
      onChange="submitAction(this.form,'%s/portal_selections/setPage')">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
951
""" % (translate('ui', 'Change Page'), REQUEST.URL1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
952 953 954
        else:
          pages = """\
   <td nowrap valign="middle" align="center">
Sebastien Robin's avatar
Sebastien Robin committed
955
    <input type="image" src="%s/images/1leftarrowv.png"
Yoshinori Okuji's avatar
Yoshinori Okuji committed
956
      title="%s" name="portal_selections/previousPage:method" border="0" />
Jean-Paul Smets's avatar
Jean-Paul Smets committed
957 958
   </td>
   <td nowrap valign="middle" align="center">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
959
    <select name="list_start" title="%s" size="1"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
960
      onChange="submitAction(this.form,'%s/portal_selections/setPage')">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
961
""" % (portal_url_string, translate('ui', 'Previous Page'), translate('ui', 'Change Page'), REQUEST.URL1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
962 963
        for p in range(0, total_pages):
          if p == current_page:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
964
            selected = 'selected'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
965
          else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
966 967 968 969 970 971
            selected = ''
          pages += '<option %s value="%s">%s</option>\n' \
                  % (selected,
                     p * lines,
                     translate('ui', '${page} of ${total_pages}',
                               mapping = {'page' : p+1, 'total_pages': total_pages}))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
972 973

        if current_page == total_pages - 1:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
974
          pages += """\
Jean-Paul Smets's avatar
Jean-Paul Smets committed
975 976 977 978 979 980
    </select>
   </td>
   <td nowrap valign="middle" align="center">
   </td>
"""
        else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
981
          pages += """\
Jean-Paul Smets's avatar
Jean-Paul Smets committed
982 983 984
    </select>
   </td>
   <td nowrap valign="middle" align="center">
Sebastien Robin's avatar
Sebastien Robin committed
985
    <input type="image" src="%s/images/1rightarrowv.png"
Yoshinori Okuji's avatar
Yoshinori Okuji committed
986
      title="%s" name="portal_selections/nextPage:method" border="0" />
Jean-Paul Smets's avatar
Jean-Paul Smets committed
987
   </td>
Yoshinori Okuji's avatar
Yoshinori Okuji committed
988
""" % (portal_url_string, translate('ui', 'Next Page'))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
989 990 991
        # Create the header of the table - this should probably become DTML
        # Create also View Selector which enables to switch from a view mode
        # to another directly from the listbox
Yoshinori Okuji's avatar
Yoshinori Okuji committed
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        #LOG('ListBox', 0, 'field_title = %s, translate(\'ui\', field_title) + %s' % (repr(field_title), repr(translate('ui', field_title))))
        format_dict = {
                        'portal_url_string' : portal_url_string,
                        'list_action' : list_action,
                        'field_title' : translate('ui', field_title),
                        'pages' : pages,
                        'record_number' : translate('ui', '${number} record(s)',
                                                    mapping = { 'number' : str(total_size) }),
                        'item_number' : translate('ui', '${number} item(s) selected',
                                                  mapping = { 'number' : str(len(checked_uids)) }),
                        'flat_list_title': translate('ui', 'Flat List'),
                        'report_tree_title': translate('ui', 'Report Tree'),
                        'domain_tree_title': translate('ui', 'Domain Tree'),
                      }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1006 1007 1008 1009 1010
        header = """\
<!-- List Summary -->
<div class="ListSummary">
 <table border="0" cellpadding="0" cellspacing="0">
  <tr height="10">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1011
   <td height="10"><img src="%(portal_url_string)s/images/Left.png" border="0"></td>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1012
   <td class="Top" colspan="2" height="10">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1013
    <img src="%(portal_url_string)s/images/spacer.png" width="5" height="10" border="0"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1014 1015
      alt="spacer"/></td>
   <td class="Top" colspan="3" height="10">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1016
    <img src="%(portal_url_string)s/images/spacer.png" width="5" height="10" border="0"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1017 1018 1019 1020 1021
      alt="spacer"/>
   </td>
  </tr>
  <tr>
   <td class="Left" width="17">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1022
    <img src="%(portal_url_string)s/images/spacer.png" width="5" height="5" border="0"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1023 1024 1025 1026
        alt="spacer"/>
   </td>
   <td valign="middle" nowrap>

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1027 1028 1029 1030 1031 1032 1033 1034
    <input type="image" src="%(portal_url_string)s/images/text_block.png" id="flat_list"
       title="%(flat_list_title)s" name="portal_selections/setFlatListMode:method" value="1" border="0" alt="img"/">
    <input type="image" src="%(portal_url_string)s/images/view_tree.png" id="flat_list"
       title="%(report_tree_title)s" name="portal_selections/setReportTreeMode:method" value="1" border="0" alt="img"/">
        <input type="image" src="%(portal_url_string)s/images/view_choose.png" id="flat_list"
       title="%(domain_tree_title)s" name="portal_selections/setDomainTreeMode:method" value="1" border="0" alt="img"/"></td>
   <td width="100%%" valign="middle">&nbsp; <a href="%(list_action)s">%(field_title)s</a>:
        %(record_number)s - %(item_number)s
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1035
   </td>
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1036
   %(pages)s
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1037 1038 1039 1040 1041 1042
  </tr>
 </table>
</div>
<!-- List Content -->
<div class="ListContent">
 <table cellpadding="0" cellspacing="0" border="0">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1043
""" % format_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

        # pages

        # Create the footer. This should be replaced by DTML
        # And work as some kind of parameter

        footer = """\
      </div>
     </td>
    </div>
   </tr>
   <tr >
    <td colspan="%s" width="50" align="center" valign="middle"
        class="DataA">
    </td>
   </tr>
  </table>
 </div>
""" % (len(columns))

        # Create the header of the table with the name of the columns
        # Create also Report Tree Column if needed
        if report_tree:
          report_tree_options = ''
          for c in report_root_list:
            if c[0] == selection_report_path:
              report_tree_options += """<option selected value="%s">%s</option>\n""" % (c[0], c[1])
            else:
              report_tree_options += """<option value="%s">%s</option>\n""" % (c[0], c[1])
          report_popup = """<select name="report_root_url"
onChange="submitAction(this.form,'%s/portal_selections/setReportRoot')">
        %s</select>""" % (here.getUrl(),report_tree_options)
          report_popup = """
  <td class="Data" width="50" align="center" valign="middle">
  %s
  </td>
""" % report_popup
        else:
          report_popup = ''

        if select:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1085 1086 1087 1088 1089 1090
          format_dict = {
                          'portal_url_string' : portal_url_string,
                          'report_popup' : report_popup,
                          'check_all_title' : translate('ui', 'Check All'),
                          'uncheck_all_title' : translate('ui', 'Uncheck All'),
                        }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1091
          list_header = """\
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1092
<tr>%(report_popup)s
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1093
   <td class="Data" width="50" align="center" valign="middle">
1094
    <input type="image" name="portal_selections/checkAll:method" value="1"
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1095
      src="%(portal_url_string)s/images/checkall.png" border="0" alt="Check All" title=%(check_all_title)s />
1096
    <input type="image" name="portal_selections/uncheckAll:method" value="1"
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1097 1098
      src="%(portal_url_string)s/images/decheckall.png" border="0" alt="Uncheck All" title=%(uncheck_all_title)s />
""" % format_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1099 1100
        else:
          list_header = """\
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1101
<tr>%s
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1102
""" % report_popup
1103

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
        # csort is a list of couples
        # we should convert it into a dict because a list of couples would need
        # a loop in each loop
        sort_dict = {}
        csort = here.portal_selections.getSelectionSortOrder(selection_name)
        for index in csort:
          sort_dict[index[0]] = index[1]

        for cname in columns:
          if sort_dict.has_key(cname[0]):
            if sort_dict[cname[0]] == 'ascending':
Sebastien Robin's avatar
Sebastien Robin committed
1115
              img = '<img src="%s/images/1bottomarrow.png" alt="Ascending display">' % portal_url_string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1116
            elif sort_dict[cname[0]] == 'descending':
Sebastien Robin's avatar
Sebastien Robin committed
1117
              img = '<img src="%s/images/1toparrow.png" alt="Descending display">' % portal_url_string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1118 1119 1120 1121 1122
            else:
              img = ''
          else:
            img = ''
          if cname[0] in search_columns_id_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1123 1124 1125
            #LOG('ListBox', 0, 'str(cname[1]) = %s, translate(\'ui\',str(cname[1])) = %s' % (repr(str(cname[1])), repr(translate('ui',str(cname[1])))))
            list_header += ("<td class=\"Data\"><a href=\"%sportal_selections/setSelectionQuickSortOrder?selection_name=%s&sort_on=%s\">%s</a> %s</td>\n" %
                (here.absolute_url() + '/' ,str(selection_name),str(cname[0]),translate('ui',str(cname[1])),img))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1126
          else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1127
            list_header += ("<td class=\"Data\">%s</td>\n" % translate('ui', str(cname[1])))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1128 1129 1130 1131 1132 1133
        list_header = list_header + "</tr>"

        # Create the search row of the table with the name of the columns
        if search:
          # Add empty column for report
          if report_tree:
1134 1135 1136 1137 1138 1139
            depth_selector = ''
            for i in range(0,6):
              # XXX We may lose previous list information
              depth_selector += """&nbsp;<a href="%s/%s?selection_name=%s&selection_index=%s&report_depth:int=%s">%s</a>""" % \
                                       (here.absolute_url(), form.id, current_selection_name, current_selection_index , i, i)
            report_search = """<td class="Data" width="50" align="left" valign="middle">%s</td>""" % depth_selector
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1140 1141 1142 1143 1144 1145 1146 1147
          else:
            report_search = ""

          if select:
            list_search ="""\
  <tr >
   %s
   <td class="Data" width="50" align="center" valign="middle">
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1148
     <input type="image" src="%s/images/exec16.png" title="%s" alt="Action" name="doSelect:method" />
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1149
   </td>
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1150
""" % (report_search,portal_url_string,translate('ui', 'Action')) # XXX Action? Is this word appropriate here?
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1151 1152 1153 1154 1155 1156 1157 1158
          else:
            list_search ="""\
  <tr >
  %s
""" % report_search

          for cname in extended_columns:
            if cname[0] in search_columns_id_list:
1159 1160 1161 1162 1163 1164 1165 1166 1167
              alias = str(cname[2])
              param = params.get(alias,'')
              if type(param) == type(''):
                param = unicode(param, 'utf-8')
              list_search += """\
     <td class="DataB">
       <font size="-3"><input name="%s" size="8" value="%s"></font>
     </td>
""" % (alias, param)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1168 1169 1170 1171 1172 1173 1174
            else:
              list_search = list_search + (
                "<td class=\"DataB\"></td> ")

          list_search = list_search + "</tr>"
        else:
          list_search = ''
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1175

1176 1177 1178 1179 1180 1181 1182
        # Build the tuple of columns
        if render_format == 'list':
          c_name_list = []
          for cname in columns:
            c_name_list.append(cname[1])

        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1183
        #
1184
        # Build lines
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1185
        #
1186
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1187

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1188 1189
        # Build Lines
        list_body = ''
1190
        if render_format == 'list': list_result = [c_name_list] # Create initial list for list render format
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1191 1192
        section_index = 0
        current_section_base_index = 0
1193 1194 1195 1196
        if len(report_sections) > section_index:
          current_section = report_sections[section_index]
        elif len(report_sections):
          current_section = report_sections[0]
1197 1198
        else:
          current_section = None
1199 1200 1201
        if current_section is not None:
          current_section_size = current_section[4]
          object_list = current_section[3]
1202
          #if current_section is not None:
1203 1204 1205
          for i in range(start,end):
            # Set the selection index.
            selection.edit(index = i)
1206

1207 1208 1209 1210 1211 1212 1213
            # Make sure we go to the right section
            while current_section_base_index + current_section_size <= i:
              current_section_base_index += current_section[4]
              section_index += 1
              current_section = report_sections[section_index]
              current_section_size = current_section[4]
              object_list = current_section[3]
1214

1215
            is_summary = current_section[1] # Update summary type
1216

1217 1218 1219
            list_body = list_body + '<tr>'
            o = object_list[i - current_section_base_index] # FASTER PERFORMANCE
            real_o = None
1220

1221 1222 1223
            # Define the CSS
            if not (i - start) % 2:
              td_css = 'DataA'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1224
            else:
1225
              td_css = 'DataB'
1226

1227 1228 1229
            list_body = list_body + \
  """<input type="hidden" value="%s" name="%s_uid:list"/>
  """ % ( getattr(o, 'uid', '') , field.id ) # What happens if we list instances which are not instances of Base XXX
1230

1231 1232 1233
            section_char = ''
            if render_format == 'list': list_result_item = [] # Start a new item for list render format
            if report_tree:
1234
              if is_summary:
1235 1236
                # This is a summary
                section_name = current_section[0]
1237
              else:
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
                section_name = ''
              if current_section[5]:
                if section_name != '':
                  section_char = '-'
                list_body = list_body + \
  """<td class="%s" align="left" valign="middle"><a href="portal_selections/foldReport?report_url=%s&form_id=%s&list_selection_name=%s">%s%s%s</a></td>
  """ % (td_css, getattr(current_section[3][0],'domain_url',''), form.id, selection_name, '&nbsp;&nbsp;' * current_section[2], section_char, section_name)
                if render_format == 'list': list_result_item.append(section_name)
              else:
                if section_name != '':
                  section_char = '+'
                list_body = list_body + \
  """<td class="%s" align="left" valign="middle"><a href="portal_selections/unfoldReport?report_url=%s&form_id=%s&list_selection_name=%s">%s%s%s</a></td>
  """ % (td_css, getattr(current_section[3][0],'domain_url',''), form.id, selection_name, '&nbsp;&nbsp;' * current_section[2], section_char, section_name)
                if render_format == 'list': list_result_item.append(section_name)
1253

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
            if select:
              if o.uid in checked_uids:
                selected = 'checked'
              else:
                selected = ''
              if section_char != '':
                list_body = list_body + \
  """<td class="%s" width="50" align="center" valign="middle">&nbsp;</td>
  """ % (td_css, )
              else:
                list_body = list_body + \
  """<td class="%s" width="50" align="center" valign="middle">&nbsp;
  <input type="checkbox" %s value="%s" id="cb_%s" name="uids:list"/></td>
  """ % (td_css, selected, o.uid , o.uid)
            error_list = []
            for cname in extended_columns:
              sql = cname[0] # (sql, title, alias)
              alias = cname[2] # (sql, title, alias)
              if '.' in sql:
                property_id = '.'.join(sql.split('.')[1:]) # Only take trailing part
              else:
                property_id = alias
  #            attribute_value = getattr(o, cname_id) # FUTURE WAY OF DOING TGW Brains
              my_field = None
              tales_expr = None
              if form.has_field('%s_%s' % (field.id, alias) ) and not is_summary:
                my_field_id = '%s_%s' % (field.id, alias)
                my_field = form.get_field(my_field_id)
                tales_expr = my_field.tales.get('default', "")
              if tales_expr:
                #
                real_o = o
                if hasattr(o,'getObject'): # we have a line of sql result
                  real_o = o.getObject()
                field_kw = {'cell':real_o}
                attribute_value = my_field.__of__(real_o).get_value('default',**field_kw)
              else:
                # Prepare stat_column is this is a summary
                if is_summary:
                  # Use stat method to find value
                  for stat_column in stat_columns:
                    if stat_column[0] == sql:
                      break
                  else:
                    stat_column = None
                if hasattr(aq_self(o),alias) and (not is_summary or stat_column is None or stat_column[0] == stat_column[1]): # Block acquisition to reduce risks
                  # First take the indexed value
                  attribute_value = getattr(o,alias) # We may need acquisition in case of method call
                elif is_summary:
                  attribute_value = getattr(here, stat_column[1])
                  #LOG('ListBox', 0, 'column = %s, value = %s' % (repr(column), repr(value)))
                  if callable(attribute_value):
1306
                    try:
1307 1308 1309
                      params = dict(kw)
                      #params['operator'] = stats[n]
                      attribute_value=attribute_value(**params)
1310
                    except:
1311 1312
                      LOG('ListBox', 0, 'WARNING: Could not call %s with %s: ' % (repr(attribute_value), repr(params)), error=sys.exc_info())
                      pass
1313
                else:
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    #             MUST IMPROVE FOR PERFORMANCE REASON
    #             attribute_value = 'Does not exist'
                  if real_o is None:
                    try:
                      real_o = o.getObject()
                    except:
                      pass
                  if real_o is not None:
                    try:
                      try:
                        attribute_value = getattr(real_o,property_id, None)
                        #LOG('Look up attribute %s' % cname_id,0,str(attribute_value))
                        if not callable(attribute_value):
                          #LOG('Look up accessor %s' % cname_id,0,'')
                          attribute_value = real_o.getProperty(property_id)
                          #LOG('Look up accessor %s' % cname_id,0,str(attribute_value))
                      except:
                        attribute_value = getattr(real_o,property_id)
                        #LOG('Fallback to attribute %s' % cname_id,0,str(attribute_value))
                    except:
                      attribute_value = 'Can not evaluate attribute: %s' % sql
                  else:
                    attribute_value = 'Object does not exist'
              if callable(attribute_value):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1338
                try:
1339 1340 1341 1342
                  try:
                    attribute_value = attribute_value(brain = o, selection = selection)
                  except TypeError:
                    attribute_value = attribute_value()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1343
                except:
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
                  LOG('ListBox', 0, 'Could not evaluate', error=sys.exc_info())
                  attribute_value = "Could not evaluate"
              #LOG('ListBox', 0, 'o = %s' % repr(dir(o)))
              if type(attribute_value) is type(0.0):
                if sql in editable_column_ids and form.has_field('%s_%s' % (field.id, alias) ):
                  # Do not truncate if editable
                  pass
                else:
                  attribute_value = "%.2f" % attribute_value
                td_align = "right"
              elif type(attribute_value) is type(1):
                td_align = "right"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1356
              else:
1357
                td_align = "left"
1358 1359
              # It is safer to convert attribute_value to an unicode string, because
              # it might be utf-8.
1360
              if type(attribute_value) == type(''):
1361
                attribute_value = unicode(attribute_value, 'utf-8')
1362 1363
              elif attribute_value is None:
                attribute_value = ''
1364 1365 1366 1367
              if sql in editable_column_ids and form.has_field('%s_%s' % (field.id, alias) ):
                key = my_field.id + '_%s' % o.uid
                if field_errors.has_key(key):
                  error_css = 'Error'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1368
                  error_message = "<br/>%s" % translate('ui', field_errors[key].error_text)
1369 1370 1371
                  # Display previous value (in case of error
                  error_list.append(field_errors.get(key))
                  display_value = REQUEST.get('field_%s' % key, attribute_value)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1372
                else:
1373 1374 1375 1376
                  error_css = ''
                  error_message = ''
                  #display_value = REQUEST.get('field_%s' % key, attribute_value)
                  display_value = attribute_value # XXX Make sure this is ok
1377 1378 1379
                #LOG('ListBox', 0, 'display_value = %r' % display_value)
                if type(display_value) == type(u''):
                  display_value = display_value.encode('utf-8')
1380 1381 1382
                cell_body = my_field.render(value = display_value, REQUEST = o, key = key)
                                                              # We use REQUEST which is not so good here
                                                              # This prevents from using standard display process
1383 1384 1385 1386 1387 1388
                # It is safer to convert cell_body to an unicode string, because
                # it might be utf-8.
                if type(cell_body) == type(''):
                  cell_body = unicode(cell_body, 'utf-8')
                #LOG('ListBox', 0, 'cell_body = %r, error_message = %r' % (cell_body, error_message))
                list_body += ('<td class=\"%s%s\">%s%s</td>' % (td_css, error_css, cell_body, error_message))
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
                # Add item to list_result_item for list render format
                if render_format == 'list':
                  list_result_item.append(my_field._get_default(self.generate_field_key(), display_value, o))
              else:
                # Check if url_columns defines a method to retrieve the URL.
                url_method = None
                for column in url_columns:
                  if sql == column[0]:
                    url_method = getattr(o, column[1], '')
                    break
                if url_method is not None:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1400
                  try:
1401
                    object_url = url_method(brain = o, selection = selection)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1402 1403 1404 1405
                    list_body = list_body + \
                      ("<td class=\"%s\" align=\"%s\"><a href=\"%s\">%s</a></td>" %
                        (td_css, td_align, object_url, attribute_value))
                  except:
1406
                    LOG('ListBox', 0, 'Could not evaluate url_method %s' % column[1], error=sys.exc_info())
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1407 1408
                    list_body = list_body + \
                      ("<td class=\"%s\" align=\"%s\">%s</td>" % (td_css, td_align, attribute_value) )
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
                else:
                  # Check if this object provides a specific URL method
                  url_method = getattr(o, 'getListItemUrl', None)
                  if url_method is None:
                    try:
                      object_url = o.absolute_url() + \
                        '/view?selection_index=%s&selection_name=%s&reset=1' % (i, selection_name)
                      list_body = list_body + \
                        ("<td class=\"%s\" align=\"%s\"><a href=\"%s\">%s</a></td>" %
                          (td_css, td_align, object_url, attribute_value))
                    except:
                      list_body = list_body + \
                        ("<td class=\"%s\" align=\"%s\">%s</td>" % (td_css, td_align, attribute_value) )
                  else:
                    try:
                      object_url = url_method(alias, i, selection_name)
                      list_body = list_body + \
                        ("<td class=\"%s\" align=\"%s\"><a href=\"%s\">%s</a></td>" %
                          (td_css, td_align, object_url, attribute_value))
                    except:
                      list_body = list_body + \
                        ("<td class=\"%s\" align=\"%s\">%s</td>" % (td_css, td_align, attribute_value) )
                # Add item to list_result_item for list render format
                if render_format == 'list': list_result_item.append(attribute_value)
1433

1434 1435 1436
            list_body = list_body + '</tr>'
            if render_format == 'list':
              list_result.append(list_result_item)
1437 1438

        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1439
        #
1440
        # Build statistics
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1441
        #
1442
        ###############################################################
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1443

1444
        # Call the stat method
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1445
        if show_stat:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1446

1447 1448 1449
          kw['select_expression'] = select_expression
          selection.edit( params = kw )

1450
          count_results = selection(method = stat_method,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1451 1452
                          context=here, REQUEST=REQUEST)
          list_body = list_body + '<tr>'
1453
          if render_format == 'list': list_result_item = []
1454 1455 1456 1457 1458 1459
          if report_tree:
            list_body += '<td class="Data">&nbsp;</td>'
          if select:
            list_body += '<td class="Data">&nbsp;</td>'
          for n in range((len(extended_columns))):
            try:
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
              sql = extended_columns[n][0]
              for column in stat_columns:
                if column[0] == sql:
                  break
              else:
                column = None
              #LOG('ListBox', 0, 'n = %s, extended_columns = %s, stat_columns = %s, column = %s' % (repr(n), repr(extended_columns), repr(stat_columns), repr(column)))
              if column is not None:
                if column[0] == column[1]:
                  alias = extended_columns[n][2]
                  value = getattr(count_results[0],alias,'')
                else:
                  value = getattr(here, column[1])
                  #LOG('ListBox', 0, 'column = %s, value = %s' % (repr(column), repr(value)))
                  if callable(value):
                    try:
                      params = dict(kw)
                      #params['operator'] = stats[n]
                      value=value(**params)
                    except:
                      LOG('ListBox', 0, 'WARNING: Could not call %s with %s: ' % (repr(value), repr(params)), error=sys.exc_info())
                      pass
                if type(value) is type(1.0):
                  list_body += '<td class="Data" align="right">%.2f</td>' % value
                else:
                  list_body += '<td class="Data">' + str(value) + '</td>'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1486
                if render_format == 'list': list_result_item.append(value)
1487
              else:
1488
                list_body += '<td class="Data">&nbsp;</td>'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1489
                if render_format == 'list': list_result_item.append(None)
1490
            except:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1491
              list_body += '<td class="Data">&nbsp;</td>'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1492
              if render_format == 'list': list_result_item.append(None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1493 1494
          list_body += '</tr>'

1495
        #LOG('ListBox', 0, 'header = %s, selection_list = %s, list_header = %s, list_search = %s, list_body = %s, footer = %s' % (type(header), type(selection_line), type(list_header), type(list_search), type(list_body), type(footer)))
1496
        list_html = header + selection_line + list_header + list_search + list_body + footer
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1497

1498 1499 1500 1501
        # Return list of brains here is render_as_list = 1
        if render_format == 'list':
          list_result.append(list_result_item)
          return list_result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1502

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        #Create DomainTree Selector and DomainTree box
        if domain_tree:
          select_tree_options = ''
          for c in domain_root_list:
            if c[0] == selection_domain_path:
              select_tree_options += """<option selected value="%s">%s</option>\n""" % (c[0], c[1])
            else:
              select_tree_options += """<option value="%s">%s</option>\n""" % (c[0], c[1])
          select_tree_header = """<select name="domain_root_url"
onChange="submitAction(this.form,'%s/portal_selections/setDomainRoot')">
        %s</select>""" % (here.getUrl(),select_tree_options)

          try:
1516 1517
            select_tree_body = makeTreeBody(form, None, selection_domain_path,
                 0, None, selection_domain_current, form.id, selection_name )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
          except KeyError:
            select_tree_body = ''

          select_tree_html = """<!-- Select Tree -->
%s
<table cellpadding="0" border="0">
%s
</table>
"""  % (select_tree_header, select_tree_body )

          return """<!-- Table Wrapping for Select Tree -->
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td valign="top">""" + """
%s
</td><td valign="top">
%s
<!-- End of Table Wrapping for Select Tree -->
</td></tr>
</table>""" % (select_tree_html,list_html)

        return list_html

ListBoxWidgetInstance = ListBoxWidget()

class ListBoxValidator(Validator.Validator):
    property_names = Validator.Validator.property_names

    def validate(self, field, key, REQUEST):
        form = field.aq_parent
        # We need to know where we get the getter from
        # This is coppied from ERP5 Form
        here = getattr(form, 'aq_parent', REQUEST)
        columns = field.get_value('columns')
        editable_columns = field.get_value('editable_columns')
        all_editable_columns = field.get_value('all_editable_columns')
        column_ids = map(lambda x: x[0], columns)
        editable_column_ids = map(lambda x: x[0], editable_columns)
        all_editable_column_ids = map(lambda x: x[0], all_editable_columns)
1556
        selection_name = field.get_value('selection_name')
1557
        #LOG('ListBoxValidator', 0, 'field = %s, selection_name = %s' % (repr(field), repr(selection_name)))
1558
        selection = here.portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST)
1559
        params = selection.getParams()
1560 1561
        portal_url = getToolByName(here, 'portal_url')
        portal = portal_url.getPortalObject()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1562 1563

        result = {}
1564
        error_result = {}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1565
        listbox_uids = REQUEST.get('%s_uid' % field.id, [])
1566
        #LOG('ListBox.validate: REQUEST',0,REQUEST)
Sebastien Robin's avatar
Sebastien Robin committed
1567
        errors = []
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
        object_list = []
        # We have two things to do in the case of temp objects,
        # the first thing is to create a list with new temp objects
        # then try to validate some data, and then create again
        # the list with a listbox as parameter. Like this we
        # can use tales expression
        for uid in listbox_uids:
          if str(uid).find('new') == 0:
            list_method = field.get_value('list_method')
            list_method = getattr(here, list_method.method_name)
1578
            object_list = list_method(REQUEST=REQUEST, **params)
1579 1580 1581 1582 1583 1584 1585 1586
            break
        listbox = {}
        for uid in listbox_uids:
          if str(uid).find('new') == 0:
            o = None
            for object in object_list:
              if object.getUid()==uid:
                o = object
1587 1588 1589 1590
            if o is None:
              # First case: dialog input to create new objects
              o = newTempBase(portal, uid[4:]) # Arghhh - XXX acquisition problem - use portal root
              o.uid = uid
1591
            listbox[uid[4:]] = {}
1592 1593
            # We first try to set a listbox corresponding to all things
            # we can validate, so that we can use the same list
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
            # as the one used for displaying the listbox
            for sql in editable_column_ids:
              alias = '_'.join(sql.split('.'))
              if '.' in sql:
                property_id = '.'.join(sql.split('.')[1:]) # Only take trailing part
              else:
                property_id = alias
              my_field_id = '%s_%s' % (field.id, alias)
              if form.has_field( my_field_id ):
                my_field = form.get_field(my_field_id)
                key = 'field_' + my_field.id + '_%s' % o.uid
                error_result_key = my_field.id + '_%s' % o.uid
                REQUEST.cell = o
                try:
                  value = my_field.validator.validate(my_field, key, REQUEST) # We need cell
                  # Here we set the property
                  listbox[uid[4:]][sql] = value
                except ValidationError, err: # XXXX import missing
                  pass
        # Here we generate again the object_list with listbox the listbox we
        # have just created
        if len(listbox)>0:
          list_method = field.get_value('list_method')
          list_method = getattr(here, list_method.method_name)
          REQUEST.set('listbox',listbox)
1619
          object_list = list_method(REQUEST=REQUEST,**params)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1620
        for uid in listbox_uids:
1621 1622
          if str(uid).find('new') == 0:
            # First case: dialog input to create new objects
1623 1624 1625 1626 1627 1628
            #o = newTempBase(here, uid[4:]) # Arghhh - XXX acquisition problem - use portal root
            #o.uid = uid
            o = None
            for object in object_list:
              if object.getUid()==uid:
                o = object
1629 1630 1631 1632
            if o is None:
              # First case: dialog input to create new objects
              o = newTempBase(portal, uid[4:]) # Arghhh - XXX acquisition problem - use portal root
              o.uid = uid
1633
            result[uid[4:]] = {}
1634 1635 1636 1637 1638 1639 1640
            for sql in editable_column_ids:
              alias = '_'.join(sql.split('.'))
              if '.' in sql:
                property_id = '.'.join(sql.split('.')[1:]) # Only take trailing part
              else:
                property_id = alias
              my_field_id = '%s_%s' % (field.id, alias)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1641 1642 1643
              if form.has_field( my_field_id ):
                my_field = form.get_field(my_field_id)
                key = 'field_' + my_field.id + '_%s' % o.uid
1644
                error_result_key = my_field.id + '_%s' % o.uid
1645
                REQUEST.cell = o
Sebastien Robin's avatar
Sebastien Robin committed
1646 1647
                try:
                  value = my_field.validator.validate(my_field, key, REQUEST) # We need cell
1648
                  result[uid[4:]][sql] = value
1649 1650 1651 1652
                except ValidationError, err: # XXXX import missing
                  #LOG("ListBox ValidationError",0,str(err))
                  err.field_id = error_result_key
                  errors.append(err)
1653 1654
          else:
            # Second case: modification of existing objects
1655 1656
            #try:
            if 1: #try:
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
              # We must try this
              # because sometimes, we can be provided bad uids
              o = here.portal_catalog.getObject(uid)
              for sql in editable_column_ids:
                alias = '_'.join(sql.split('.'))
                if '.' in sql:
                  property_id = '.'.join(sql.split('.')[1:]) # Only take trailing part
                else:
                  property_id = alias
                my_field_id = '%s_%s' % (field.id, alias)
                if form.has_field( my_field_id ):
                  my_field = form.get_field(my_field_id)
                  key = 'field_' + my_field.id + '_%s' % o.uid
                  error_result_key = my_field.id + '_%s' % o.uid
                  #if hasattr(o,cname_id): WHY THIS ????
                  # XXX This is not acceptable - we do not calculate things the same way in 2 different cases
                  REQUEST.cell = o # We need cell
                  try:
                    value = my_field.validator.validate(my_field, key, REQUEST) # We need cell
                    error_result[error_result_key] = value
                    try:
                      attribute_value = o.getProperty(property_id)
                    except:
                      attribute_value = getattr(o,property_id, None)
                    if my_field.meta_type == "MultiListField":
                      test_equal = 1
                      # Sometimes, the attribute is not a list
                      # so we need to force update
                      try:
                        for v in attribute_value:
                          if v not in value:
                            test_equal = 0
                      except:
                        test_equal = 0
                      try:
                        for v in value:
                          if v not in attribute_value:
                            test_equal = 0
                      except:
                        test_equal = 0
                    else:
                      test_equal = attribute_value == value
                    if not result.has_key(o.getUrl()):
                      result[o.getUrl()] = {}  # We always provide an empty dict - this should be improved by migrating the test of equality to Bae - it is not the purpose of ListBox to do this probably. XXX
                    if not test_equal:
                      result[o.getUrl()][sql] = value
                  except ValidationError, err: # XXXX import missing
                    #LOG("ListBox ValidationError",0,str(err))
                    err.field_id = error_result_key
                    errors.append(err)
1707 1708
            #except:
            else:
1709
              LOG("ListBox WARNING",0,"Object uid %s could not be validated" % uid)
1710
        if len(errors) > 0:
1711 1712
            LOG("ListBox FormValidationError",0,str(error_result))
            LOG("ListBox FormValidationError",0,str(errors))
1713
            raise FormValidationError(errors, error_result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
        return result

ListBoxValidatorInstance = ListBoxValidator()

class ListBox(ZMIField):
    meta_type = "ListBox"

    widget = ListBoxWidgetInstance
    validator = ListBoxValidatorInstance

1724
    security = ClassSecurityInfo()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1725

1726 1727 1728
    security.declareProtected('Access contents information', 'get_value')
    def get_value(self, id, **kw):
      if id == 'default' and kw.get('render_format') in ('list', ):
1729
        return self.widget.render(self, self.generate_field_key() , None , kw.get('REQUEST'), render_format=kw.get('render_format'))
1730
      else:
1731
        return ZMIField.get_value(self, id, **kw)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1732

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1733 1734 1735 1736 1737 1738
# Psyco
import psyco
psyco.bind(ListBoxWidget.render)
psyco.bind(ListBoxValidator.validate)