SelectionTool.py 71.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3
##############################################################################
#
4
# Copyright (c) 2002,2007 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
6 7
#
# WARNING: This program as such is intended to be used by professional
8
# programmers who take the whole responsibility of assessing all potential
Jean-Paul Smets's avatar
Jean-Paul Smets committed
9 10
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
11
# guarantees and support are strongly adviced to contract a Free Software
Jean-Paul Smets's avatar
Jean-Paul Smets committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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.
#
##############################################################################

30 31
"""
  ERP5 portal_selection tool.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33 34 35
"""

from OFS.SimpleItem import SimpleItem
from Products.CMFCore.utils import UniqueObject
36
from Products.ERP5Type.Globals import InitializeClass, DTMLFile, PersistentMapping, get_request
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37
from AccessControl import ClassSecurityInfo
38
from Products.ERP5Type.Tool.BaseTool import BaseTool
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39
from Products.ERP5Type import Permissions as ERP5Permissions
40
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
41
from Products.ERP5Form import _dtmldir
42
from Products.ERP5Form.Selection import Selection, DomainSelection
43
from ZPublisher.HTTPRequest import FileUpload
Sebastien Robin's avatar
Sebastien Robin committed
44
import md5
45
import string, re
46
from urlparse import urlsplit, urlunsplit
47 48
from zLOG import LOG, INFO
from Acquisition import aq_base
49
from Products.ERP5Type.Message import translateString
50
import warnings
51

52

53 54
_MARKER = []

Jean-Paul Smets's avatar
Jean-Paul Smets committed
55 56 57
class SelectionError( Exception ):
    pass

