SelectionTool.py 55.3 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 30
"""
  ERP5 portal_selection tool.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32
"""

33
from OFS.Traversable import NotFound
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35 36
from OFS.SimpleItem import SimpleItem
from Products.CMFCore.utils import UniqueObject
from Globals import InitializeClass, DTMLFile, PersistentMapping, get_request
37
from ZTUtils import make_query
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38 39 40
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions as ERP5Permissions
from Products.ERP5Form import _dtmldir
41
from Selection import Selection, DomainSelection
42
from ZPublisher.HTTPRequest import FileUpload
Sebastien Robin's avatar
Sebastien Robin committed
43 44
from email.MIMEBase import MIMEBase
from email import Encoders
Sebastien Robin's avatar
Sebastien Robin committed
45
from copy import copy
46
from DateTime import DateTime
Sebastien Robin's avatar
Sebastien Robin committed
47
import md5
Sebastien Robin's avatar
Sebastien Robin committed
48 49 50
import pickle
import hmac
import random
51
import re
52
import string
Jean-Paul Smets's avatar
Jean-Paul Smets committed
53
from zLOG import LOG
54
from Acquisition import Implicit, aq_base
55
from Products.ERP5Type.Message import Message
56

Jean-Paul Smets's avatar
Jean-Paul Smets committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
class SelectionError( Exception ):
    pass