58
class SelectionTool( BaseTool, UniqueObject, SimpleItem ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
59 60 61 62 63 64 65 66
    """
      The SelectionTool object is the place holder for all
      methods and algorithms related to persistent selections
      in ERP5.
    """

    id              = 'portal_selections'
    meta_type       = 'ERP5 Selections'
67
    portal_type     = 'Selection Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
68 69 70 71 72 73 74
    security = ClassSecurityInfo()

    #
    #   ZMI methods
    #
    manage_options = ( ( { 'label'      : 'Overview'
                         , 'action'     : 'manage_overview'
75 76
                         },
                         { 'label'      : 'View Selections'
77
                         , 'action'     : 'manage_viewSelections'
78 79 80
                         },
                         { 'label'      : 'Configure'
                         , 'action'     : 'manage_configure'
81
                         } ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
82 83 84

    security.declareProtected( ERP5Permissions.ManagePortal
                             , 'manage_overview' )
85
    manage_overview = DTMLFile( 'explainSelectionTool', _dtmldir )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
86

87
    security.declareProtected( ERP5Permissions.ManagePortal
88 89
                             , 'manage_viewSelections' )
    manage_viewSelections = DTMLFile( 'SelectionTool_manageViewSelections', _dtmldir )
90

91 92 93 94
    security.declareProtected( ERP5Permissions.ManagePortal
                             , 'manage_configure' )
    manage_configure = DTMLFile( 'SelectionTool_configure', _dtmldir )

95 96 97 98 99 100 101 102 103 104 105
    security.declareProtected( ERP5Permissions.ManagePortal
                             , 'manage_deleteSelectionForUser' )
    def manage_deleteSelectionForUser(self, selection_name, user_id, REQUEST=None):
      """
        Delete a specified selection
      """
      self._deleteSelectionForUserFromContainer(selection_name, user_id)
      if REQUEST is not None:
        return REQUEST.RESPONSE.redirect('%s/%s' %
                (self.absolute_url(), 'manage_viewSelections'))

106 107 108 109 110 111 112 113 114 115 116
    security.declareProtected( ERP5Permissions.ManagePortal
                             , 'manage_deleteSelection' )
    def manage_deleteSelection(self, selection_name, REQUEST=None):
      """
        Relete a specified selection
      """
      self._deleteSelectionFromContainer(selection_name)
      if REQUEST is not None:
        return REQUEST.RESPONSE.redirect('%s/%s' %
                (self.absolute_url(), 'manage_viewSelections'))

117 118 119 120 121 122 123 124 125 126 127
    security.declareProtected( ERP5Permissions.ManagePortal
                             , 'manage_deleteGlobalSelection' )
    def manage_deleteGlobalSelection(self, selection_name, REQUEST=None):
      """
        Relete a specified selection
      """
      self._deleteGlobalSelectionFromContainer(selection_name)
      if REQUEST is not None:
        return REQUEST.RESPONSE.redirect('%s/%s' %
                (self.absolute_url(), 'manage_viewSelections'))

128
    # storages of SelectionTool
129 130 131 132 133 134 135 136 137 138 139
    security.declareProtected(ERP5Permissions.ManagePortal
                              , 'getStorageItemList')
    def getStorageItemList(self):
      """Return the list of available storages
      """
      #storage_item_list = [('Persistent Mapping', 'selection_data',)]
      #list of tuple may fail dtml code: zope/documenttemplate/dt_in.py +578
      storage_item_list = [['Persistent Mapping', 'selection_data']]
      memcached_plugin_list = self.portal_memcached.contentValues(portal_type='Memcached Plugin', sort_on='int_index')
      storage_item_list.extend([['/'.join((mp.getParentValue().getTitle(), mp.getTitle(),)), mp.getRelativeUrl()] for mp in memcached_plugin_list])
      return storage_item_list
140 141 142 143 144 145

    security.declareProtected( ERP5Permissions.ManagePortal, 'setStorage')
    def setStorage(self, value, RESPONSE=None):
      """
        Set the storage of Selection Tool.
      """
146
      if value in [item[1] for item in self.getStorageItemList()]:
147 148 149 150 151 152
        self.storage = value
      else:
        raise ValueError, 'Given storage type (%s) is now supported.' % (value,)
      if RESPONSE is not None:
        RESPONSE.redirect('%s/manage_configure' % (self.absolute_url()))

153
    security.declareProtected( ERP5Permissions.ManagePortal, 'getStorage')
154
    def getStorage(self, default='selection_data'):
155 156
      """return the selected storage
      """
157
      storage = getattr(aq_base(self), 'storage', default)
158
      if storage is not default:
159 160 161 162 163
        #Backward compatibility
        if storage == 'Persistent Mapping':
          storage = 'selection_data'
        elif storage == 'Memcached Tool':
          memcached_plugin_list = self.portal_memcached.contentValues(portal_type='Memcached Plugin', sort_on='int_index')
164 165 166 167
          if len(memcached_plugin_list):
            storage = memcached_plugin_list[0].getRelativeUrl()
          else:
            storage = 'selection_data'
168 169 170
      return storage

    def isMemcachedUsed(self):
171
      return 'portal_memcached' in self.getStorage()
172

Vincent Pelletier's avatar
Vincent Pelletier committed
173 174
    def _redirectToOriginalForm(self, REQUEST=None, form_id=None, dialog_id=None,
                                query_string=None,
175
                                no_reset=False, no_report_depth=False):
Vincent Pelletier's avatar
Vincent Pelletier committed
176 177
      """Redirect to the original form or dialog, using the information given
         as parameters.
178 179
         (Actually does not redirect  in the HTTP meaning because of URL
         limitation problems.)
Vincent Pelletier's avatar
Vincent Pelletier committed
180 181 182

         DEPRECATED parameters :
         query_string is used to transmit parameters from caller to callee.
183
         If no_reset is True, replace reset parameters with noreset.
Vincent Pelletier's avatar
Vincent Pelletier committed
184 185
         If no_report_depth is True, replace report_depth parameters with
         noreport_depth.
186 187 188 189
      """
      if REQUEST is None:
        return

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
190 191 192 193 194 195 196
      form = REQUEST.form
      if no_reset and form.has_key('reset'):
        form['noreset'] = form['reset'] # Kept for compatibility - might no be used anymore
        del form['reset']
      if no_report_depth and form.has_key('report_depth'):
        form['noreport_depth'] = form['report_depth'] # Kept for compatibility - might no be used anymore
        del form['report_depth']
Vincent Pelletier's avatar
Vincent Pelletier committed
197

198
      if query_string is not None:
199 200
        warnings.warn('DEPRECATED: _redirectToOriginalForm got called with a query_string. The variables must be passed in REQUEST.form.',
                      DeprecationWarning)
201
      context = REQUEST['PARENTS'][0]
Vincent Pelletier's avatar
Vincent Pelletier committed
202
      form_id = dialog_id or REQUEST.get('dialog_id', None) or form_id or REQUEST.get('form_id', 'view')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
203
      return getattr(context, form_id)()
204

205 206
    security.declareProtected(ERP5Permissions.View, 'getSelectionNameList')
    def getSelectionNameList(self, context=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
207 208 209
      """
        Returns the selection names of the current user.
      """
210 211
      if self.isMemcachedUsed():
        return []
212
      return sorted(self._getSelectionNameListFromContainer())
213

214 215 216 217 218 219 220 221
    # backward compatibility
    security.declareProtected(ERP5Permissions.View, 'getSelectionNames')
    def getSelectionNames(self, context=None, REQUEST=None):
      warnings.warn("getSelectionNames() is deprecated.\n"
                    "Please use getSelectionNameList() instead.",
                    DeprecationWarning)
      return self.getSelectionNameList(context, REQUEST)

222
    security.declareProtected(ERP5Permissions.View, 'callSelectionFor')
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    def callSelectionFor(self, selection_name, method=None, context=None, 
                                               REQUEST=None, params=None):
      """
      Calls the selection and return the list of selected documents
      or objects. Seledction method, context and parameters may be 
      overriden in a non persistent way.

      selection_name -- the name of the selectoin (string)

      method -- optional method (callable) or method path (string)
                to use instead of the persistent selection method

      context -- optional context to call the selection method on

      REQUEST -- optional REQUEST parameters (not used, only to 
                 provide API compatibility)

      params -- optional parameters which can be used to override
                default params

      TODO: is it acceptable to keep method in the API at this level
            for security reasons (XXX-JPS)
      """
246 247 248 249
      if context is None: context = self
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is None:
        return None
250
      return selection(method=method, context=context, REQUEST=REQUEST, params=params)
251

Jean-Paul Smets's avatar
Jean-Paul Smets committed
252 253 254 255 256
    security.declareProtected(ERP5Permissions.View, 'getSelectionFor')
    def getSelectionFor(self, selection_name, REQUEST=None):
      """
        Returns the selection instance for a given selection_name
      """
257 258 259 260 261
      if isinstance(selection_name, (tuple, list)):
        selection_name = selection_name[0]
      selection = self._getSelectionFromContainer(selection_name)
      if selection is not None:
        return selection.__of__(self)
262

263 264 265
    def __getitem__(self, key):
        return self.getSelectionParamsFor(key)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
266 267 268 269 270
    security.declareProtected(ERP5Permissions.View, 'setSelectionFor')
    def setSelectionFor(self, selection_name, selection_object, REQUEST=None):
      """
        Sets the selection instance for a given selection_name
      """
271 272
      if selection_object != None:
        # Set the name so that this selection itself can get its own name.
273
        selection_object.edit(name=selection_name)
274

275 276
      if self.getSelectionFor(selection_name) != selection_object:
        self._setSelectionToContainer(selection_name, selection_object)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
277

278 279
    security.declareProtected(ERP5Permissions.View, 'getSelectionParamsFor')
    def getSelectionParamsFor(self, selection_name, params=None, REQUEST=None):
280 281 282
      """
        Returns the params in the selection
      """
283 284
      if params is None:
        params = {}
285 286
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
287
        if selection.params:
288
          return selection.getParams()
289
      return params
290 291

    # backward compatibility
292 293
    security.declareProtected(ERP5Permissions.View, 'getSelectionParams')
    getSelectionParams = getSelectionParamsFor
294

Jean-Paul Smets's avatar
Jean-Paul Smets committed
295 296 297 298 299 300
    security.declareProtected(ERP5Permissions.View, 'setSelectionParamsFor')
    def setSelectionParamsFor(self, selection_name, params, REQUEST=None):
      """
        Sets the selection params for a given selection_name
      """
      selection_object = self.getSelectionFor(selection_name, REQUEST)
301
      if selection_object is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
302 303 304 305 306
        selection_object.edit(params=params)
      else:
        selection_object = Selection(params=params)
      self.setSelectionFor(selection_name, selection_object, REQUEST)

307
    security.declareProtected(ERP5Permissions.View, 'getSelectionDomainDictFor')
308 309 310 311 312 313 314 315 316 317 318
    def getSelectionDomainDictFor(self, selection_name, REQUEST=None):
      """
        Returns the Domain dict for a given selection_name
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        try:
          return selection.getDomain().asDomainDict
        except AttributeError:
          return {}

319
    security.declareProtected(ERP5Permissions.View, 'getSelectionReportDictFor')
320 321 322 323 324 325 326 327 328 329 330
    def getSelectionReportDictFor(self, selection_name, REQUEST=None):
      """
        Returns the Report dict for a given selection_name
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        try:
          return selection.getReport().asDomainDict
        except AttributeError:
          return {}

Jean-Paul Smets's avatar
Jean-Paul Smets committed
331 332 333
    security.declareProtected(ERP5Permissions.View, 'setSelectionCheckedUidsFor')
    def setSelectionCheckedUidsFor(self, selection_name, checked_uids, REQUEST=None):
      """
334
        Sets the checked uids for a given selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
335 336 337 338 339 340 341 342
      """
      selection_object = self.getSelectionFor(selection_name, REQUEST)
      if selection_object:
        selection_object.edit(checked_uids=checked_uids)
      else:
        selection_object = Selection(checked_uids=checked_uids)
      self.setSelectionFor(selection_name, selection_object, REQUEST)

343
    security.declareProtected(ERP5Permissions.View, 'updateSelectionCheckedUidList')
344 345
    def updateSelectionCheckedUidList(self, selection_name, listbox_uid, uids, REQUEST=None):
      """
346 347
        Updates the unchecked uids(listbox_uids) and checked uids (uids)
        for a given selection_name
348 349 350 351 352 353 354 355
      """
      if listbox_uid is None:
        listbox_uid = []
      if uids is None:
        uids = []
      self.uncheckAll(selection_name,listbox_uid,REQUEST=REQUEST)
      self.checkAll(selection_name,uids,REQUEST=REQUEST)

356 357 358
    security.declareProtected(ERP5Permissions.View, 'getSelectionCheckedUidsFor')
    def getSelectionCheckedUidsFor(self, selection_name, REQUEST=None):
      """
359
        Returns the checked uids for a given selection_name
360 361 362
      """
      selection_object = self.getSelectionFor(selection_name, REQUEST)
      if selection_object:
363
        return selection_object.getCheckedUids()
364 365 366
      return []

    security.declareProtected(ERP5Permissions.View, 'checkAll')
367
    def checkAll(self, list_selection_name, listbox_uid=[], REQUEST=None,
368
                 query_string=None, form_id=None):
369
      """
370
        Check uids in a given listbox_uid list for a given list_selection_name
371
      """
372
      selection_object = self.getSelectionFor(list_selection_name, REQUEST)
373 374
      if selection_object:
        selection_uid_dict = {}
375
        for uid in selection_object.checked_uids:
376 377
          selection_uid_dict[uid] = 1
        for uid in listbox_uid:
378 379
          try:
            selection_uid_dict[int(uid)] = 1
380
          except ValueError:
381
            selection_uid_dict[uid] = 1
382
        self.setSelectionCheckedUidsFor(list_selection_name, selection_uid_dict.keys(), REQUEST=REQUEST)
383 384 385
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string, no_reset=True)
386 387

    security.declareProtected(ERP5Permissions.View, 'uncheckAll')
388
    def uncheckAll(self, list_selection_name, listbox_uid=[], REQUEST=None,
389
                   query_string=None, form_id=None):
390
      """
391
        Uncheck uids in a given listbox_uid list for a given list_selection_name
392
      """
393
      selection_object = self.getSelectionFor(list_selection_name, REQUEST)
394 395
      if selection_object:
        selection_uid_dict = {}
396
        for uid in selection_object.checked_uids:
397 398
          selection_uid_dict[uid] = 1
        for uid in listbox_uid:
399 400 401
          try:
            if selection_uid_dict.has_key(int(uid)): del selection_uid_dict[int(uid)]
          except ValueError:
402
            if selection_uid_dict.has_key(uid): del selection_uid_dict[uid]
403
        self.setSelectionCheckedUidsFor(list_selection_name, selection_uid_dict.keys(), REQUEST=REQUEST)
404 405 406
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string, no_reset=True)
407

Jean-Paul Smets's avatar
Jean-Paul Smets committed
408 409 410 411 412 413 414
    security.declareProtected(ERP5Permissions.View, 'getSelectionListUrlFor')
    def getSelectionListUrlFor(self, selection_name, REQUEST=None):
      """
        Returns the URL of the list mode of selection instance
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection:
415
        return selection.getListUrl()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
416 417
      else:
        return None
418

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    security.declareProtected(ERP5Permissions.View, 'getSelectionInvertModeFor')
    def getSelectionInvertModeFor(self, selection_name, REQUEST=None):
      """Get the 'invert_mode' parameter of a selection.
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        return selection.isInvertMode()
      return 0

    security.declareProtected(ERP5Permissions.View, 'setSelectionInvertModeFor')
    def setSelectionInvertModeFor(self, selection_name,
                                  invert_mode, REQUEST=None):
      """Change the 'invert_mode' parameter of a selection.
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        selection.edit(invert_mode=invert_mode)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
436

437
    security.declareProtected(ERP5Permissions.View, 'getSelectionInvertModeUidListFor')
438 439 440 441 442 443 444 445
    def getSelectionInvertModeUidListFor(self, selection_name, REQUEST=None):
      """Get the 'invert_mode' parameter of a selection.
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        return selection.getInvertModeUidList()
      return 0

446 447 448 449 450 451 452 453 454
    security.declareProtected(ERP5Permissions.View, 'getSelectionIndexFor')
    def getSelectionIndexFor(self, selection_name, REQUEST=None):
      """Get the 'index' parameter of a selection.
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        return selection.getIndex()
      return None

Jean-Paul Smets's avatar
Jean-Paul Smets committed
455 456 457 458 459 460 461
    security.declareProtected(ERP5Permissions.View, 'setSelectionToIds')
    def setSelectionToIds(self, selection_name, selection_uids, REQUEST=None):
      """
        Sets the selection to a small list of uids of documents
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
462
        selection.edit(invert_mode=1, uids=selection_uids, checked_uids=selection_uids)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
463 464

    security.declareProtected(ERP5Permissions.View, 'setSelectionToAll')
465 466
    def setSelectionToAll(self, selection_name, REQUEST=None,
                          reset_domain_tree=False, reset_report_tree=False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
467 468 469 470 471
      """
        Resets the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
472
        selection.edit(invert_mode=0, params={}, checked_uids=[], report_opened=1)
473
        if reset_domain_tree:
474
          selection.edit(domain=None, domain_path=None, domain_list=None)
475
        if reset_report_tree:
476
          selection.edit(report=None, report_path=None, report_list=None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
477 478 479 480 481 482 483 484 485 486 487

    security.declareProtected(ERP5Permissions.View, 'setSelectionSortOrder')
    def setSelectionSortOrder(self, selection_name, sort_on, REQUEST=None):
      """
        Defines the sort order of the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        selection.edit(sort_on=sort_on)

    security.declareProtected(ERP5Permissions.View, 'setSelectionQuickSortOrder')
488
    def setSelectionQuickSortOrder(self, selection_name=None, sort_on=None, REQUEST=None,
489
                                   query_string=None, form_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
490 491 492 493
      """
        Defines the sort order of the selection directly from the listbox
        In this method, sort_on is just a string that comes from url
      """
494 495
      # selection_name, sort_on and form_id params are kept only for bacward compatibilty
      # as some test call setSelectionQuickSortOrder in url with these params
Aurel's avatar
Aurel committed
496
      listbox_id = None
497 498
      if REQUEST is not None:
        form = REQUEST.form
499
      if sort_on is None:
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
500
        listbox_id, sort_on = form["setSelectionQuickSortOrder"].split(".", 1)
501

502 503 504 505 506 507
      if REQUEST is not None:
        if listbox_id is not None:
            selection_name_key = "%s_list_selection_name" %listbox_id
            selection_name = form[selection_name_key]
        elif selection_name is None:
            selection_name = form['selection_name']
Aurel's avatar
Aurel committed
508
          
Jean-Paul Smets's avatar
Jean-Paul Smets committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        current_sort_on = self.getSelectionSortOrder(selection_name)
        # We must first switch from asc to desc and vice-versa if sort_order exists
        # in selection
        n = 0
        for current in current_sort_on:
          if current[0] == sort_on:
            n = 1
            if current[1] == 'ascending':
              new_sort_on = [(sort_on, 'descending')]
              break
            else:
              new_sort_on = [(sort_on,'ascending')]
              break
        # And if no one exists, we just set ascending sort
        if n == 0:
          new_sort_on = [(sort_on,'ascending')]
        selection.edit(sort_on=new_sort_on)

529
      if REQUEST is not None:
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
530 531
        if form.has_key('listbox_uid') and \
            form.has_key('uids'):
532 533 534
          self.uncheckAll(selection_name, REQUEST.get('listbox_uid'))
          self.checkAll(selection_name, REQUEST.get('uids'))

535 536
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string, no_reset=True)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
537 538 539 540 541 542 543 544

    security.declareProtected(ERP5Permissions.View, 'getSelectionSortOrder')
    def getSelectionSortOrder(self, selection_name, REQUEST=None):
      """
        Returns the sort order of the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is None: return ()
545
      return selection.sort_on
Jean-Paul Smets's avatar
Jean-Paul Smets committed
546 547 548 549 550 551 552 553 554 555

    security.declareProtected(ERP5Permissions.View, 'setSelectionColumns')
    def setSelectionColumns(self, selection_name, columns, REQUEST=None):
      """
        Defines the columns in the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      selection.edit(columns=columns)

    security.declareProtected(ERP5Permissions.View, 'getSelectionColumns')
556
    def getSelectionColumns(self, selection_name, columns=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
557
      """
558 559
        Returns the columns in the selection if not empty, otherwise
        returns the value of columns argument
Jean-Paul Smets's avatar
Jean-Paul Smets committed
560
      """
561
      if columns is None: columns = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
562 563
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
564 565
        if len(selection.columns) > 0:
          return selection.columns
566
      return columns
Jean-Paul Smets's avatar
Jean-Paul Smets committed
567 568 569 570 571 572 573 574 575 576 577


    security.declareProtected(ERP5Permissions.View, 'setSelectionStats')
    def setSelectionStats(self, selection_name, stats, REQUEST=None):
      """
        Defines the stats in the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      selection.edit(stats=stats)

    security.declareProtected(ERP5Permissions.View, 'getSelectionStats')
578
    def getSelectionStats(self, selection_name, stats=_MARKER, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
579 580 581
      """
        Returns the stats in the selection
      """
582 583 584 585
      if stats is not _MARKER:
        default_stats = stats
      else:
        default_stats = [' '] * 6
Jean-Paul Smets's avatar
Jean-Paul Smets committed
586 587
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
588
        return getattr(aq_base(selection), 'stats', default_stats)
589
      return default_stats
Jean-Paul Smets's avatar
Jean-Paul Smets committed
590 591 592 593 594 595 596 597 598 599 600


    security.declareProtected(ERP5Permissions.View, 'viewFirst')
    def viewFirst(self, selection_index='', selection_name='', form_id='view', REQUEST=None):
      """
        Access first item in a selection
      """
      if not REQUEST:
        REQUEST = get_request()
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection:
601
        method = self.unrestrictedTraverse(selection.method_path)
602
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
603 604 605 606
        if len(selection_list):
          o = selection_list[0]
          url = o.absolute_url()
        else:
607
          url = REQUEST.getURL()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
608
      else:
609
        url = REQUEST.getURL()
610 611
      ignore_layout = int(REQUEST.get('ignore_layout', 0))
      url = '%s/%s?selection_index=%s&selection_name=%s&ignore_layout:int=%s' % (url, form_id, 0, selection_name, ignore_layout)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
612 613 614 615 616
      REQUEST.RESPONSE.redirect(url)

    security.declareProtected(ERP5Permissions.View, 'viewLast')
    def viewLast(self, selection_index='', selection_name='', form_id='view', REQUEST=None):
      """
617
        Access last item in a selection
Jean-Paul Smets's avatar
Jean-Paul Smets committed
618 619 620 621 622
      """
      if not REQUEST:
        REQUEST = get_request()
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection:
623
        method = self.unrestrictedTraverse(selection.method_path)
624
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
625 626 627 628 629
        if len(selection_list):
          o = selection_list[-1]
          url = o.absolute_url()
        else:
          url = REQUEST.getURL()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
630
      else:
631
        url = REQUEST.getURL()
632 633
      ignore_layout = int(REQUEST.get('ignore_layout', 0))
      url = '%s/%s?selection_index=%s&selection_name=%s&ignore_layout:int=%s' % (url, form_id, -1, selection_name, ignore_layout)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
634 635 636 637 638 639 640 641 642 643 644
      REQUEST.RESPONSE.redirect(url)

    security.declareProtected(ERP5Permissions.View, 'viewNext')
    def viewNext(self, selection_index='', selection_name='', form_id='view', REQUEST=None):
      """
        Access next item in a selection
      """
      if not REQUEST:
        REQUEST = get_request()
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection:
645
        method = self.unrestrictedTraverse(selection.method_path)
646
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
Aurel's avatar
Aurel committed
647
        if len(selection_list):
648 649 650 651
          o = selection_list[(int(selection_index) + 1) % len(selection_list)]
          url = o.absolute_url()
        else:
          url = REQUEST.getURL()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
652
      else:
653
        url = REQUEST.getURL()
654 655
      ignore_layout = int(REQUEST.get('ignore_layout', 0))
      url = '%s/%s?selection_index=%s&selection_name=%s&ignore_layout:int=%s' % (url, form_id, int(selection_index) + 1, selection_name, ignore_layout)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
656 657 658 659 660 661 662 663 664 665 666
      REQUEST.RESPONSE.redirect(url)

    security.declareProtected(ERP5Permissions.View, 'viewPrevious')
    def viewPrevious(self, selection_index='', selection_name='', form_id='view', REQUEST=None):
      """
        Access previous item in a selection
      """
      if not REQUEST:
        REQUEST = get_request()
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection:
667
        method = self.unrestrictedTraverse(selection.method_path)
668
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
669 670 671 672 673
        if len(selection_list):
          o = selection_list[(int(selection_index) - 1) % len(selection_list)]
          url = o.absolute_url()
        else:
          url = REQUEST.getURL()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
674
      else:
675
        url = REQUEST.getURL()
676 677
      ignore_layout = int(REQUEST.get('ignore_layout', 0))
      url = '%s/%s?selection_index=%s&selection_name=%s&ignore_layout:int=%s' % (url, form_id, int(selection_index) - 1, selection_name, ignore_layout)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
678 679 680 681
      REQUEST.RESPONSE.redirect(url)


    # ListBox related methods
682 683

    security.declareProtected(ERP5Permissions.View, 'firstPage')
Vincent Pelletier's avatar
Vincent Pelletier committed
684
    def firstPage(self, list_selection_name, listbox_uid, uids=None, REQUEST=None):
685 686
      """
        Access the first page of a list
687 688 689
        XXX: As its complementary (lastPage) is broken, this method is
        probably not used either. If so, it should be removed along with
        lastPage.
690 691
      """
      if uids is None: uids = []
692 693 694 695 696
      selection = self.getSelectionFor(list_selection_name, REQUEST)
      if selection is not None:
        params = selection.getParams()
        params['list_start'] = 0
        selection.edit(params=params)
Vincent Pelletier's avatar
Vincent Pelletier committed
697 698
      self.uncheckAll(list_selection_name, listbox_uid)
      return self.checkAll(list_selection_name, uids, REQUEST=REQUEST)
699 700

    security.declareProtected(ERP5Permissions.View, 'lastPage')
Vincent Pelletier's avatar
Vincent Pelletier committed
701
    def lastPage(self, list_selection_name, listbox_uid, uids=None, REQUEST=None):
702 703
      """
        Access the last page of a list
704 705 706
        XXX: This method is broken, since "total_size" field is not
        present in the listbox rendering any longer. It should be
        removed.
707 708
      """
      if uids is None: uids = []
Vincent Pelletier's avatar
Vincent Pelletier committed
709
      selection = self.getSelectionFor(list_selection_name, REQUEST)
710 711 712 713 714 715 716 717 718 719 720
      if selection is not None:
        params = selection.getParams()
        # XXX This will not work if the number of lines shown in the listbox is greater
        #       than the BIG_INT constan. Such a case has low probability but is not
        #       impossible. If you are in this case, send me a mail ! -- Kev
        BIG_INT = 10000000
        last_page_start = BIG_INT
        total_lines = REQUEST.form.get('total_size', BIG_INT)
        if total_lines != BIG_INT:
          lines_per_page  = params.get('list_lines', 1)
          last_page_start = int(total_lines) - (int(total_lines) % int(lines_per_page))
721 722
        params['list_start'] = last_page_start
        selection.edit(params=params)
Vincent Pelletier's avatar
Vincent Pelletier committed
723 724
      self.uncheckAll(list_selection_name, listbox_uid)
      return self.checkAll(list_selection_name, uids, REQUEST=REQUEST)
725

Jean-Paul Smets's avatar
Jean-Paul Smets committed
726
    security.declareProtected(ERP5Permissions.View, 'nextPage')
Vincent Pelletier's avatar
Vincent Pelletier committed
727
    def nextPage(self, list_selection_name, listbox_uid, uids=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
728 729 730
      """
        Access the next page of a list
      """
731
      if uids is None: uids = []
Vincent Pelletier's avatar
Vincent Pelletier committed
732
      selection = self.getSelectionFor(list_selection_name, REQUEST)
733 734
      if selection is not None:
        params = selection.getParams()
735 736 737
        lines = int(params.get('list_lines', 0))
        form = REQUEST.form
        if form.has_key('page_start'):
738 739 740 741
          try:
            list_start = (int(form.pop('page_start', 0)) - 1) * lines
          except ValueError:
            list_start = 0
742 743
        else:
          list_start = int(form.pop('list_start', 0))
744
        params['list_start'] = max(list_start + lines, 0)
745
        selection.edit(params=params)
Vincent Pelletier's avatar
Vincent Pelletier committed
746 747
      self.uncheckAll(list_selection_name, listbox_uid)
      return self.checkAll(list_selection_name, uids, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
748 749

    security.declareProtected(ERP5Permissions.View, 'previousPage')
Vincent Pelletier's avatar
Vincent Pelletier committed
750
    def previousPage(self, list_selection_name, listbox_uid, uids=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
751 752 753
      """
        Access the previous page of a list
      """
754
      if uids is None: uids = []
Vincent Pelletier's avatar
Vincent Pelletier committed
755
      selection = self.getSelectionFor(list_selection_name, REQUEST)
756 757
      if selection is not None:
        params = selection.getParams()
758 759 760
        lines = int(params.get('list_lines', 0))
        form = REQUEST.form
        if form.has_key('page_start'):
761 762 763 764
          try:
            list_start = (int(form.pop('page_start', 0)) - 1) * lines
          except ValueError:
            list_start = 0
765 766 767
        else:
          list_start = int(form.pop('list_start', 0))
        params['list_start'] = max(list_start - lines, 0)
768
        selection.edit(params=params)
Vincent Pelletier's avatar
Vincent Pelletier committed
769 770
      self.uncheckAll(list_selection_name, listbox_uid)
      return self.checkAll(list_selection_name, uids, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
771 772

    security.declareProtected(ERP5Permissions.View, 'setPage')
Vincent Pelletier's avatar
Vincent Pelletier committed
773
    def setPage(self, list_selection_name, listbox_uid, query_string=None, uids=None, REQUEST=None):
774
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
775
         Sets the current displayed page in a selection
776
      """
777
      if uids is None: uids = []
Vincent Pelletier's avatar
Vincent Pelletier committed
778
      selection = self.getSelectionFor(list_selection_name, REQUEST)
779 780
      if selection is not None:
        params = selection.getParams()
781 782 783
        lines = int(params.get('list_lines', 0))
        form = REQUEST.form
        if form.has_key('page_start'):
784 785 786 787
          try:
            list_start = (int(form.pop('page_start', 0)) - 1) * lines
          except ValueError:
            list_start = 0
788 789
        else:
          list_start = int(form.pop('list_start', 0))
790
        params['list_start'] = max(list_start, 0)
791 792
        selection.edit(params=params)
        self.uncheckAll(list_selection_name, listbox_uid)
Vincent Pelletier's avatar
Vincent Pelletier committed
793
      return self.checkAll(list_selection_name, uids, REQUEST=REQUEST, query_string=query_string)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
794

795
    # PlanningBox related methods
796 797
    security.declareProtected(ERP5Permissions.View, 'setLanePath')
    def setLanePath(self, uids=None, REQUEST=None, form_id=None,
798
                     query_string=None):
799 800 801
      """
      Set graphic zoom level in PlanningBox
      """
802 803
      if uids is None:
        uids = []
804 805 806 807 808
      request = REQUEST
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
809 810 811
        lane_path = request.form.get('lane_path', None)
        if lane_path is None:
          # If lane_path is not defined try to 
812
          # use the last one from params
813 814 815 816 817 818
          lane_path = params.get('lane_path',1)
        bound_start = request.form.get('bound_start', None)
        if bound_start is not None:
          params['bound_start'] = bound_start
        params['lane_path'] = lane_path     
        params['zoom_variation'] = 0
819
        selection.edit(params=params)
820
      if REQUEST is not None:
821 822 823
        return self._redirectToOriginalForm(REQUEST=REQUEST,
                                            form_id=form_id,
                                            query_string=query_string)
824

825 826
    security.declareProtected(ERP5Permissions.View, 'nextLanePage')
    def nextLanePage(self, uids=None, REQUEST=None, form_id=None, query_string=None):
827 828 829
      """
      Set next graphic zoom start in PlanningBox
      """
830 831
      if uids is None:
        uids = []
832 833 834 835 836
      request = REQUEST
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
837
        params['bound_variation'] = 1
838
        selection.edit(params=params)
839
      if REQUEST is not None:
840 841 842
        return self._redirectToOriginalForm(REQUEST=REQUEST,
                                            form_id=form_id,
                                             query_string=query_string)
843

844 845
    security.declareProtected(ERP5Permissions.View, 'previousLanePage')
    def previousLanePage(self, uids=None, REQUEST=None, form_id=None, query_string=None):
846 847 848
      """
      Set previous graphic zoom in PlanningBox
      """
849 850
      if uids is None:
        uids = []
851 852 853 854 855
      request = REQUEST
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
856
        params['bound_variation'] = -1
857 858 859 860 861
        selection.edit(params=params)
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST,
                                            form_id=form_id,
                                             query_string=query_string)
862

Jean-Paul Smets's avatar
Jean-Paul Smets committed
863
    security.declareProtected(ERP5Permissions.View, 'setDomainRoot')
864
    def setDomainRoot(self, REQUEST, form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
865 866 867
      """
        Sets the root domain for the current selection
      """
868
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
869
      selection = self.getSelectionFor(selection_name, REQUEST)
870
      root_url = REQUEST.form.get('domain_root_url','portal_categories')
871
      selection.edit(domain_path=root_url, domain_list=())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
872

873 874 875
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string)
876

877 878 879 880 881 882
    security.declareProtected(ERP5Permissions.View, 'setDomainRootFromParam')
    def setDomainRootFromParam(self, REQUEST, selection_name, domain_root):
      if REQUEST is None:
        return
      selection = self.getSelectionFor(selection_name, REQUEST)
      selection.edit(domain_path=domain_root, domain_list=())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
883

884
    security.declareProtected(ERP5Permissions.View, 'unfoldDomain')
885
    def unfoldDomain(self, REQUEST, form_id=None, query_string=None):
886 887 888
      """
        Unfold domain for the current selection
      """
889
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
890
      selection = self.getSelectionFor(selection_name, REQUEST)
891 892
      domain_url = REQUEST.form.get('domain_url',None)
      domain_depth = REQUEST.form.get('domain_depth',0)
893 894
      domain_list = list(selection.getDomainList())
      domain_list = domain_list[0:min(domain_depth, len(domain_list))]
895
      if isinstance(domain_url, str):
896
        selection.edit(domain_list = domain_list + [domain_url])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
897

898 899 900
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
901

902
    security.declareProtected(ERP5Permissions.View, 'foldDomain')
903
    def foldDomain(self, REQUEST, form_id=None, query_string=None):
904 905 906
      """
        Fold domain for the current selection
      """
907
      selection_name = REQUEST.list_selection_name
908
      selection = self.getSelectionFor(selection_name, REQUEST)
909 910
      domain_url = REQUEST.form.get('domain_url',None)
      domain_depth = REQUEST.form.get('domain_depth',0)
911 912
      domain_list = list(selection.getDomainList())
      domain_list = domain_list[0:min(domain_depth, len(domain_list))]
913
      selection.edit(domain_list=[x for x in domain_list if x != domain_url])
914

915 916 917
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string)
918

919

Jean-Paul Smets's avatar
Jean-Paul Smets committed
920
    security.declareProtected(ERP5Permissions.View, 'setReportRoot')
921
    def setReportRoot(self, REQUEST, form_id=None, query_string=None):
922 923 924
      """
        Sets the root report for the current selection
      """
925
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
926
      selection = self.getSelectionFor(selection_name, REQUEST)
927
      root_url = REQUEST.form.get('report_root_url','portal_categories')
928
      selection.edit(report_path=root_url, report_list=())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
929

930 931 932
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
933 934

    security.declareProtected(ERP5Permissions.View, 'unfoldReport')
935
    def unfoldReport(self, REQUEST, form_id=None, query_string=None):
936 937 938
      """
        Unfold report for the current selection
      """
939
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
940
      selection = self.getSelectionFor(selection_name, REQUEST)
941
      report_url = REQUEST.form.get('report_url',None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
942
      if type(report_url) == type('a'):
943
        selection.edit(report_list=list(selection.getReportList()) + [report_url])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
944

945 946 947
      return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                          query_string=query_string,
                                          no_report_depth=True)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
948 949

    security.declareProtected(ERP5Permissions.View, 'foldReport')
950
    def foldReport(self, REQUEST, form_id=None, query_string=None):
951 952 953
      """
        Fold domain for the current selection
      """
954
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
955
      selection = self.getSelectionFor(selection_name, REQUEST)
956
      report_url = REQUEST.form.get('report_url',None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
957
      if type(report_url) == type('a'):
958
        report_list = selection.getReportList()
959
        selection.edit(report_list=[x for x in report_list if x != report_url])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
960

961 962 963
      return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                          query_string=query_string,
                                          no_report_depth=True)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
964

965 966 967 968
    security.declareProtected(ERP5Permissions.View, 'getListboxDisplayMode')
    def getListboxDisplayMode(self, selection_name, REQUEST=None):
      if REQUEST is None:
        REQUEST = get_request()
969
      selection = self.getSelectionFor(selection_name, REQUEST)
970

971 972 973 974 975
      if getattr(selection, 'report_tree_mode', 0):
        return 'ReportTreeMode'
      elif getattr(selection, 'domain_tree_mode', 0):
        return 'DomainTreeMode'
      return 'FlatListMode'
976

Jean-Paul Smets's avatar
Jean-Paul Smets committed
977
    security.declareProtected(ERP5Permissions.View, 'setListboxDisplayMode')
978
    def setListboxDisplayMode(self, REQUEST, listbox_display_mode,
979 980
                              selection_name=None, redirect=0,
                              form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
981
      """
982
        Toggle display of the listbox
Jean-Paul Smets's avatar
Jean-Paul Smets committed
983 984
      """
      request = REQUEST
985 986 987 988 989 990 991
      # XXX FIXME
      # Dirty fix: we must be able to change the display mode of a listbox
      # in form_view
      # But, form can have multiple listbox...
      # This need to be cleaned
      # Beware, this fix may break the report system...
      # and we don't have test for this
992 993
      # Possible fix: currently, display mode icon are implemented as
      # method. It could be easier to generate them as link (where we
994 995 996 997 998 999 1000 1001 1002
      # can define explicitely parameters through the url).
      try:
        list_selection_name = request.list_selection_name
      except AttributeError:
        pass
      else:
        if list_selection_name is not None:
          selection_name = request.list_selection_name
      # Get the selection
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1003
      selection = self.getSelectionFor(selection_name, REQUEST)
1004 1005
      if selection is None:
        selection = Selection()
1006
        self.setSelectionFor(selection_name, selection, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

      if listbox_display_mode == 'FlatListMode':
        flat_list_mode = 1
        domain_tree_mode = 0
        report_tree_mode = 0
      elif listbox_display_mode == 'DomainTreeMode':
        flat_list_mode = 0
        domain_tree_mode = 1
        report_tree_mode = 0
      elif listbox_display_mode == 'ReportTreeMode':
        flat_list_mode = 0
        domain_tree_mode = 0
        report_tree_mode = 1
1020 1021 1022
      else:
        flat_list_mode = 0
        domain_tree_mode = 0
1023
        report_tree_mode = 0
1024

1025 1026 1027
      selection.edit(flat_list_mode=flat_list_mode,
                     domain_tree_mode=domain_tree_mode,
                     report_tree_mode=report_tree_mode)
1028
      # It is better to reset the query when changing the display mode.
1029 1030
      params = selection.getParams()
      if 'where_expression' in params: del params['where_expression']
1031
      selection.edit(params=params)
1032

1033
      if redirect:
1034 1035 1036
        return self._redirectToOriginalForm(REQUEST=request, form_id=form_id,
                                            query_string=query_string,
                                            no_reset=True)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1037 1038

    security.declareProtected(ERP5Permissions.View, 'setFlatListMode')
1039
    def setFlatListMode(self, REQUEST, selection_name=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1040 1041 1042
      """
        Set display of the listbox to FlatList mode
      """
1043
      return self.setListboxDisplayMode(
1044
                       REQUEST=REQUEST, listbox_display_mode='FlatListMode',
1045
                       selection_name=selection_name, redirect=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1046 1047

    security.declareProtected(ERP5Permissions.View, 'setDomainTreeMode')
1048
    def setDomainTreeMode(self, REQUEST, selection_name=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1049 1050 1051
      """
         Set display of the listbox to DomainTree mode
      """
1052
      return self.setListboxDisplayMode(
1053
                       REQUEST=REQUEST, listbox_display_mode='DomainTreeMode',
1054
                       selection_name=selection_name, redirect=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1055 1056

    security.declareProtected(ERP5Permissions.View, 'setReportTreeMode')
1057
    def setReportTreeMode(self, REQUEST, selection_name=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1058 1059 1060
      """
        Set display of the listbox to ReportTree mode
      """
1061 1062 1063
      return self.setListboxDisplayMode(
                       REQUEST=REQUEST, listbox_display_mode='ReportTreeMode',
                       selection_name=selection_name, redirect=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1064

1065 1066 1067 1068 1069 1070
    security.declareProtected(ERP5Permissions.View, 'getSelectionSelectedValueList')
    def getSelectionSelectedValueList(self, selection_name, REQUEST=None, selection_method=None, context=None):
      """
        Get the list of values selected for 'selection_name'
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
1071 1072
      if selection is None:
        return []
1073
      return selection(method=selection_method, context=context, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1074

1075 1076 1077 1078 1079 1080
    security.declareProtected(ERP5Permissions.View, 'getSelectionCheckedValueList')
    def getSelectionCheckedValueList(self, selection_name, REQUEST=None):
      """
        Get the list of values checked for 'selection_name'
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
1081 1082
      if selection is None:
        return []
1083
      uid_list = selection.getCheckedUids()
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
      value_list = self.portal_catalog.getObjectList(uid_list)
      return value_list

    security.declareProtected(ERP5Permissions.View, 'getSelectionValueList')
    def getSelectionValueList(self, selection_name, REQUEST=None, selection_method=None, context=None):
      """
        Get the list of values checked or selected for 'selection_name'
      """
      value_list = self.getSelectionCheckedValueList(selection_name, REQUEST=REQUEST)
      if len(value_list) == 0:
1094 1095
        value_list = self.getSelectionSelectedValueList(
                                            selection_name,
1096 1097
                                            REQUEST=REQUEST,
                                            selection_method=selection_method,
1098
                                            context=context)
1099
      return value_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1100

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1101 1102 1103
    security.declareProtected(ERP5Permissions.View, 'getSelectionUidList')
    def getSelectionUidList(self, selection_name, REQUEST=None, selection_method=None, context=None):
      """
1104
        Get the list of uids checked or selected for 'selection_name'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1105
      """
1106
      return [x.getObject().getUid() for x in self.getSelectionValueList(selection_name, REQUEST=REQUEST, selection_method=selection_method, context=context)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1107

Sebastien Robin's avatar
Sebastien Robin committed
1108 1109 1110 1111 1112
    security.declareProtected(ERP5Permissions.View, 'selectionHasChanged')
    def selectionHasChanged(self, md5_string, object_uid_list):
      """
        We want to be sure that the selection did not change
      """
1113
      # XXX To avoid the difference of the string representations of int and long,
1114
      # convert each element to a string.
1115 1116 1117 1118
      object_uid_list = [str(x) for x in object_uid_list]
      object_uid_list.sort()
      new_md5_string = md5.new(str(object_uid_list)).hexdigest()
      return md5_string != new_md5_string
Sebastien Robin's avatar
Sebastien Robin committed
1119

Sebastien Robin's avatar
Sebastien Robin committed
1120

1121
    # Related document searching
1122
    def viewSearchRelatedDocumentDialog(self, index, form_id,
1123
                                        REQUEST=None, sub_index=None, **kw):
1124
      """
1125 1126
      Returns a search related document dialog
      A set of forwarders us defined to circumvent limitations of HTML
1127
      """
Romain Courteaud's avatar
Romain Courteaud committed
1128 1129
      if sub_index != None:
        REQUEST.form['sub_index'] = sub_index
1130
      object_path = REQUEST.form['object_path']
1131
      # Find the object which needs to be updated
1132
      o = self.restrictedTraverse(object_path)
1133
      # Find the field which was clicked on
1134
      # Important to get from the object instead of self
1135
      form = getattr(o, form_id)
1136
      field = None
1137 1138
      # Search the correct field
      relation_field_found = 0
1139
      relation_index = 0
1140
      # XXX may be should support another parameter,
1141
      for field in form.get_fields(include_disabled=0):
1142 1143
        if field.get_value('editable', REQUEST=REQUEST):
          try:
1144 1145
           field.get_value('is_relation_field')
          except KeyError:
1146
            pass
1147
          else:
1148 1149 1150 1151 1152
            if index == relation_index:
              relation_field_found = 1
              break
            else:
              relation_index += 1
1153
      if not relation_field_found:
1154
        # We didn't find the field...
1155
        raise SelectionError, "SelectionTool: can not find the relation" \
1156
                              " field %s" % index
1157 1158 1159 1160
      else:
        # Field found
        field_key = field.generate_field_key()
        field_value = REQUEST.form[field_key]
1161 1162
        dialog_id = field.get_value('relation_form_id') or \
                                                   'Base_viewRelatedObjectList'
1163
        redirect_form = getattr(o, dialog_id)
1164 1165 1166
        # XXX Hardcoded listbox field
        selection_name = redirect_form.listbox.get_value('selection_name')
        # Reset current selection
1167
        self.setSelectionFor(selection_name, None)
1168 1169 1170 1171


        if (field.get_value('is_multi_relation_field')) and \
           (sub_index is None):
1172 1173 1174 1175
          # user click on the wheel, not on the validation button
          # we need to facilitate user search

          # first: store current field value in the selection
1176
          base_category = field.get_value('base_category')
1177

1178 1179 1180 1181 1182 1183
          property_get_related_uid_method_name = \
            "get%sUidList" % ''.join(['%s%s' % (x[0].upper(), x[1:]) \
                                      for x in base_category.split('_')])
          current_uid_list = getattr(o, property_get_related_uid_method_name)\
                               (portal_type=[x[0] for x in \
                                  field.get_value('portal_type')])
Romain Courteaud's avatar
Romain Courteaud committed
1184 1185
          # Checked current uid
          kw ={}
1186 1187
          catalog_index = field.get_value('catalog_index')
          kw[catalog_index] = field_value
1188
          self.setSelectionParamsFor(selection_name,
Vincent Pelletier's avatar
Vincent Pelletier committed
1189 1190 1191
                                     kw.copy())
          self.setSelectionCheckedUidsFor(selection_name,
                                          current_uid_list)
1192 1193 1194 1195 1196 1197 1198
          field_value = str(field_value)
          if len(field_value):
            sql_catalog = self.portal_catalog.getSQLCatalog()
            field_value = sql_catalog.buildQuery({
              catalog_index: field_value.splitlines()
            }).asSearchTextExpression(sql_catalog, column='')

1199
          REQUEST.form[field_key] = field_value
1200
          portal_status_message = translateString("Please select one (or more) object.")
1201
        else:
1202
          portal_status_message = translateString("Please select one object.")
1203 1204


1205 1206
        # Save the current REQUEST form
        # We can't put FileUpload instances because we can't pickle them
1207 1208 1209
        saved_form_data = {}
        for key, value in REQUEST.form.items():
          if not isinstance(value, FileUpload):
1210 1211 1212
            if isinstance(value, basestring):
              value = value.encode('base64')
            saved_form_data[key] = value
1213

1214 1215
        base_category = None
        kw = {}
1216
        kw['dialog_id'] = dialog_id
1217 1218 1219 1220 1221 1222 1223 1224 1225
        kw['selection_name'] = selection_name
        kw['selection_index'] = 0 # We start on the first page
        kw['field_id'] = field.id
        parameter_list = field.get_value('parameter_list')
        if len(parameter_list) > 0:
          for k,v in parameter_list:
            kw[k] = v
        kw['reset'] = 0
        kw['base_category'] = field.get_value( 'base_category')
1226
        kw['form_id'] = form_id
1227 1228
        kw[field.get_value('catalog_index')] = field_value
        kw['portal_status_message'] = portal_status_message
1229
        kw['saved_form_data'] = saved_form_data
1230
        kw['ignore_layout'] = int(REQUEST.get('ignore_layout', 0))
1231
        kw['ignore_hide_rows'] = 1
1232 1233 1234
        # remove ignore_layout parameter from cancel_url otherwise we
        # will have two ignore_layout parameters after clicking cancel
        # button.
1235 1236 1237
        split_referer = list(urlsplit(REQUEST.get('HTTP_REFERER')))
        split_referer[3] = '&'.join([x for x in \
                                     split_referer[3].split('&') \
1238
                                     if not re.match('^ignore_layout[:=]', x)])
1239
        kw['cancel_url'] = urlunsplit(split_referer)
1240

1241 1242
        proxy_listbox_ids = field.get_value('proxy_listbox_ids')
        REQUEST.set('proxy_listbox_ids', proxy_listbox_ids)
1243
        if len(proxy_listbox_ids) == 1:
1244 1245
          REQUEST.set('proxy_listbox_id', proxy_listbox_ids[0][0])
        else:
1246
          REQUEST.set('proxy_listbox_id',
1247 1248 1249
                       "Base_viewRelatedObjectListBase/listbox")

        # Empty the selection (uid)
1250 1251
        REQUEST.form = kw # New request form
        # Define new HTTP_REFERER
Romain Courteaud's avatar
Romain Courteaud committed
1252
        REQUEST.HTTP_REFERER = '%s/%s' % (o.absolute_url(),
1253
                                          dialog_id)
1254 1255 1256 1257 1258

        # If we are called from a Web Site, we should return
        # in the context of the Web Section
        if self.getApplicableLayout() is not None:
          return getattr(o.__of__(self.getWebSectionValue()), dialog_id)(REQUEST=REQUEST)
1259
        # Return the search dialog
1260
        return getattr(o, dialog_id)(REQUEST=REQUEST)
1261

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    security.declarePublic('buildSQLJoinExpressionFromDomainSelection')
    def buildSQLJoinExpressionFromDomainSelection(self, selection_domain,
                                                  domain_id=None,
                                                  exclude_domain_id=None,
                                                  category_table_alias='category'):
      if isinstance(selection_domain, DomainSelection):
        warnings.warn("To pass a DomainSelection instance is deprecated.\n"
                      "Please use a domain dict instead.",
                      DeprecationWarning)
      else:
        selection_domain = DomainSelection(selection_domain).__of__(self)
1273 1274
      return selection_domain.asSQLJoinExpression(
          category_table_alias=category_table_alias)
1275 1276 1277

    security.declarePublic('buildSQLExpressionFromDomainSelection')
    def buildSQLExpressionFromDomainSelection(self, selection_domain,
1278
                                              table_map=None, domain_id=None,
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
                                              exclude_domain_id=None,
                                              strict_membership=0,
                                              join_table="catalog",
                                              join_column="uid",
                                              base_category=None,
                                              category_table_alias='category'):
      if isinstance(selection_domain, DomainSelection):
        warnings.warn("To pass a DomainSelection instance is deprecated.\n"
                      "Please use a domain dict instead.",
                      DeprecationWarning)
      else:
        selection_domain = DomainSelection(selection_domain).__of__(self)
1291 1292 1293 1294 1295 1296
      return selection_domain.asSQLExpression(
          strict_membership = strict_membership,
          join_table=join_table,
          join_column=join_column,
          base_category=base_category,
          category_table_alias = category_table_alias)
1297

1298 1299
    def _aq_dynamic(self, name):
      """
1300
        Generate viewSearchRelatedDocumentDialog0,
1301
                 viewSearchRelatedDocumentDialog1,... if necessary
1302 1303 1304
      """
      aq_base_name = getattr(aq_base(self), name, None)
      if aq_base_name == None:
1305 1306 1307
        DYNAMIC_METHOD_NAME = 'viewSearchRelatedDocumentDialog'
        method_name_length = len(DYNAMIC_METHOD_NAME)

1308
        zope_security = '__roles__'
1309
        if (name[:method_name_length] == DYNAMIC_METHOD_NAME) and \
1310
           (name[-len(zope_security):] != zope_security):
1311
          method_count_string_list = name[method_name_length:].split('_')
1312 1313 1314 1315
          method_count_string = method_count_string_list[0]
          # be sure that method name is correct
          try:
            method_count = string.atoi(method_count_string)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1316
          except TypeError:
1317
            return aq_base_name
1318
          else:
1319 1320 1321
            if len(method_count_string_list) > 1:
              # be sure that method name is correct
              try:
Romain Courteaud's avatar
Romain Courteaud committed
1322
                sub_index = string.atoi(method_count_string_list[1])
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1323
              except TypeError:
1324 1325
                return aq_base_name
            else:
Romain Courteaud's avatar
Romain Courteaud committed
1326
              sub_index = None
1327

1328
            # generate dynamicaly needed forwarder methods
1329
            def viewSearchRelatedDocumentDialogWrapper(self, form_id,
1330
                                                       REQUEST=None, **kw):
1331 1332 1333
              """
                viewSearchRelatedDocumentDialog Wrapper
              """
1334 1335
#               LOG('SelectionTool.viewSearchRelatedDocumentDialogWrapper, kw',
#                   0, kw)
1336
              return self.viewSearchRelatedDocumentDialog(
1337
                                   method_count, form_id,
1338
                                   REQUEST=REQUEST, sub_index=sub_index, **kw)
1339
            setattr(self.__class__, name,
1340
                    viewSearchRelatedDocumentDialogWrapper)
1341 1342

            klass = aq_base(self).__class__
1343 1344 1345 1346
            security_property_id = '%s__roles__' % (name, )
            # Declare method as public
            setattr(klass, security_property_id, None)

1347 1348 1349 1350
            return getattr(self, name)
        else:
          return aq_base_name
      return aq_base_name
1351

1352 1353
    def _getUserId(self):
      return self.portal_membership.getAuthenticatedMember().getUserName()
1354 1355
      # XXX It would be good to add somthing here
      # So that 2 anonymous users do not share the same selection
1356

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    def getTemporarySelectionDict(self):
      """ Temporary selections are used in push/pop nested scope,
      to prevent from editting for stored selection in the scope.
      Typically, it is used for ReportSection."""
      tv = getTransactionalVariable(self)
      return tv.setdefault('_temporary_selection_dict', {})

    def pushSelection(self, selection_name):
      selection = self.getSelectionFor(selection_name)
      # a temporary selection is kept in transaction.
      temp_selection = Selection()
      if selection:
        temp_selection.__dict__.update(selection.__dict__)
      self.getTemporarySelectionDict()\
        .setdefault(selection_name, []).append(temp_selection)

    def popSelection(self, selection_name):
      temporary_selection_dict = self.getTemporarySelectionDict()
      if selection_name in temporary_selection_dict and \
         temporary_selection_dict[selection_name]:
        temporary_selection_dict[selection_name].pop()

1379 1380 1381
    def _getSelectionFromContainer(self, selection_name):
      user_id = self._getUserId()
      if user_id is None: return None
1382 1383 1384 1385 1386 1387 1388

      temporary_selection_dict = self.getTemporarySelectionDict()
      if temporary_selection_dict and selection_name in temporary_selection_dict:
        if temporary_selection_dict[selection_name]:
          # focus the temporary selection in the most narrow scope.
          return temporary_selection_dict[selection_name][-1]

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
      if self.isMemcachedUsed():
        return self._getMemcachedContainer().get('%s-%s' %
                                                 (user_id, selection_name))
      else:
        return self._getPersistentContainer(user_id).get(selection_name,
                                                         None)

    def _setSelectionToContainer(self, selection_name, selection):
      user_id = self._getUserId()
      if user_id is None: return
1399 1400 1401 1402 1403 1404 1405 1406

      temporary_selection_dict = self.getTemporarySelectionDict()
      if temporary_selection_dict and selection_name in temporary_selection_dict:
        if temporary_selection_dict[selection_name]:
          # focus the temporary selection in the most narrow scope.
          temporary_selection_dict[selection_name][-1] = selection
          return

1407 1408 1409 1410 1411
      if self.isMemcachedUsed():
        self._getMemcachedContainer().set('%s-%s' % (user_id, selection_name), aq_base(selection))
      else:
        self._getPersistentContainer(user_id)[selection_name] = aq_base(selection)

1412
    def _deleteSelectionForUserFromContainer(self, selection_name, user_id):
1413 1414 1415 1416 1417 1418
      if user_id is None: return None
      if self.isMemcachedUsed():
        del(self._getMemcachedContainer()['%s-%s' % (user_id, selection_name)])
      else:
        del(self._getPersistentContainer(user_id)[selection_name])

1419 1420 1421 1422
    def _deleteSelectionFromContainer(self, selection_name):
      user_id = self._getUserId()
      self._deleteSelectionForUserFromContainer(selection_name, user_id)

1423
    def _deleteGlobalSelectionFromContainer(self, selection_name):
1424
      if not self.isMemcachedUsed():
1425 1426 1427 1428 1429 1430
        if getattr(aq_base(self), 'selection_data', None) is not None:
          for user_id in self.selection_data.keys():
            mapping = self._getPersistentContainer(user_id)
            if mapping.has_key(selection_name):
              del(mapping[selection_name])

1431 1432 1433 1434 1435 1436
    def _getSelectionNameListFromContainer(self):
      if self.isMemcachedUsed():
        return []
      else:
        user_id = self._getUserId()
        if user_id is None: return []
1437 1438 1439

        tv = getTransactionalVariable(self)
        return list(set(self._getPersistentContainer(user_id).keys() + self.getTemporarySelectionDict().keys()))
1440 1441

    def _getMemcachedContainer(self):
1442
      value = getattr(aq_base(self), '_v_selection_data', None)
1443
      if value is None:
1444 1445 1446 1447
        plugin_path = self.getStorage()
        value = self.getPortalObject().\
                portal_memcached.getMemcachedDict(key_prefix='selection_tool',
                                                  plugin_path=plugin_path)
1448 1449 1450 1451
        setattr(self, '_v_selection_data', value)
      return value

    def _getPersistentContainer(self, user_id):
1452
      if getattr(aq_base(self), 'selection_data', None) is None:
1453 1454 1455 1456 1457
        self.selection_data = PersistentMapping()
      if not self.selection_data.has_key(user_id):
        self.selection_data[user_id] = SelectionPersistentMapping()
      return self.selection_data[user_id]

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1458
InitializeClass( SelectionTool )
1459

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473

class SelectionPersistentMapping(PersistentMapping):
  """A conflict-free PersistentMapping.

  Like selection objects, the purpose is to only prevent restarting
  transactions.
  """
  def _p_independent(self) :
    return 1

  def _p_resolveConflict(self, oldState, savedState, newState):
    # update keys that only savedState has
    oldState = newState
    # dict returned by PersistentMapping.__getstate__ contains the data
1474
    # under '_container' key in zope 2.7 and 'data' in zope 2.8
Kazuhiko Shiozaki's avatar
typo.  
Kazuhiko Shiozaki committed
1475
    if 'data' in oldState:
1476 1477 1478
      oldState['data'].update(savedState['data'])
    else:
      oldState['_container'].update(savedState['_container'])
1479 1480 1481
    return oldState


1482 1483 1484 1485 1486 1487 1488 1489
class TreeListLine:
  def __init__(self,object,is_pure_summary,depth, is_open,select_domain_dict,exception_uid_list):
    self.object=object
    self.is_pure_summary=is_pure_summary
    self.depth=depth
    self.is_open=is_open
    self.select_domain_dict=select_domain_dict
    self.exception_uid_list=exception_uid_list
1490

1491 1492
  def getObject(self):
    return self.object
1493

1494 1495
  def getIsPureSummary(self):
    return self.is_pure_summary
1496

1497 1498
  def getDepth(self):
    return self.depth
1499

1500 1501
  def getIsOpen(self):
    return self.is_open
1502 1503

  def getSelectDomainDict(self):
1504
    return self.select_domain_dict
1505

1506 1507
  def getExceptionUidList(self):
    return self.exception_uid_list
1508

1509

1510
def makeTreeList(here, form, root_dict, report_path, base_category,
Nicolas Delaby's avatar
Nicolas Delaby committed
1511 1512 1513
                 depth, unfolded_list, form_id, selection_name,
                 report_depth, is_report_opened=1, list_method=None,
                 filtered_portal_types=[] ,sort_on = (('id', 'ASC'),)):
1514 1515 1516 1517 1518
  """
    (object, is_pure_summary, depth, is_open, select_domain_dict)

    select_domain_dict is a dictionary of  associative list of (id, domain)
  """
1519 1520
  if isinstance(report_path, str):
    report_path = report_path.split('/')
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

  portal_categories = getattr(form, 'portal_categories', None)
  portal_domains = getattr(form, 'portal_domains', None)
  portal_object = form.portal_url.getPortalObject()
  if len(report_path):
    base_category = report_path[0]

  if root_dict is None:
    root_dict = {}

  is_empty_level = 1
  while is_empty_level:
    if not root_dict.has_key(base_category):
      root = None
      if portal_categories is not None:
1536
        if portal_categories._getOb(base_category, None) is not None:
1537 1538 1539 1540
          if base_category == 'parent':
            # parent has a special treatment
            root = root_dict[base_category] = root_dict[None] = here
            report_path = report_path[1:]
1541
          else:
1542 1543
            root = root_dict[base_category] = root_dict[None] = \
                                               portal_categories[base_category]
1544 1545
            report_path = report_path[1:]
      if root is None and portal_domains is not None:
1546 1547 1548
        if portal_domains._getOb(base_category, None) is not None:
          root = root_dict[base_category] = root_dict[None] = \
                                               portal_domains[base_category]
1549 1550 1551
          report_path = report_path[1:]
      if root is None:
        try:
1552 1553
          root = root_dict[None] = \
              portal_object.unrestrictedTraverse(report_path)
1554
        except KeyError:
1555
          LOG('SelectionTool', INFO, "Not found %s" % str(report_path))
1556 1557 1558 1559 1560
          root = None
        report_path = ()
    else:
      root = root_dict[None] = root_dict[base_category]
      report_path = report_path[1:]
1561 1562
    is_empty_level = (root is not None) and \
        (root.objectCount() == 0) and (len(report_path) != 0)
1563
    if is_empty_level:
1564
      base_category = report_path[0]
1565 1566

  tree_list = []
1567
  if root is None:
1568
    return tree_list
1569

1570
  if base_category == 'parent':
1571 1572 1573 1574 1575
    # Use searchFolder as default
    if list_method is None:
      if hasattr(aq_base(root), 'objectValues'):
        # If this is a folder, try to browse the hierarchy
        object_list = root.searchFolder(sort_on=sort_on)
1576
    else:
1577
      if filtered_portal_types not in [[],None,'']:
1578 1579
        object_list = list_method(portal_type=filtered_portal_types,
                                  sort_on=sort_on)
1580
      else:
1581
        object_list = list_method(sort_on=sort_on)
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
    for zo in object_list:
      o = zo.getObject()
      if o is not None:
        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:
          exception_uid_list = [] # Object we do not want to display

          for sub_zo in o.searchFolder(sort_on=sort_on):
            sub_o = sub_zo.getObject()
            if sub_o is not None and hasattr(aq_base(root), 'objectValues'):
              exception_uid_list.append(sub_o.getUid())
          # Summary (open)
1598
          tree_list += [TreeListLine(o, 1, depth, 1, selection_domain, exception_uid_list)]
1599 1600
          if is_report_opened :
            # List (contents, closed, must be strict selection)
1601 1602 1603
            tree_list += [TreeListLine(o, 0, depth, 0, selection_domain, exception_uid_list)]

          tree_list += makeTreeList(here, form, new_root_dict, report_path,
1604
      		    base_category, depth + 1, unfolded_list, form_id,
1605
      		    selection_name, report_depth,
1606 1607 1608
      		    is_report_opened=is_report_opened, sort_on=sort_on)
        else:
          tree_list += [TreeListLine(o, 1, depth, 0, selection_domain, ())] # Summary (closed)
1609
  else:
1610 1611 1612 1613 1614 1615
    # process to recover objects in case a generation script is used
    if hasattr(root,'getChildDomainValueList'):
      oblist = root.getChildDomainValueList(root,depth=depth)
    else:
      oblist = root.objectValues()
    for o in oblist:
1616 1617 1618 1619 1620 1621 1622
      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 += [TreeListLine(o, 1, depth, 1, selection_domain, None)] # Summary (open)
        if is_report_opened :
          tree_list += [TreeListLine(o, 0, depth, 0, selection_domain, None)] # List (contents, closed, must be strict selection)
1623 1624
        tree_list += makeTreeList(here, form, new_root_dict, report_path, base_category, depth + 1,
            unfolded_list, form_id, selection_name, report_depth,
1625 1626 1627 1628
            is_report_opened=is_report_opened, sort_on=sort_on)
      else:

        tree_list += [TreeListLine(o, 1, depth, 0, selection_domain, None)] # Summary (closed)
1629

1630 1631
  return tree_list

1632
# Automaticaly add wrappers on Folder so it can access portal_selections.
1633
# Cannot be done in ERP5Type/Document/Folder.py because ERP5Type must not
1634
# depend on ERP5Form.
1635 1636

from Products.CMFCore.utils import getToolByName
1637
from Products.ERP5Type.Core.Folder import FolderMixIn
1638 1639
from ZPublisher.mapply import mapply

1640 1641
method_id_filter_list = [x for x in FolderMixIn.__dict__ if callable(getattr(FolderMixIn, x))]
candidate_method_id_list = [x for x in SelectionTool.__dict__ if callable(getattr(SelectionTool, x)) and not x.startswith('_') and not x.endswith('__roles__') and x not in method_id_filter_list]
1642

1643 1644 1645
# Monkey patch FolderMixIn with SelectionTool methods
#   kept here for compatibility with previous implementations
#   of Listbox HTML renderer. See bellow new implementation
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
for property_id in candidate_method_id_list:
  def portal_selection_wrapper(self, wrapper_property_id=property_id, *args, **kw):
    """
      Wrapper method for SelectionTool.
    """
    portal_selection = getToolByName(self, 'portal_selections')
    request = self.REQUEST
    method = getattr(portal_selection, wrapper_property_id)
    return mapply(method, positional=args, keyword=request,
                  context=self, bind=1)
1656
  setattr(FolderMixIn, property_id, portal_selection_wrapper)
1657 1658 1659
  security_property_id = '%s__roles__' % (property_id, )
  security_property = getattr(SelectionTool, security_property_id, None)
  if security_property is not None:
1660
    setattr(FolderMixIn, security_property_id, security_property)
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

def createFolderMixInPageSelectionMethod(listbox_id):
  """
  This method must be called by listbox at rendering time.
  It dynamically creates methods on FolderMixIn in line
  with the naming of the listbox field. Generated method
  are able to convert request parameters in order to
  mimic the API of a listbox with ID "listbox". This
  approach was required for example to implement
  multiple multi-page listboxes in view mode. It also
  opens the way towards multiple editable listboxes in the same
  page although this is something which we can not recommend.
  """
  # Immediately return in the method already exists
  test_method_id = "%s_nextPage" % listbox_id
  if hasattr(FolderMixIn, test_method_id):
    return
  # Monkey patch FolderMixIn
  for property_id in candidate_method_id_list:
    def portal_selection_wrapper(self, wrapper_listbox_id=listbox_id,
                                       wrapper_property_id=property_id, *args, **kw):
      """
        Wrapper method for SelectionTool.
      """
      portal_selection = getToolByName(self, 'portal_selections')
      request = self.REQUEST
      selection_name_property_id = "%s_list_selection_name" % listbox_id
      listbox_uid_property_id = "%s_uid" % listbox_id
      list_start_property_id = "%s_list_start" % listbox_id
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1690
      page_start_property_id = "%s_page_start" % listbox_id
1691 1692
      # Rename request parameters
      if request.has_key(selection_name_property_id):
1693
        request.form['list_selection_name'] = request[selection_name_property_id]
1694 1695 1696 1697
      if request.has_key(listbox_uid_property_id):
        request.form['listbox_uid'] = request[listbox_uid_property_id]
      if request.has_key(list_start_property_id):
        request.form['list_start'] = request[list_start_property_id]
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1698 1699
      if request.has_key(page_start_property_id):
        request.form['page_start'] = request[page_start_property_id]
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
      # Call the wrapper
      method = getattr(portal_selection, wrapper_property_id)
      return mapply(method, positional=args, keyword=request,
                    context=self, bind=1)
    new_property_id = "%s_%s" % (listbox_id, property_id)
    setattr(FolderMixIn, new_property_id, portal_selection_wrapper)
    security_property_id = '%s__roles__' % (property_id, )
    security_property = getattr(SelectionTool, security_property_id, None)
    if security_property is not None:
      new_security_property_id = '%s__roles__' % (new_property_id, )
1710
      setattr(FolderMixIn, new_security_property_id, security_property)