class SelectionTool( UniqueObject, SimpleItem ):
    """
      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'

    security = ClassSecurityInfo()

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

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

86 87 88
    security.declareProtected( ERP5Permissions.ManagePortal
                             , 'manage_view_selections' )
    manage_view_selections = DTMLFile( 'SelectionTool_manageViewSelections', _dtmldir )
89 90 91 92 93 94 95 96 97 98 99 100 101

    _query_string_reset_regexp = re.compile('\\breset(:int|)?=')
    _query_string_report_depth_regexp = re.compile('\\breport_depth(:int|)?=')
    def _redirectToOriginalForm(self, REQUEST=None, form_id=None, query_string=None,
                                no_reset=False, no_report_depth=False):
      """Redirect to the original form, using the information given as parameters.
         If no_reset is True, replace reset parameters with noreset.
         If no_report_depth is True, replace report_depth parameters with noreport_depth.
      """
      if REQUEST is None:
        return

      context = self.aq_parent
102
      form_id = form_id or REQUEST.get('form_id', 'view')
103 104 105 106 107 108 109 110 111 112 113
      url = context.absolute_url() + '/' + form_id
      if query_string is not None:
        if no_reset:
          query_string = self._query_string_reset_regexp.sub('noreset\\1=',
                                                             query_string)
        if no_report_depth:
          query_string = self._query_string_report_depth_regexp.sub('noreport_depth\\1=',
                                                                    query_string)
        url = url + '?' + query_string
      return REQUEST.RESPONSE.redirect(url)

114 115 116 117 118 119 120 121 122 123 124
    security.declareProtected(ERP5Permissions.View, 'getSelectionNames')
    def getSelectionNames(self, context=None, REQUEST=None):
      if context is None: context = self
      if not REQUEST:
        REQUEST = get_request()
        if hasattr(self, 'selection_data'):
          user_id = self.portal_membership.getAuthenticatedMember().getUserName()
        if user_id is not None and self.selection_data.has_key(user_id):
          return self.selection_data[user_id].keys()
      return ()

125 126 127 128 129 130 131 132
    security.declareProtected(ERP5Permissions.View, 'callSelectionFor')
    def callSelectionFor(self, selection_name, context=None, REQUEST=None):
      if context is None: context = self
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is None:
        return None
      return selection(context=context)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
133 134 135 136 137 138 139
    security.declareProtected(ERP5Permissions.View, 'getSelectionFor')
    def getSelectionFor(self, selection_name, REQUEST=None):
      """
        Returns the selection instance for a given selection_name
      """
      if not REQUEST:
        REQUEST = get_request()
140

141 142 143 144 145 146
      if not hasattr(self, 'selection_data'):
        self.selection_data = PersistentMapping()
      user_id = self.portal_membership.getAuthenticatedMember().getUserName()
      if user_id is not None:
        if not self.selection_data.has_key(user_id):
          self.selection_data[user_id] = PersistentMapping()
147 148
        if type(selection_name) is type(()) or type(selection_name) is type([]) :
          selection_name = selection_name[0]
149 150
        return self.selection_data[user_id].get(selection_name, None)
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
151
        return None
152

Jean-Paul Smets's avatar
Jean-Paul Smets committed
153 154 155 156 157
    security.declareProtected(ERP5Permissions.View, 'setSelectionFor')
    def setSelectionFor(self, selection_name, selection_object, REQUEST=None):
      """
        Sets the selection instance for a given selection_name
      """
158 159 160
      if selection_object != None:
        # Set the name so that this selection itself can get its own name.
        selection_object.edit(name = selection_name)
161

Jean-Paul Smets's avatar
Jean-Paul Smets committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
      if not REQUEST:
        REQUEST = get_request()
      # New system: store directly - bypass session
      if 0:
        user_id = self.portal_membership.getAuthenticatedMember().getUserName()
        if user_id is not None:
          self.selection_data.set((user_id, selection_name), selection_object)
        return

      # Another method: local dict
      if 0:
        if not hasattr(self, 'selection_data'):
          self.selection_data = PersistentMapping()
        user_id = self.portal_membership.getAuthenticatedMember().getUserName()
        if user_id is not None:
          self.selection_data[(user_id, selection_name)] = selection_object
        return

      # Another method: local dict but 2 stage to prevent user conflict
      if 1:
        if not hasattr(self, 'selection_data'):
          self.selection_data = PersistentMapping()
        user_id = self.portal_membership.getAuthenticatedMember().getUserName()
        if user_id is not None:
          if not self.selection_data.has_key(user_id):
            self.selection_data[user_id] = PersistentMapping()
          self.selection_data[user_id][selection_name] = selection_object
        return

      #try: CAUSES PROBLEMS WHY ??
      if 1:
        session = REQUEST.SESSION
        selection_name = selection_name + '_selection_object'
        session[selection_name] = selection_object
      #except:
      #  LOG('WARNING ERP5Form SelectionTool',0,'Could not set Selection')

199 200
    security.declareProtected(ERP5Permissions.View, 'getSelectionParamsFor')
    def getSelectionParamsFor(self, selection_name, params=None, REQUEST=None):
201 202 203
      """
        Returns the params in the selection
      """
204
      if params is None: params = {}
205 206
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
207 208
        if len(selection.params) > 0:
          return selection.getParams()
209 210 211 212
        else:
          return params
      else:
        return params
213 214

    # backward compatibility
215 216
    security.declareProtected(ERP5Permissions.View, 'getSelectionParams')
    getSelectionParams = getSelectionParamsFor
217

Jean-Paul Smets's avatar
Jean-Paul Smets committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    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)
      if selection_object:
        selection_object.edit(params=params)
      else:
        selection_object = Selection(params=params)
      self.setSelectionFor(selection_name, selection_object, REQUEST)

    security.declareProtected(ERP5Permissions.View, 'setSelectionCheckedUidsFor')
    def setSelectionCheckedUidsFor(self, selection_name, checked_uids, REQUEST=None):
      """
        Sets the selection params for a given selection_name
      """
      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)

242 243 244 245 246 247 248 249 250 251 252
    def updateSelectionCheckedUidList(self, selection_name, listbox_uid, uids, REQUEST=None):
      """
        Sets the selection params for a given selection_name
      """
      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)

253 254 255 256 257 258 259
    security.declareProtected(ERP5Permissions.View, 'getSelectionCheckedUidsFor')
    def getSelectionCheckedUidsFor(self, selection_name, REQUEST=None):
      """
        Sets the selection params for a given selection_name
      """
      selection_object = self.getSelectionFor(selection_name, REQUEST)
      if selection_object:
260
        #return selection_object.selection_checked_uids
261
        return selection_object.getCheckedUids()
262 263 264
      return []

    security.declareProtected(ERP5Permissions.View, 'checkAll')
265 266
    def checkAll(self, selection_name, listbox_uid=[], REQUEST=None,
                 query_string=None, form_id=None):
267 268 269 270 271 272
      """
        Sets the selection params for a given selection_name
      """
      selection_object = self.getSelectionFor(selection_name, REQUEST)
      if selection_object:
        selection_uid_dict = {}
273
        for uid in selection_object.checked_uids:
274 275
          selection_uid_dict[uid] = 1
        for uid in listbox_uid:
276 277
          try:
            selection_uid_dict[int(uid)] = 1
278
          except ValueError:
279
            selection_uid_dict[uid] = 1
280
        self.setSelectionCheckedUidsFor(selection_name, selection_uid_dict.keys(), REQUEST=REQUEST)
281 282 283
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string, no_reset=True)
284 285

    security.declareProtected(ERP5Permissions.View, 'uncheckAll')
286 287
    def uncheckAll(self, selection_name, listbox_uid=[], REQUEST=None,
                   query_string=None, form_id=None):
288 289 290 291 292 293
      """
        Sets the selection params for a given selection_name
      """
      selection_object = self.getSelectionFor(selection_name, REQUEST)
      if selection_object:
        selection_uid_dict = {}
294
        for uid in selection_object.checked_uids:
295 296
          selection_uid_dict[uid] = 1
        for uid in listbox_uid:
297 298 299
          try:
            if selection_uid_dict.has_key(int(uid)): del selection_uid_dict[int(uid)]
          except ValueError:
300
            if selection_uid_dict.has_key(uid): del selection_uid_dict[uid]
301
        self.setSelectionCheckedUidsFor(selection_name, selection_uid_dict.keys(), REQUEST=REQUEST)
302 303 304
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string, no_reset=True)
305

Jean-Paul Smets's avatar
Jean-Paul Smets committed
306 307 308 309 310 311 312
    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:
313
        return selection.getListUrl()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
314 315
      else:
        return None
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    
    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
334 335 336 337 338 339 340 341

    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:
342
        selection.edit(invert_mode=1, uids=selection_uids, checked_uids=selection_uids)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
343 344

    security.declareProtected(ERP5Permissions.View, 'setSelectionToAll')
345 346
    def setSelectionToAll(self, selection_name, REQUEST=None,
                          reset_domain_tree=False, reset_report_tree=False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
347 348 349 350 351
      """
        Resets the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
352
        selection.edit(invert_mode=0, params={}, checked_uids=[], report_opened=1)
353
        if reset_domain_tree:
354
          selection.edit(domain=None, domain_path=None, domain_list=None)
355
        if reset_report_tree:
356
          selection.edit(report=None, report_path=None, report_list=None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
357 358 359 360 361 362 363 364 365 366 367

    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')
368 369
    def setSelectionQuickSortOrder(self, selection_name, sort_on, REQUEST=None,
                                   query_string=None, form_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
      """
        Defines the sort order of the selection directly from the listbox
        In this method, sort_on is just a string that comes from url
      """
      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)

394 395 396
      if REQUEST is not None:
        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
397 398 399 400 401 402 403 404

    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 ()
405
      return selection.sort_on
Jean-Paul Smets's avatar
Jean-Paul Smets committed
406 407 408 409 410 411 412 413 414 415

    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')
416
    def getSelectionColumns(self, selection_name, columns=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
417 418 419
      """
        Returns the columns in the selection
      """
420
      if columns is None: columns = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
421 422
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
423 424
        if len(selection.columns) > 0:
          return selection.columns
425
      return columns
Jean-Paul Smets's avatar
Jean-Paul Smets committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443


    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')
    def getSelectionStats(self, selection_name, stats=[' ',' ',' ',' ',' ',' '], REQUEST=None):
      """
        Returns the stats in the selection
      """
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        try:
444
          return selection.stats
Yoshinori Okuji's avatar
Yoshinori Okuji committed
445
        except AttributeError:
446
          return stats # That is really bad programming XXX
Jean-Paul Smets's avatar
Jean-Paul Smets committed
447 448 449 450 451 452 453 454 455 456 457 458 459
      else:
        return stats


    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:
460
        method = self.unrestrictedTraverse(selection.method_path)
461 462
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
        o = selection_list[0]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        url = o.absolute_url()
      else:
        url = REQUEST.url
      url = '%s/%s?selection_index=%s&selection_name=%s' % (url, form_id, 0, selection_name)
      REQUEST.RESPONSE.redirect(url)

    security.declareProtected(ERP5Permissions.View, 'viewLast')
    def viewLast(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:
478
        method = self.unrestrictedTraverse(selection.method_path)
479 480
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
        o = selection_list[-1]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        url = o.absolute_url()
      else:
        url = REQUEST.url
      url = '%s/%s?selection_index=%s&selection_name=%s' % (url, form_id, -1, selection_name)
      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:
496
        method = self.unrestrictedTraverse(selection.method_path)
497 498
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
        o = selection_list[(int(selection_index) + 1) % len(selection_list)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
        url = o.absolute_url()
      else:
        url = REQUEST.url
      url = '%s/%s?selection_index=%s&selection_name=%s' % (url, form_id, int(selection_index) + 1, selection_name)
      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:
514
        method = self.unrestrictedTraverse(selection.method_path)
515 516
        selection_list = selection(method = method, context=self, REQUEST=REQUEST)
        o = selection_list[(int(selection_index) - 1) % len(selection_list)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
517 518 519 520 521 522 523 524
        url = o.absolute_url()
      else:
        url = REQUEST.url
      url = '%s/%s?selection_index=%s&selection_name=%s' % (url, form_id, int(selection_index) - 1, selection_name)
      REQUEST.RESPONSE.redirect(url)


    # ListBox related methods
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

    security.declareProtected(ERP5Permissions.View, 'firstPage')
    def firstPage(self, listbox_uid, uids=None, REQUEST=None):
      """
        Access the first page of a list
      """
      if uids is None: uids = []
      request = REQUEST
      #form_id = request.form_id
      selection_name = request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST)
      params = selection.getParams()
      params['list_start'] = 0
      selection.edit(params=params)
      self.uncheckAll(selection_name, listbox_uid)
      return self.checkAll(selection_name, uids, REQUEST=REQUEST)

    security.declareProtected(ERP5Permissions.View, 'lastPage')
    def lastPage(self, listbox_uid, uids=None, REQUEST=None):
      """
        Access the last page of a list
      """
      if uids is None: uids = []
      request = REQUEST
      #form_id = request.form_id
      selection_name = request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST)
      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))
      params['list_start'] = last_page_start
      selection.edit(params=params)
      self.uncheckAll(selection_name, listbox_uid)
      return self.checkAll(selection_name, uids, REQUEST=REQUEST)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
567
    security.declareProtected(ERP5Permissions.View, 'nextPage')
568
    def nextPage(self, listbox_uid, uids=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
569 570 571
      """
        Access the next page of a list
      """
572
      if uids is None: uids = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
573
      request = REQUEST
574
      #form_id = request.form_id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
575 576
      selection_name = request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST)
577
      params = selection.getParams()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
578 579 580
      lines = params.get('list_lines',0)
      start = params.get('list_start', 0)
      params['list_start'] = int(start) + int(lines)
581
      selection.edit(params=params)
582 583
      self.uncheckAll(selection_name, listbox_uid)
      return self.checkAll(selection_name, uids, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
584 585

    security.declareProtected(ERP5Permissions.View, 'previousPage')
586
    def previousPage(self, listbox_uid, uids=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
587 588 589
      """
        Access the previous page of a list
      """
590
      if uids is None: uids = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
591
      request = REQUEST
592
      #form_id = request.form_id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
593 594
      selection_name = request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST)
595
      params = selection.getParams()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
596 597 598
      lines = params.get('list_lines',0)
      start = params.get('list_start', 0)
      params['list_start'] = max(int(start) - int(lines), 0)
599
      selection.edit(params=selection.params)
600 601
      self.uncheckAll(selection_name, listbox_uid)
      return self.checkAll(selection_name, uids, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
602 603

    security.declareProtected(ERP5Permissions.View, 'setPage')
604
    def setPage(self, listbox_uid, query_string=None, uids=None, REQUEST=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
605 606 607
      """
        Access the previous page of a list
      """
608
      if uids is None: uids = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
609
      request = REQUEST
610
      #form_id = request.form_id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
611 612 613
      selection_name = request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
614
        params = selection.getParams()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
615 616 617
        lines = params.get('list_lines',0)
        start = request.form.get('list_start',0)
        params['list_start'] = start
618
        selection.edit(params= selection.params)
619
      self.uncheckAll(selection_name, listbox_uid)
620 621
      return self.checkAll(selection_name, uids, REQUEST=REQUEST, query_string=query_string)

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

623
    # PlanningBox related methods
624

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    security.declareProtected(ERP5Permissions.View, 'setZoomLevel')
    def setZoomLevel(self, uids=None, REQUEST=None):
      """
      Set graphic zoom level in PlanningBox
      """
      if uids is None: uids = []
      request = REQUEST
      #zoom_level=request.get('zoom_level')
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
        zoom_level = request.form.get('zoom_level',1)
        zoom_start = request.form.get('zoom_start',0)
        params['zoom_level'] = zoom_level
        if zoom_level <= zoom_start:
          zoom_start = max(int(float(zoom_level)),1) - 1
          params['zoom_start'] = zoom_start
        selection.edit(params= params)
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST)

647
    security.declareProtected(ERP5Permissions.View, 'setZoom')
648
    def setZoom(self, uids=None, REQUEST=None):
649 650
      """
      Set graphic zoom in PlanningBox
651
      """
652
      if uids is None: uids = []
653
      request = REQUEST
654 655 656 657
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
658 659
        zoom_start = request.form.get('zoom_start')
        params['zoom_start'] = zoom_start
660
        selection.edit(params= params)
661
      if REQUEST is not None:
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
        return self._redirectToOriginalForm(REQUEST=REQUEST)

    security.declareProtected(ERP5Permissions.View, 'nextZoom')
    def nextZoom(self, uids=None, REQUEST=None):
      """
      Set next graphic zoom start in PlanningBox
      """
      if uids is None: uids = []
      request = REQUEST
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
        zoom_start = params.get('zoom_start')
        params['zoom_start'] = int(zoom_start) + 1
        selection.edit(params= params)
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST)

    security.declareProtected(ERP5Permissions.View, 'previousZoom')
    def previousZoom(self, uids=None, REQUEST=None):
      """
      Set previous graphic zoom in PlanningBox
      """
      if uids is None: uids = []
      request = REQUEST
      selection_name=request.list_selection_name
      selection = self.getSelectionFor(selection_name, REQUEST=REQUEST)
      if selection is not None:
        params = selection.getParams()
        zoom_start = params.get('zoom_start')
        params['zoom_start'] = int(zoom_start) - 1
        selection.edit(params= params)
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST)
697

Jean-Paul Smets's avatar
Jean-Paul Smets committed
698
    security.declareProtected(ERP5Permissions.View, 'setDomainRoot')
699
    def setDomainRoot(self, REQUEST, form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
700 701 702
      """
        Sets the root domain for the current selection
      """
703
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
704
      selection = self.getSelectionFor(selection_name, REQUEST)
705
      root_url = REQUEST.form.get('domain_root_url','portal_categories')
706
      selection.edit(domain_path=root_url, domain_list=())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
707

708 709 710
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string)
711 712 713 714 715 716 717
                                            
    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
718

719
    security.declareProtected(ERP5Permissions.View, 'unfoldDomain')
720
    def unfoldDomain(self, REQUEST, form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
721 722 723
      """
        Sets the root domain for the current selection
      """
724
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
725
      selection = self.getSelectionFor(selection_name, REQUEST)
726 727
      domain_url = REQUEST.form.get('domain_url',None)
      domain_depth = REQUEST.form.get('domain_depth',0)
728 729
      domain_list = list(selection.getDomainList())
      domain_list = domain_list[0:min(domain_depth, len(domain_list))]
730
      if isinstance(domain_url, str):
731
        selection.edit(domain_list = domain_list + [domain_url])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
732

733 734 735
      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
736

737
    security.declareProtected(ERP5Permissions.View, 'foldDomain')
738
    def foldDomain(self, REQUEST, form_id=None, query_string=None):
739 740 741
      """
        Sets the root domain for the current selection
      """
742
      selection_name = REQUEST.list_selection_name
743
      selection = self.getSelectionFor(selection_name, REQUEST)
744 745
      domain_url = REQUEST.form.get('domain_url',None)
      domain_depth = REQUEST.form.get('domain_depth',0)
746 747
      domain_list = list(selection.getDomainList())
      domain_list = domain_list[0:min(domain_depth, len(domain_list))]
748
      selection.edit(domain_list=[x for x in domain_list if x != domain_url])
749

750 751 752
      if REQUEST is not None:
        return self._redirectToOriginalForm(REQUEST=REQUEST, form_id=form_id,
                                            query_string=query_string)
753

754

Jean-Paul Smets's avatar
Jean-Paul Smets committed
755
    security.declareProtected(ERP5Permissions.View, 'setReportRoot')
756
    def setReportRoot(self, REQUEST, form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
757 758 759
      """
        Sets the root domain for the current selection
      """
760
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
761
      selection = self.getSelectionFor(selection_name, REQUEST)
762
      root_url = REQUEST.form.get('report_root_url','portal_categories')
763
      selection.edit(report_path=root_url, report_list=())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
764

765 766 767
      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
768 769

    security.declareProtected(ERP5Permissions.View, 'unfoldReport')
770
    def unfoldReport(self, REQUEST, form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
771 772
      """
        Sets the root domain for the current selection
773

774
        report_list is a list of relative_url of category, domain, etc.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
775
      """
776
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
777
      selection = self.getSelectionFor(selection_name, REQUEST)
778
      report_url = REQUEST.form.get('report_url',None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
779
      if type(report_url) == type('a'):
780
        selection.edit(report_list=list(selection.getReportList()) + [report_url])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
781

782 783 784
      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
785 786

    security.declareProtected(ERP5Permissions.View, 'foldReport')
787
    def foldReport(self, REQUEST, form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
788 789 790
      """
        Sets the root domain for the current selection
      """
791
      selection_name = REQUEST.list_selection_name
Jean-Paul Smets's avatar
Jean-Paul Smets committed
792
      selection = self.getSelectionFor(selection_name, REQUEST)
793
      report_url = REQUEST.form.get('report_url',None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
794
      if type(report_url) == type('a'):
795
        report_list = selection.getReportList()
796
        selection.edit(report_list=[x for x in report_list if x != report_url])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
797

798 799 800
      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
801

802 803 804 805
    security.declareProtected(ERP5Permissions.View, 'getListboxDisplayMode')
    def getListboxDisplayMode(self, selection_name, REQUEST=None):
      if REQUEST is None:
        REQUEST = get_request()
806
      selection = self.getSelectionFor(selection_name, REQUEST)
807

808 809 810 811 812
      if getattr(selection, 'report_tree_mode', 0):
        return 'ReportTreeMode'
      elif getattr(selection, 'domain_tree_mode', 0):
        return 'DomainTreeMode'
      return 'FlatListMode'
813

Jean-Paul Smets's avatar
Jean-Paul Smets committed
814
    security.declareProtected(ERP5Permissions.View, 'setListboxDisplayMode')
815
    def setListboxDisplayMode(self, REQUEST, listbox_display_mode,
816 817
                              selection_name=None, redirect=0,
                              form_id=None, query_string=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
818 819 820 821
      """
        Toogle display of the listbox
      """
      request = REQUEST
822 823 824 825 826 827 828
      # 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
829 830
      # Possible fix: currently, display mode icon are implemented as
      # method. It could be easier to generate them as link (where we
831 832 833 834 835 836 837 838 839
      # 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
840
      selection = self.getSelectionFor(selection_name, REQUEST)
841 842
      if selection is None:
        selection = Selection()
843
        self.setSelectionFor(selection_name, selection, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
844 845 846 847 848 849 850 851 852 853 854 855 856

      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
857 858 859
      else:
        flat_list_mode = 0
        domain_tree_mode = 0
860
        report_tree_mode = 0
861

862 863 864
      selection.edit(flat_list_mode=flat_list_mode,
                     domain_tree_mode=domain_tree_mode,
                     report_tree_mode=report_tree_mode)
865
      # It is better to reset the query when changing the display mode.
866 867
      params = selection.getParams()
      if 'where_expression' in params: del params['where_expression']
868 869
      selection.edit(params = params)

870
      if redirect:
871 872 873
        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
874 875

    security.declareProtected(ERP5Permissions.View, 'setFlatListMode')
876
    def setFlatListMode(self, REQUEST, selection_name=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
877 878 879
      """
        Set display of the listbox to FlatList mode
      """
880
      return self.setListboxDisplayMode(
881
                       REQUEST=REQUEST, listbox_display_mode='FlatListMode',
882
                       selection_name=selection_name, redirect=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
883 884

    security.declareProtected(ERP5Permissions.View, 'setDomainTreeMode')
885
    def setDomainTreeMode(self, REQUEST, selection_name=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
886 887 888
      """
         Set display of the listbox to DomainTree mode
      """
889
      return self.setListboxDisplayMode(
890
                       REQUEST=REQUEST, listbox_display_mode='DomainTreeMode',
891
                       selection_name=selection_name, redirect=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
892 893

    security.declareProtected(ERP5Permissions.View, 'setReportTreeMode')
894
    def setReportTreeMode(self, REQUEST, selection_name=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
895 896 897
      """
        Set display of the listbox to ReportTree mode
      """
898 899 900
      return self.setListboxDisplayMode(
                       REQUEST=REQUEST, listbox_display_mode='ReportTreeMode',
                       selection_name=selection_name, redirect=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
901

902 903 904 905 906 907
    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)
908 909
      if selection is None:
        return []
910
      return selection(method=selection_method, context=context, REQUEST=REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
911

912 913 914 915 916 917
    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)
918 919
      if selection is None:
        return []
920
      uid_list = selection.getCheckedUids()
921 922 923 924 925 926 927 928 929 930
      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:
931 932
        value_list = self.getSelectionSelectedValueList(
                                            selection_name,
933 934
                                            REQUEST=REQUEST,
                                            selection_method=selection_method,
935
                                            context=context)
936
      return value_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
937

Jean-Paul Smets's avatar
Jean-Paul Smets committed
938 939 940 941 942 943 944
    security.declareProtected(ERP5Permissions.View, 'getSelectionUidList')
    def getSelectionUidList(self, selection_name, REQUEST=None, selection_method=None, context=None):
      """
        Get the list of values checked or selected for 'selection_name'
      """
      return map(lambda x:x.getObject().getUid(), self.getSelectionValueList(selection_name, REQUEST=REQUEST, selection_method=selection_method, context=context))

Sebastien Robin's avatar
Sebastien Robin committed
945 946 947 948 949
    security.declareProtected(ERP5Permissions.View, 'selectionHasChanged')
    def selectionHasChanged(self, md5_string, object_uid_list):
      """
        We want to be sure that the selection did not change
      """
950
      # XXX To avoid the difference of the string representations of int and long,
951
      # convert each element to a string.
952 953 954 955
      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
956

957 958
    security.declareProtected(ERP5Permissions.View, 'getPickle')
    def getPickle(self,**kw):
Sebastien Robin's avatar
Sebastien Robin committed
959 960 961 962
      """
      we give many keywords and we will get the corresponding
      pickle string and signature
      """
Yoshinori Okuji's avatar
Yoshinori Okuji committed
963
      #LOG('getPickle kw',0,kw)
964 965 966
      # XXX Remove DateTime, This is really bad, only use for zope 2.6
      # XXX This has to be removed as quickly as possible
      for k,v in kw.items():
Sebastien Robin's avatar
Sebastien Robin committed
967
        if isinstance(v,DateTime):
968 969
          del kw[k]
      # XXX End of the part to remove
970
      #LOG('SelectionTool.getPickle, kw',0,kw)
Sebastien Robin's avatar
Sebastien Robin committed
971 972 973 974 975 976
      pickle_string = pickle.dumps(kw)
      msg = MIMEBase('application','octet-stream')
      msg.set_payload(pickle_string)
      Encoders.encode_base64(msg)
      pickle_string = msg.get_payload()
      pickle_string = pickle_string.replace('\n','@@@')
977 978 979 980 981 982 983 984
      return pickle_string

    security.declareProtected(ERP5Permissions.View, 'getPickleAndSignature')
    def getPickleAndSignature(self,**kw):
      """
      we give many keywords and we will get the corresponding
      pickle string and signature
      """
985
      cookie_password = self._getCookiePassword()
986
      pickle_string = self.getPickle(**kw)
Sebastien Robin's avatar
Sebastien Robin committed
987 988 989
      signature = hmac.new(cookie_password,pickle_string).hexdigest()
      return (pickle_string,signature)

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    security.declareProtected(ERP5Permissions.View, 'getObjectFromPickle')
    def getObjectFromPickle(self,pickle_string):
      """
      we give a pickle string and a signature
      """
      object = None
      pickle_string = pickle_string.replace('@@@','\n')
      msg = MIMEBase('application','octet-stream')
      Encoders.encode_base64(msg)
      msg.set_payload(pickle_string)
      pickle_string = msg.get_payload(decode=1)
      object = pickle.loads(pickle_string)
      return object

Sebastien Robin's avatar
Sebastien Robin committed
1004 1005 1006 1007 1008 1009 1010 1011 1012
    security.declareProtected(ERP5Permissions.View, 'getObjectFromPickleAndSignature')
    def getObjectFromPickleAndSignature(self,pickle_string,signature):
      """
      we give a pickle string and a signature
      """
      cookie_password = self._getCookiePassword()
      object = None
      new_signature = hmac.new(cookie_password,pickle_string).hexdigest()
      if new_signature==signature:
1013
        object = self.getObjectFromPickle(pickle_string)
Sebastien Robin's avatar
Sebastien Robin committed
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
      return object

    security.declarePrivate('_getCookiePassword')
    def _getCookiePassword(self):
      """
      get the password used for encryption
      """
      cookie_password = getattr(self,'cookie_password',None)
      if cookie_password is None:
        cookie_password = str(random.randrange(1,2147483600))
        self.cookie_password = cookie_password
      return cookie_password

    security.declareProtected(ERP5Permissions.View, 'registerCookieInfo')
    def setCookieInfo(self,request,cookie_name,**kw):
      """
      regiter info directly in cookie
      """
      cookie_name = cookie_name + '_cookie'
      (pickle_string,signature) = self.getPickleAndSignature(**kw)
      request.RESPONSE.setCookie(cookie_name,pickle_string,max_age=15*60)
      signature_cookie_name = cookie_name + '_signature'
      request.RESPONSE.setCookie(signature_cookie_name,signature,max_age=15*60)

    security.declareProtected(ERP5Permissions.View, 'registerCookieInfo')
    def getCookieInfo(self,request,cookie_name):
      """
      regiter info directly in cookie
      """
      cookie_name = cookie_name + '_cookie'
      object = None
      if getattr(request,cookie_name,None) is not None:
        pickle_string = request.get(cookie_name)
        signature_cookie_name = cookie_name + '_signature'
        signature = request.get(signature_cookie_name)
        object = self.getObjectFromPickleAndSignature(pickle_string,signature)
      if object is None:
        object = {}
      return object

1054
    # Related document searching
1055
    def viewSearchRelatedDocumentDialog(self, index, form_id,
1056
                                        REQUEST=None, sub_index=None, **kw):
1057
      """
1058 1059
      Returns a search related document dialog
      A set of forwarders us defined to circumvent limitations of HTML
1060
      """
Romain Courteaud's avatar
Romain Courteaud committed
1061 1062
      if sub_index != None:
        REQUEST.form['sub_index'] = sub_index
1063
      object_path = REQUEST.form['object_path']
1064
      # Find the object which needs to be updated
1065
      o = self.restrictedTraverse(object_path)
1066
      # Find the field which was clicked on
1067
      # Important to get from the object instead of self
1068
      form = getattr(o, form_id)
1069
      field = None
1070 1071
      # Search the correct field
      relation_field_found = 0
1072
      relation_index = 0
1073
      # XXX may be should support another parameter,
1074
      for field in form.get_fields(include_disabled=0):
1075 1076
        if field.get_value('editable', REQUEST=REQUEST):
          try:
1077 1078
           field.get_value('is_relation_field')
          except KeyError:
1079
            pass
1080
          else:
1081 1082 1083 1084 1085
            if index == relation_index:
              relation_field_found = 1
              break
            else:
              relation_index += 1
1086
      if not relation_field_found:
1087
        # We didn't find the field...
1088
        raise SelectionError, "SelectionTool: can not find the relation" \
1089
                              " field %s" % index
1090 1091 1092 1093 1094
      else:
        # Field found
        field_key = field.generate_field_key()
        field_value = REQUEST.form[field_key]
        # XXX Hardcoded form name
1095 1096
        dialog_id = 'Base_viewRelatedObjectList'
        redirect_form = getattr(o, dialog_id)
1097 1098 1099 1100 1101 1102 1103 1104
        # XXX Hardcoded listbox field
        selection_name = redirect_form.listbox.get_value('selection_name')
        # Reset current selection
        self.portal_selections.setSelectionFor(selection_name, None)


        if (field.get_value('is_multi_relation_field')) and \
           (sub_index is None):
1105 1106 1107 1108
          # user click on the wheel, not on the validation button
          # we need to facilitate user search

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

1111 1112 1113 1114 1115 1116
          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
1117 1118 1119
          # Checked current uid
          kw ={}
          kw[field.get_value('catalog_index')] = field_value
1120
          self.portal_selections.setSelectionParamsFor(selection_name,
1121 1122
                                                       kw.copy())
          self.portal_selections.setSelectionCheckedUidsFor(
1123
                                             selection_name,
1124
                                             current_uid_list)
1125 1126 1127 1128 1129 1130 1131 1132
          field_value = str(field_value).splitlines()
          REQUEST.form[field_key] = field_value
          portal_status_message = Message(
                          domain='erp5_ui',
                          message="Please select one (or more) object.")
        else:
          portal_status_message = Message(domain='erp5_ui',
                                          message="Please select one object.")
1133 1134


1135 1136 1137 1138 1139 1140
        # Save the current REQUEST form
        # We can't put FileUpload instances because we can't pickle them
        pickle_kw = {}
        for key in REQUEST.form.keys():
          if not isinstance(REQUEST.form[key],FileUpload):
            pickle_kw[key] = REQUEST.form[key]
1141
        form_pickle, form_signature = self.getPickleAndSignature(**pickle_kw)
1142

1143 1144
        base_category = None
        kw = {}
1145
        kw['dialog_id'] = dialog_id
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
        kw['selection_name'] = selection_name
        kw['selection_index'] = 0 # We start on the first page
        kw['field_id'] = field.id
        kw['portal_type'] = [x[0] for x in field.get_value('portal_type')]
        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')
        kw['cancel_url'] = REQUEST.get('HTTP_REFERER')
1157
        kw['form_id'] = form_id
1158 1159
        kw[field.get_value('catalog_index')] = field_value
        kw['portal_status_message'] = portal_status_message
1160
        kw['form_pickle'] = form_pickle
1161 1162 1163 1164 1165
        kw['form_signature'] = form_signature

         # Empty the selection (uid)
        REQUEST.form = kw # New request form
        # Define new HTTP_REFERER
Romain Courteaud's avatar
Romain Courteaud committed
1166
        REQUEST.HTTP_REFERER = '%s/%s' % (o.absolute_url(),
1167
                                          dialog_id)
1168
        # Return the search dialog
1169
        return getattr(o, dialog_id)(REQUEST=REQUEST)
1170

1171 1172
    def _aq_dynamic(self, name):
      """
1173
        Generate viewSearchRelatedDocumentDialog0,
1174
                 viewSearchRelatedDocumentDialog1,... if necessary
1175 1176 1177
      """
      aq_base_name = getattr(aq_base(self), name, None)
      if aq_base_name == None:
1178 1179 1180
        DYNAMIC_METHOD_NAME = 'viewSearchRelatedDocumentDialog'
        method_name_length = len(DYNAMIC_METHOD_NAME)

1181
        zope_security = '__roles__'
1182
        if (name[:method_name_length] == DYNAMIC_METHOD_NAME) and \
1183
           (name[-len(zope_security):] != zope_security):
1184
          method_count_string_list = name[method_name_length:].split('_')
1185 1186 1187 1188
          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
1189
          except TypeError:
1190
            return aq_base_name
1191
          else:
1192 1193 1194
            if len(method_count_string_list) > 1:
              # be sure that method name is correct
              try:
Romain Courteaud's avatar
Romain Courteaud committed
1195
                sub_index = string.atoi(method_count_string_list[1])
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1196
              except TypeError:
1197 1198
                return aq_base_name
            else:
Romain Courteaud's avatar
Romain Courteaud committed
1199
              sub_index = None
1200

1201
            # generate dynamicaly needed forwarder methods
1202
            def viewSearchRelatedDocumentDialogWrapper(self, form_id,
1203
                                                       REQUEST=None, **kw):
1204 1205 1206
              """
                viewSearchRelatedDocumentDialog Wrapper
              """
1207
              LOG('SelectionTool.viewSearchRelatedDocumentDialogWrapper, kw',
1208
                  0, kw)
1209
              return self.viewSearchRelatedDocumentDialog(
1210
                                   method_count, form_id,
1211
                                   REQUEST=REQUEST, sub_index=sub_index, **kw)
1212
            setattr(self.__class__, name,
1213
                    viewSearchRelatedDocumentDialogWrapper)
1214 1215 1216 1217 1218 1219 1220

            klass = aq_base(self).__class__
            if hasattr(klass, 'security'):
              from Products.ERP5Type import Permissions as ERP5Permissions
              klass.security.declareProtected(ERP5Permissions.View, name)
            else:
              # XXX security declaration always failed....
1221 1222
              LOG('WARNING ERP5Form SelectionTool, security not defined on',
                  0, klass.__name__)
1223 1224 1225 1226
            return getattr(self, name)
        else:
          return aq_base_name
      return aq_base_name
1227

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1228
InitializeClass( SelectionTool )
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

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
  def getObject(self):
    return self.object
1240

1241 1242
  def getIsPureSummary(self):
    return self.is_pure_summary
1243

1244 1245
  def getDepth(self):
    return self.depth
1246

1247 1248
  def getIsOpen(self):
    return self.is_open
1249 1250

  def getSelectDomainDict(self):
1251
    return self.select_domain_dict
1252

1253 1254
  def getExceptionUidList(self):
    return self.exception_uid_list
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

def makeTreeList(here, form, root_dict, report_path, base_category, depth, unfolded_list, form_id, selection_name, report_depth, is_report_opened=1, sort_on = (('id', 'ASC'),)):
  """
    (object, is_pure_summary, depth, is_open, select_domain_dict)

    select_domain_dict is a dictionary of  associative list of (id, domain)
  """
  if type(report_path) is type('a'): report_path = report_path.split('/')

  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:
        if base_category in portal_categories.objectIds():
          if base_category == 'parent':
            # parent has a special treatment
            root = root_dict[base_category] = root_dict[None] = here
            report_path = report_path[1:]
1284
          else:
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
            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 = ()
    else:
      root = root_dict[None] = root_dict[base_category]
      report_path = report_path[1:]
    is_empty_level = (root.objectCount() == 0) and (len(report_path) != 0)
    if is_empty_level: base_category = report_path[0]

  tree_list = []
  if root is None: return tree_list

  if base_category == 'parent':
    if hasattr(aq_base(root), 'objectValues'):
      # If this is a folder, try to browse the hierarchy
      for zo in root.searchFolder(sort_on=sort_on):
        o = zo.getObject()
        if o is not None:
          new_root_dict = root_dict.copy()
          new_root_dict[None] = new_root_dict[base_category] = o
1314

1315 1316 1317
          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
1318

1319 1320 1321
            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'):
1322
                exception_uid_list.append(sub_o.getUid())
1323 1324 1325 1326 1327 1328 1329
            tree_list += [TreeListLine(o, 1, depth, 1, selection_domain, exception_uid_list)] # Summary (open)
            if is_report_opened :
              tree_list += [TreeListLine(o, 0, depth, 0, selection_domain, exception_uid_list)] # List (contents, closed, must be strict selection)
            tree_list += makeTreeList(here, form, new_root_dict, report_path, base_category, depth + 1, unfolded_list, form_id, selection_name, report_depth, is_report_opened=is_report_opened, sort_on=sort_on)
          else:
            tree_list += [TreeListLine(o, 1, depth, 0, selection_domain, ())] # Summary (closed)
  else:
1330 1331 1332 1333 1334 1335
    # 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:
1336 1337 1338 1339 1340 1341 1342
      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)
1343 1344
        tree_list += makeTreeList(here, form, new_root_dict, report_path, base_category, depth + 1,
            unfolded_list, form_id, selection_name, report_depth,
1345 1346 1347 1348
            is_report_opened=is_report_opened, sort_on=sort_on)
      else:

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

1350 1351
  return tree_list