ZSQLCatalog.py 41.8 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL. All Rights Reserved.
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""ZCatalog product"""

from Globals import DTMLFile, MessageDialog
import Globals

from OFS.Folder import Folder
from OFS.FindSupport import FindSupport
from OFS.ObjectManager import ObjectManager
from DateTime import DateTime
23
from Acquisition import Implicit, aq_base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
24 25 26 27 28
from Persistence import Persistent
from DocumentTemplate.DT_Util import InstanceDict, TemplateDict
from DocumentTemplate.DT_Util import Eval
from AccessControl.Permission import name_trans
from SQLCatalog import Catalog, CatalogError
29
from AccessControl import ClassSecurityInfo, getSecurityManager
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30
from AccessControl.DTML import RestrictedDTML
31
import string, os, sys, types, threading
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33 34

from zLOG import LOG

35 36 37
# Put the queue of catalogged objects in RAM for distributed computation.
catalogged_path_list = []
catalogged_path_list_lock = threading.Lock()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38

39
manage_addZSQLCatalogForm=DTMLFile('dtml/addZSQLCatalog',globals())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40

41
def manage_addZSQLCatalog(self, id, title,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
             vocab_id='create_default_catalog_',
             REQUEST=None):
  """Add a ZCatalog object
  """
  id=str(id)
  title=str(title)
  vocab_id=str(vocab_id)
  if vocab_id == 'create_default_catalog_':
    vocab_id = None

  c=ZCatalog(id, title, self)
  self._setObject(id, c)
  if REQUEST is not None:
    return self.manage_main(self, REQUEST,update_menu=1)


class ZCatalog(Folder, Persistent, Implicit):
  """ZCatalog object

  A ZCatalog contains arbirary index like references to Zope
  objects.  ZCatalog's can index either 'Field' values of object, or
  'Text' values.

  ZCatalog does not store references to the objects themselves, but
  rather to a unique identifier that defines how to get to the
  object.  In Zope, this unique idenfier is the object's relative
  path to the ZCatalog (since two Zope object's cannot have the same
  URL, this is an excellent unique qualifier in Zope).

  Most of the dirty work is done in the _catalog object, which is an
  instance of the Catalog class.  An interesting feature of this
  class is that it is not Zope specific.  You can use it in any
  Python program to catalog objects.

  """

  meta_type = "ZSQLCatalog"
  icon='misc_/ZCatalog/ZCatalog.gif'
80
  security = ClassSecurityInfo()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
81 82 83 84 85 86 87 88 89

  manage_options = (
    {'label': 'Contents',       # TAB: Contents
     'action': 'manage_main',
     'help': ('OFSP','ObjectManager_Contents.stx')},
    {'label': 'Catalog',      # TAB: Cataloged Objects
     'action': 'manage_catalogView',
     'target': 'manage_main',
     'help':('ZCatalog','ZCatalog_Cataloged-Objects.stx')},
90 91
    {'label' : 'Filter',        # TAB: Filter
     'action' : 'manage_catalogFilter' },
Jean-Paul Smets's avatar
Jean-Paul Smets committed
92 93 94 95 96 97 98 99 100 101 102
    {'label': 'Properties',     # TAB: Properties
     'action': 'manage_propertiesForm',
     'help': ('OFSP','Properties.stx')},
    {'label': 'Find Objects',     # TAB: Find Objects
     'action': 'manage_catalogFind',
     'target':'manage_main',
     'help':('ZCatalog','ZCatalog_Find-Items-to-ZCatalog.stx')},
    {'label': 'Advanced',       # TAB: Advanced
     'action': 'manage_catalogAdvanced',
     'target':'manage_main',
     'help':('ZCatalog','ZCatalog_Advanced.stx')},
103 104 105
    {'label': 'Hot Reindexing',       # TAB: Hot Reindex
     'action': 'manage_catalogHotReindexing',
     'target':'manage_main', },
Jean-Paul Smets's avatar
Jean-Paul Smets committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    {'label': 'Undo',         # TAB: Undo
     'action': 'manage_UndoForm',
     'help': ('OFSP','Undo.stx')},
    {'label': 'Security',       # TAB: Security
     'action': 'manage_access',
     'help': ('OFSP','Security.stx')},
    {'label': 'Ownership',      # TAB: Ownership
     'action': 'manage_owner',
     'help': ('OFSP','Ownership.stx'),}
    )

  __ac_permissions__=(

    ('Manage ZCatalog Entries',
     ['manage_catalogObject', 'manage_uncatalogObject',
      'catalog_object', 'uncatalog_object', 'refreshCatalog',

      'manage_catalogView', 'manage_catalogFind',
124
      'manage_catalogSchema', 'manage_catalogFilter',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
125
      'manage_catalogAdvanced', 'manage_objectInformation',
126
      'manage_catalogHotReindexing',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
127

128
      'manage_catalogReindex', 'manage_catalogFoundItems',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
129 130
      'manage_catalogClear', 'manage_editSchema',
      'manage_reindexIndex', 'manage_main',
131 132 133
      'manage_editFilter',

      'manage_hotReindexAll',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
134 135 136 137 138 139 140 141

      ],
     ['Manager']),

    ('Search ZCatalog',
     ['searchResults', '__call__', 'uniqueValuesFor',
      'getpath', 'schema', 'names', 'columns', 'indexes', 'index_objects',
      'all_meta_types', 'valid_roles', 'resolve_url',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
142
      'getobject', 'getObject', 'getObjectList', 'getCatalogSearchTableIds',
143
      'getCatalogSearchResultKeys', 'getFilterableMethodList', ],
Jean-Paul Smets's avatar
Jean-Paul Smets committed
144
     ['Anonymous', 'Manager']),
145 146 147 148 149

    ('Import/Export objects',
     ['manage_catalogExportProperties', 'manage_catalogImportProperties', ],
     ['Manager']),

Jean-Paul Smets's avatar
Jean-Paul Smets committed
150 151 152
    )

  _properties = (
Jean-Paul Smets's avatar
Jean-Paul Smets committed
153
    { 'id'      : 'title',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
154 155 156
      'description' : 'The title of this catalog',
      'type'    : 'string',
      'mode'    : 'w' },
157 158
    { 'id'      : 'default_sql_catalog_id',
      'description' : 'The id of the default SQL Catalog',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
159
      'type'    : 'selection',
160
      'select_variable'    : 'getSQLCatalogIdList',
161
      'mode'    : 'w' },
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
    # Hot Reindexing
    { 'id'      : 'source_sql_catalog_id',
      'description' : 'The id of a source SQL Catalog for hot reindexing',
      'type'    : 'string',
      'mode'    : '' },
    { 'id'      : 'destination_sql_catalog_id',
      'description' : 'The id of a destination SQL Catalog for hot reindexing',
      'type'    : 'string',
      'mode'    : '' },
    { 'id'      : 'hot_reindexing_state',
      'description' : 'The state of hot reindexing',
      'type'    : 'string',
      'mode'    : '' },

  )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
178

179 180 181 182
  source_sql_catalog_id = None
  destination_sql_catalog_id = None
  hot_reindexing_state = None
  default_sql_catalog_id = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
183 184

  manage_catalogAddRowForm = DTMLFile('dtml/catalogAddRowForm', globals())
185
  manage_catalogFilter = DTMLFile( 'dtml/catalogFilter', globals() )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
186 187 188 189 190
  manage_catalogView = DTMLFile('dtml/catalogView',globals())
  manage_catalogFind = DTMLFile('dtml/catalogFind',globals())
  manage_catalogSchema = DTMLFile('dtml/catalogSchema', globals())
  manage_catalogIndexes = DTMLFile('dtml/catalogIndexes', globals())
  manage_catalogAdvanced = DTMLFile('dtml/catalogAdvanced', globals())
191
  manage_catalogHotReindexing = DTMLFile('dtml/catalogHotReindexing', globals())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
192 193 194 195 196 197 198 199
  manage_objectInformation = DTMLFile('dtml/catalogObjectInformation',
                                                              globals())

  def __init__(self, id, title='', container=None):
    if container is not None:
      self=self.__of__(container)
    self.id=id
    self.title=title
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

  def getSQLCatalogIdList(self):
    return self.objectIds(spec=('SQLCatalog',))

  def getSQLCatalog(self, id=None, default_value=None):
    """
      Get the default SQL Catalog.
    """
    if id is None:
      if not self.default_sql_catalog_id:
        id_list = self.getSQLCatalogIdList()
        if len(id_list) > 0:
          self.default_sql_catalog_id = id_list[0]
        else:
          return default_value
      id = self.default_sql_catalog_id

    return self._getOb(id)

  def manage_catalogExportProperties(self, REQUEST=None, RESPONSE=None, sql_catalog_id=None):
    """
      Export properties to an XML file.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
222
    """
223 224 225
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.manage_exportProperties(REQUEST=REQUEST, RESPONSE=RESPONSE)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
226

227 228 229 230 231 232 233
  def manage_catalogImportProperties(self, file, sql_catalog_id=None):
    """
      Import properties from an XML file.
    """
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.manage_importProperties(file)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
234

235 236 237 238 239 240 241 242 243
  def __len__(self):
    catalog = self.getSQLCatalog()
    if catalog is None:
      return 0
    return len(catalog)

  def setHotReindexingState(self, state='', source_sql_catalog_id=None, destination_sql_catalog_id=None):
    """
      Set the state of hot reindexing.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
      Do not use setProperty because the state should not modified from the ZMI directly.
      It must be maintained very carefully.
    """
    if source_sql_catalog_id is None:
      source_sql_catalog_id = self.default_sql_catalog_id

    if state == 'finished':
      self.hot_reindexing_state = None
      self.source_sql_catalog_id = None
      self.destination_sql_catalog_id = None
    elif state == 'recording' or state == 'double indexing':
      self.hot_reindexing_state = state
      self.source_sql_catalog_id = source_sql_catalog_id
      self.destination_sql_catalog_id = destination_sql_catalog_id
    else:
      raise CatalogError, 'unknown hot reindexing state %s' % state
Jean-Paul Smets's avatar
Jean-Paul Smets committed
261

262 263
    # This change must be reflected as soon as possible.
    get_transaction().commit()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
264

265 266 267 268 269 270
  def finishHotReindexing(self, **kw):
    """
      XXX: This is a workaround for CMFActivity.
    """
    self.setHotReindexingState(state='finished', **kw)

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  def playBackRecordedObjectList(self, sql_catalog_id=None):
    """
      Play back must be a distinct method to activate...
    """
    catalog = self.getSQLCatalog(sql_catalog_id)
    while 1:
      result = catalog.readRecordedObjectList()
      if len(result) == 0:
        break
      get_transaction().commit()

      path_dict = {}
      for o in result:
        if o.path not in path_dict:
          path_dict[o.path] = None
          object = self.resolve_path(o.path)
          if o.catalog:
            if object is not None:
289
              LOG('playBackRecordedObjectList, will reindexObject:',0,object.getPhysicalPath())
290
              object.reindexObject(sql_catalog_id=sql_catalog_id, activity='SQLQueue')
291 292 293
              #self.activate(passive_commit=1, priority=5).reindexObject(object, sql_catalog_id=sql_catalog_id)
              # XXX We can't call reindexObject has an activate message, because we can not
              # do pickle with acquisition wrappers
294
              #self.reindexObject(object, sql_catalog_id=sql_catalog_id) # Ask YO, we must find something activated
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
              # Make sure that this object has no extra reference.
              object = None
          else:
            if object is None:
              self.uncatalog_object(o.path, sql_catalog_id=sql_catalog_id)
            else:
              # Make sure that this object has no extra reference.
              object = None
        get_transaction().commit()

      catalog.deleteRecordedObjectList(path_dict.keys())
      get_transaction().commit()

  def exchangeDatabases(self, source_sql_catalog_id, destination_sql_catalog_id,
                        skin_selection_dict, sql_connection_id_dict):
    """
      Exchange two databases.
    """
    if self.default_sql_catalog_id == source_sql_catalog_id:
      self.default_sql_catalog_id = destination_sql_catalog_id

316 317 318 319 320 321 322
    LOG('exchangeDatabases skin_selection_dict:',0,skin_selection_dict)
    if skin_selection_dict is not None:
      LOG('exchangeDatabases skin_selection_dict:',0,'we will do manage_skinLayers')
      for skin_name, selection in self.portal_skins.getSkinPaths():
        if skin_name in skin_selection_dict:
          new_selection = tuple(skin_selection_dict[skin_name])
          self.portal_skins.manage_skinLayers(skinpath = new_selection, skinname = skin_name, add_skin = 1)
323

324
    if sql_connection_id_dict is not None:
325 326 327 328 329 330 331 332 333 334 335
      def changeSQLConnectionIds(folder):
        if folder.meta_type == 'Z SQL Method':
          connection_id = folder.connection_id
          if connection_id in sql_connection_id_dict:
            folder.connection_id = sql_connection_id_dict[connection_id]
        elif hasattr(aq_base(folder), 'objectValues'):
          for object in folder.objectValues():
            changeSQLConnectionIds(object)

      changeSQLConnectionIds(self.portal_skins)

336 337 338 339 340 341 342
  def manage_hotReindexAll(self, source_sql_catalog_id='erp5_mysql',
                                 destination_sql_catalog_id='erp5_mysql',
                                 source_sql_connection_id_list = None,
                                 destination_sql_connection_id_list = None,
                                 skin_name_list = None,
                                 skin_selection_list = None,
                                 REQUEST=None, RESPONSE=None):
343 344
    """
      Reindex objects from scratch in the background then switch to the newly created database.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
345
    """
346
    # Get parameters.
347 348 349 350 351 352 353 354 355 356 357 358
    #source_sql_catalog_id = REQUEST.get('source_sql_catalog_id')
    #destination_sql_catalog_id = REQUEST.get('destination_sql_catalog_id')
    #source_sql_connection_id_list = REQUEST.get('source_sql_connection_id_list')
    #destination_sql_connection_id_list = REQUEST.get('destination_sql_connection_id_list')
    #skin_name_list = REQUEST.get('skin_name_list')
    #skin_selection_list = REQUEST.get('skin_selection_list')
    LOG('source_sql_catalog_id',0,source_sql_catalog_id)
    LOG('destination_sql_catalog_id',0,destination_sql_catalog_id)
    LOG('source_sql_connection_id_list',0,source_sql_connection_id_list)
    LOG('destination_sql_connection_id_list',0,destination_sql_connection_id_list)
    LOG('skin_name_list',0,skin_name_list)
    LOG('skin_selection_list',0,skin_selection_list)
359 360

    # Construct a mapping for skin selections.
361 362 363 364 365 366 367 368 369 370 371
    skin_selection_dict = None
    if skin_name_list is not None and skin_selection_list is not None:
      skin_selection_dict = {}
      for name, selection_list in zip(skin_name_list, skin_selection_list):
        # Make sure that there is no extra space.
        new_selection_list = []
        for selection in selection_list:
          new_selection = selection.strip()
          if len(new_selection) > 0:
            new_selection_list.append(new_selection)
        skin_selection_dict[name] = new_selection_list
372 373

    # Construct a mapping for connection ids.
374 375 376 377 378 379
    sql_connection_id_dict = None
    if source_sql_connection_id_list is not None and destination_sql_connection_id_list is not None:
      sql_connection_id_dict = {}
      for source_sql_connection_id, destination_sql_connection_id in zip(source_sql_connection_id_list, destination_sql_connection_id_list):
        if source_sql_connection_id != destination_sql_connection_id:
          sql_connection_id_dict[source_sql_connection_id] = destination_sql_connection_id
380 381 382 383 384

    # Hot reindexing may not run for multiple databases.
    if self.hot_reindexing_state is not None:
      raise CatalogError, 'hot reindexing process is already running'

385 386 387 388 389 390 391 392 393 394
    # First of all, make sure that all root objects have uids.
    # XXX This is a workaround for tools (such as portal_simulation).
    for path in self.portal_skins.erp5_core.Catalog_getIndexablePathList():
      object = self.resolve_path(path)
      if object is None: continue
      if getattr(object, 'uid', None) is None:
        object.getUid()
      object = None
      get_transaction().commit() # Should not have references to objects too long.

395 396 397
    # Recreate the new database.
    LOG('hotReindexObjectList', 0, 'Clearing the new database')
    self.manage_catalogClear(sql_catalog_id=destination_sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
398

399 400 401 402 403 404 405 406 407 408 409
    try:
      # Start recording catalog/uncatalog information.
      LOG('hotReindexObjectList', 0, 'Starting recording')
      self.setHotReindexingState('recording',
                                 source_sql_catalog_id=source_sql_catalog_id,
                                 destination_sql_catalog_id=destination_sql_catalog_id)

      # Iterate all objects recursively.
      # XXX Commit transactions very often and use resolve_path to get objects instead of objectValues
      # XXX This is not to be disturbed by normal user operations in the foreground.
      # XXX Otherwise, many read conflicts happen and hot reindexing restarts again and again.
410 411
      #for path in self.Catalog_getIndexablePathList():
      for path in self.portal_skins.erp5_core.Catalog_getIndexablePathList():
412 413 414
        object = self.resolve_path(path)
        if object is None: continue
        id_list = object.objectIds()
415 416
        #LOG('will hotReindex this object:',0,object.getPhysicalPath())
        #LOG('will hotReindex this object uid:',0,getattr(object,'uid',None))
417
        object.activate(passive_commit=1, priority=5, activity='SQLQueue').queueCataloggedObject(sql_catalog_id=destination_sql_catalog_id, activity='SQLQueue')
418 419 420 421 422 423 424 425
        object = None
        get_transaction().commit() # Should not have references to objects too long.

        LOG('hotReindexObjectList', 0, 'Catalogging %s' % path)
        for id in id_list:
          subpath = '/'.join([path, id])
          o = self.resolve_path(subpath)
          if o is not None:
426
            o.activate(passive_commit=1, priority=5, activity='SQLQueue').recursiveQueueCataloggedObject(sql_catalog_id=destination_sql_catalog_id, activity='SQLQueue')
427 428 429 430 431
            o = None
            get_transaction().commit() # Should not have references to objects too long.

      # Make sure that everything is catalogged.
      LOG('hotReindexObjectList', 0, 'Flushing the queue')
432
      self.activate(broadcast=1, passive_commit=1, after_method_id=('recursiveQueueCataloggedObject', 'queueCataloggedObject', 'immediateQueueCataloggedObject'), priority=5, activity='SQLQueue').flushQueuedObjectList(sql_catalog_id=destination_sql_catalog_id)
433 434 435 436

      # Now synchronize this new database with the current one.
      # XXX It is necessary to use ActiveObject to wait for queued objects to be flushed.
      LOG('hotReindexObjectList', 0, 'Starting double indexing')
437
      self.activate(passive_commit=1, after_method_id='flushQueuedObjectList', priority=5, activity='SQLQueue').setHotReindexingState('double indexing',
438 439 440 441
                                 source_sql_catalog_id=source_sql_catalog_id,
                                 destination_sql_catalog_id=destination_sql_catalog_id)

      # Play back records.
442 443 444
      if source_sql_catalog_id != destination_sql_catalog_id:
        # If equals, then this does not make sense to reindex again.
        LOG('hotReindexObjectList', 0, 'Playing back records')
445
        self.activate(passive_commit=1, after_method_id='setHotReindexingState', priority=5, activity='SQLQueue').playBackRecordedObjectList(sql_catalog_id=destination_sql_catalog_id)
446 447 448

      # Exchange the databases.
      LOG('hotReindexObjectList', 0, 'Exchanging databases')
449
      self.activate(after_method_id=('reindexObject', 'playBackRecordedObjectList', 'setHotReindexingState'), priority=5, activity='SQLQueue').exchangeDatabases(source_sql_catalog_id, destination_sql_catalog_id, skin_selection_dict, sql_connection_id_dict) # XXX Never called by activity tool, why ??? XXX
450 451 452
    finally:
      # Finish.
      LOG('hotReindexObjectList', 0, 'Finishing hot reindexing')
453
      self.activate(passive_commit=1, after_method_id='exchangeDatabases', priority=5, activity='SQLQueue').finishHotReindexing()
454

455 456 457
    if RESPONSE is not None:
      URL1 = REQUEST.get('URL1')
      RESPONSE.redirect(URL1 + '/manage_catalogHotReindexing?manage_tabs_message=Catalog%20Changed')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
458 459 460 461 462 463 464 465 466 467

  def manage_edit(self, RESPONSE, URL1, threshold=1000, REQUEST=None):
    """ edit the catalog """
    if type(threshold) is not type(1):
      threshold=string.atoi(threshold)
    self.threshold = threshold

    RESPONSE.redirect(URL1 + '/manage_main?manage_tabs_message=Catalog%20Changed')


468
  def manage_catalogObject(self, REQUEST, RESPONSE, URL1, urls=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
469
    """ index Zope object(s) that 'urls' point to """
470 471
    if sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
472

473 474 475
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_catalogObject(REQUEST, RESPONSE, URL1, urls=urls)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
476 477


478
  def manage_uncatalogObject(self, REQUEST, RESPONSE, URL1, urls=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
479
    """ removes Zope object(s) 'urls' from catalog """
480 481
    if sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
482

483 484 485
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_uncatalogObject(REQUEST, RESPONSE, URL1, urls=urls)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
486 487


488
  def manage_catalogReindex(self, REQUEST, RESPONSE, URL1, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
489
    """ clear the catalog, then re-index everything """
490 491
    if sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
492

493 494 495
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_catalogReindex(REQUEST, RESPONSE, URL1, urls=urls)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
496

497
  def refreshCatalog(self, clear=0, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
498 499
    """ re-index everything we can find """

500 501 502 503 504
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      paths = catalog.getPaths()
      if clear:
        catalog.clear()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
505

506 507 508 509 510 511
      for p in paths:
        obj = self.resolve_path(p.path)
        if not obj:
          obj = self.resolve_url(p.path, self.REQUEST)
        if obj is not None:
          self.catalog_object(obj, p.path, sql_catalog_id=sql_catalog_id)
512

513
  def manage_catalogClear(self, REQUEST=None, RESPONSE=None, URL1=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
514
    """ clears the whole enchilada """
515 516
    if REQUEST is not None and sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
517

518 519 520
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_catalogClear(REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
521

522
  def manage_catalogClearReserved(self, REQUEST=None, RESPONSE=None, URL1=None, sql_catalog_id=None):
523
    """ clears the whole enchilada """
524 525
    if REQUEST is not None and sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
526

527 528 529
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_catalogClearReserved(REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
530 531 532 533 534 535

  def manage_catalogFoundItems(self, REQUEST, RESPONSE, URL2, URL1,
                 obj_metatypes=None,
                 obj_ids=None, obj_searchterm=None,
                 obj_expr=None, obj_mtime=None,
                 obj_mspec=None, obj_roles=None,
536 537
                 obj_permission=None,
                 sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
538 539
    """ Find object according to search criteria and Catalog them
    """
540 541 542 543 544 545 546 547 548 549
    if sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)

    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_catalogFoundItems(REQUEST, RESPONSE, URL2, URL1,
                                       obj_metatypes=obj_metatypes, obj_ids=obj_ids,
                                       obj_searchterm=obj_searchterm, obj_expr=obj_expr,
                                       obj_mtime=obj_mtime, obj_mspec=obj_mspec,
                                       obj_roles=obj_roles, obj_permission=obj_permission)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

    elapse = time.time()
    c_elapse = time.clock()

    words = 0
    obj = REQUEST.PARENTS[1]
    path = string.join(obj.getPhysicalPath(), '/')


    results = self.ZopeFindAndApply(obj,
                    obj_metatypes=obj_metatypes,
                    obj_ids=obj_ids,
                    obj_searchterm=obj_searchterm,
                    obj_expr=obj_expr,
                    obj_mtime=obj_mtime,
                    obj_mspec=obj_mspec,
                    obj_permission=obj_permission,
                    obj_roles=obj_roles,
                    search_sub=1,
                    REQUEST=REQUEST,
                    apply_func=self.catalog_object,
571 572
                    apply_path=path,
                    sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
573 574 575 576 577 578 579

    elapse = time.time() - elapse
    c_elapse = time.clock() - c_elapse

    RESPONSE.redirect(URL1 + '/manage_catalogView?manage_tabs_message=' +
              urllib.quote('Catalog Updated<br>Total time: %s<br>Total CPU time: %s' % (`elapse`, `c_elapse`)))

580
  def manage_editSchema(self, names, REQUEST=None, RESPONSE=None, URL1=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
581
    """ add a column """
582 583 584 585
    if REQUEST is not None and sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)

    self.editSchema(names, sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
586 587 588 589

    if REQUEST and RESPONSE:
      RESPONSE.redirect(URL1 + '/manage_catalogSchema?manage_tabs_message=Schema%20Saved')

590
  def newUid(self, sql_catalog_id=None):
591 592 593
    """
        Allocates a new uid value.
    """
594 595 596
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.newUid()
597

598 599 600 601 602 603 604 605
  def wrapObject(self, object, **kw):
    """
      Return a wrapped object for reindexing.

      This method should be overridden if necessary.
    """
    return object

606
  def catalog_object(self, obj, url=None, idxs=[], is_object_moved=0, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
607 608
    """ wrapper around catalog """

609 610
    if url is None:
      try: url = obj.getPhysicalPath
Jean-Paul Smets's avatar
Jean-Paul Smets committed
611 612 613 614 615
      except AttributeError:
        raise CatalogError(
          "A cataloged object must support the 'getPhysicalPath' "
          "method if no unique id is provided when cataloging"
          )
616 617
      else: url=string.join(url(), '/')
    elif not isinstance(url, types.StringType):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
618 619
      raise CatalogError('The object unique id must be a string.')

620 621 622 623
    obj = self.wrapObject(obj, sql_catalog_id=sql_catalog_id)

    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
624 625 626
      LOG('ZSQLCatalog.catalog_object, object:',0,obj.getPhysicalPath())
      catalog.catalogObject(obj, url, is_object_moved=is_object_moved) # support obj, not uid
      #catalog.reindexObject(obj, is_object_moved=is_object_moved) # support obj, not uid
627 628 629 630

      if self.hot_reindexing_state is not None and self.source_sql_catalog_id == catalog.id:
        destination_catalog = self.getSQLCatalog(self.destination_sql_catalog_id)
        if self.hot_reindexing_state == 'recording':
631
          destination_catalog.recordCatalogObject(url)
632
        else:
633 634 635
          destination_catalog.deleteRecordedObjectList([url]) # Prevent this object from being replayed.
          LOG('ZSQLCatalog.catalog_object, and hot reindex : object:',0,obj.getPhysicalPath())
          destination_catalog.catalogObject(obj, url, is_object_moved=is_object_moved)
636 637

  security.declarePrivate('queueCataloggedObject')
638
  def queueCataloggedObject(self, object, sql_catalog_id=None, **kw):
639 640 641 642 643 644 645 646 647 648 649 650 651
    """
      Add an object into the queue for catalogging the object later in a batch form.
    """
    catalogged_path_list_lock.acquire()
    try:
      catalogged_path_list.append(object.getPath())
      size = len(catalogged_path_list)
    finally:
      catalogged_path_list_lock.release()

    # It is better to flush the queued objects if they are too many...
    if size > 100:
      self.flushQueuedObjectList(sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
652

653
  security.declarePublic('flushQueuedObjectList')
654
  def flushQueuedObjectList(self, sql_catalog_id=None, **kw):
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    """
      Flush queued objects.
    """
    catalogged_path_list_lock.acquire()
    try:
      global catalogged_path_list
      path_list = catalogged_path_list
      catalogged_path_list = []
    finally:
      catalogged_path_list_lock.release()

    object_list = []
    for path in path_list:
      object = self.resolve_path(path)
      if object is not None:
        object = self.wrapObject(object, sql_catalog_id=sql_catalog_id)
        object_list.append(object)
672
    LOG('flushQueuedObjectList, object_list',0,[x.getPhysicalPath() for x in object_list])
673 674 675 676 677
    if len(object_list) > 0:
      catalog = self.getSQLCatalog(sql_catalog_id)
      catalog.catalogObjectList(object_list)

  def uncatalog_object(self, uid, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
678
    """ wrapper around catalog """
679 680 681 682 683 684 685 686 687 688 689
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.uncatalogObject(uid)

    if self.hot_reindexing_state is not None and self.source_sql_catalog_id == catalog.id:
      destination_catalog = self.getSQLCatalog(self.destination_sql_catalog_id)
      if self.hot_reindexing_state == 'recording':
        destination_catalog.recordUncatalogObject(uid)
      else:
        destination_catalog.deleteRecordedObjectList([uid]) # Prevent this object from being replayed.
        destination_catalog.uncatalogObject(uid)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
690

691
  def uniqueValuesFor(self, name, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
692
    """ returns the unique values for a given FieldIndex """
693 694 695
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.uniqueValuesFor(name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
696

697 698 699
    return ()

  def getpath(self, uid, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
700 701 702
    """
    Return the path to a cataloged object given its uid
    """
703 704 705 706 707 708 709
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      object = catalog[uid]
      if object:
        return object.path
      else:
        return None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
710 711
  getPath = getpath

712
  def hasPath(self, path, sql_catalog_id=None):
Sebastien Robin's avatar
Sebastien Robin committed
713
    """
714
    Checks if path is catalogued
Sebastien Robin's avatar
Sebastien Robin committed
715
    """
716 717 718
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.hasPath(path)
Sebastien Robin's avatar
Sebastien Robin committed
719

720
  def getobject(self, uid, REQUEST=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
721 722 723
    """
    Return a cataloged object given its uid
    """
724 725 726
    if REQUEST is not None and sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
727
    try:
728
      obj = self.aq_parent.unrestrictedTraverse(self.getpath(uid, sql_catalog_id=sql_catalog_id))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
729 730 731 732 733 734
    except:
      LOG('WARNING: ZSQLCatalog',0,'Could not find object for uid %s' % uid)
      obj = None
    if obj is not None:
      if REQUEST is None:
        REQUEST=self.REQUEST
735
      path = self.getpath(uid, sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
736 737 738 739 740 741 742
      if path:
        obj = self.resolve_url(path, REQUEST)
      else:
        obj = None
    return obj
  getObject = getobject

743
  def getObjectList(self, uid_list, REQUEST=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
744 745 746 747 748
    """
    Return a cataloged object given its uid
    """
    obj_list = []
    for uid in uid_list:
749
      obj_list.append(self.getObject(uid, REQUEST, sql_catalog_id=sql_catalog_id))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
750 751
    return obj_list

752
  def getMetadataForUid(self, rid, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
753
    """return the correct metadata for the cataloged uid"""
754 755 756 757
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getMetadataForUid(int(rid))
    return {}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
758

759
  def getIndexDataForUid(self, rid, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
760
    """return the current index contents for the specific uid"""
761 762 763 764
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getIndexDataForUid(rid)
    return {}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
765 766 767 768 769

  # Aliases
  getMetadataForRID = getMetadataForUid
  getIndexDataForRID = getIndexDataForUid

770 771
  def schema(self, sql_catalog_id=None):
    return self.getColumnIds(sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
772

773 774
  def indexes(self, sql_catalog_id=None):
    return self.getColumnIds(sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
775

776 777 778 779 780
  def names(self, sql_catalog_id=None):
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.names
    return {}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
781

782 783 784 785 786
  def getColumnIds(self, sql_catalog_id=None):
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getColumnIds()
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
787

788
  def getAttributesForColumn(self, column, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
789 790 791
    """
      Return the attribute names as a single string
    """
792
    return string.join(self.names(sql_catalog_id=sql_catalog_id).get(column, ('',)),' ')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
793

794 795 796 797 798
  def _searchable_arguments(self, sql_catalog_id=None):
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getColumnIds(sql_catalog_id=sql_catalog_id)
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
799

800 801 802 803
  def editSchema(self,names, sql_catalog_id=None):
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.editSchema(names)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
804

805
  def _searchable_result_columns(self, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
806
    r = []
807 808 809 810 811 812 813 814 815
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      for name in catalog.getColumnIds():
        i = {}
        i['name'] = name
        i['type'] = 's'
        i['parser'] = str
        i['width'] = 8
        r.append(i)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
816 817 818 819 820 821
    r.append({'name': 'data_record_id_',
          'type': 's',
          'parser': str,
          'width': 8})
    return r

822
  security.declarePublic('buildSQLQuery')
823
  def buildSQLQuery(self, REQUEST=None, query_table='catalog', sql_catalog_id=None, **kw):
824 825 826 827
    """
      Build a SQL query from keywords.
      If query_table is specified, it is used as the table name instead of 'catalog'.
    """
828 829 830 831
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.buildSQLQuery(REQUEST=REQUEST, query_table=query_table, **kw)
    return ''
832

833
  def searchResults(self, REQUEST=None, used=None, sql_catalog_id=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
834 835 836 837 838
    """
    Search the catalog according to the ZTables search interface.
    Search terms can be passed in the REQUEST or as keyword
    arguments.
    """
839 840 841 842
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return apply(catalog.searchResults, (REQUEST,used), kw)
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
843 844 845

  __call__=searchResults

846
  def countResults(self, REQUEST=None, used=None, sql_catalog_id=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
847 848 849
    """
    Counts the number of items which satisfy the query defined in kw.
    """
850 851 852 853
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return apply(catalog.countResults, (REQUEST,used), kw)
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884

## this stuff is so the find machinery works

  meta_types=() # Sub-object types that are specific to this object

  def valid_roles(self):
    "Return list of valid roles"
    obj=self
    dict={}
    dup =dict.has_key
    x=0
    while x < 100:
      if hasattr(obj, '__ac_roles__'):
        roles=obj.__ac_roles__
        for role in roles:
          if not dup(role):
            dict[role]=1
      if not hasattr(obj, 'aq_parent'):
        break
      obj=obj.aq_parent
      x=x+1
    roles=dict.keys()
    roles.sort()
    return roles

  def ZopeFindAndApply(self, obj, obj_ids=None, obj_metatypes=None,
             obj_searchterm=None, obj_expr=None,
             obj_mtime=None, obj_mspec=None,
             obj_permission=None, obj_roles=None,
             search_sub=0,
             REQUEST=None, result=None, pre='',
885 886
             apply_func=None, apply_path='',
             sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    """Zope Find interface and apply

    This is a *great* hack.  Zope find just doesn't do what we
    need here; the ability to apply a method to all the objects
    *as they're found* and the need to pass the object's path into
    that method.

    """

    if result is None:
      result=[]

      if obj_metatypes and 'all' in obj_metatypes:
        obj_metatypes=None

      if obj_mtime and type(obj_mtime)==type('s'):
        obj_mtime=DateTime(obj_mtime).timeTime()

      if obj_permission:
        obj_permission=p_name(obj_permission)

      if obj_roles and type(obj_roles) is type('s'):
        obj_roles=[obj_roles]

      if obj_expr:
        # Setup expr machinations
        md=td()
        obj_expr=(Eval(obj_expr), md, md._push, md._pop)

    base=obj
    if hasattr(obj, 'aq_base'):
      base=obj.aq_base

    if not hasattr(base, 'objectItems'):
      return result
    try:  items=obj.objectItems()
    except: return result

    try: add_result=result.append
    except:
      raise AttributeError, `result`

    for id, ob in items:
      if pre: p="%s/%s" % (pre, id)
      else:   p=id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
932

Jean-Paul Smets's avatar
Jean-Paul Smets committed
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
      dflag=0
      if hasattr(ob, '_p_changed') and (ob._p_changed == None):
        dflag=1

      if hasattr(ob, 'aq_base'):
        bs=ob.aq_base
      else: bs=ob

      if (
        (not obj_ids or absattr(bs.id) in obj_ids)
        and
        (not obj_metatypes or (hasattr(bs, 'meta_type') and
         bs.meta_type in obj_metatypes))
        and
        (not obj_searchterm or
         (hasattr(ob, 'PrincipiaSearchSource') and
          string.find(ob.PrincipiaSearchSource(), obj_searchterm) >= 0
          ))
        and
        (not obj_expr or expr_match(ob, obj_expr))
        and
        (not obj_mtime or mtime_match(ob, obj_mtime, obj_mspec))
        and
        ( (not obj_permission or not obj_roles) or \
           role_match(ob, obj_permission, obj_roles)
        )
        ):
        if apply_func:
961
          apply_func(ob, (apply_path+'/'+p), sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
962 963 964 965 966 967 968 969 970 971 972
        else:
          add_result((p, ob))
          dflag=0

      if search_sub and hasattr(bs, 'objectItems'):
        self.ZopeFindAndApply(ob, obj_ids, obj_metatypes,
                    obj_searchterm, obj_expr,
                    obj_mtime, obj_mspec,
                    obj_permission, obj_roles,
                    search_sub,
                    REQUEST, result, p,
973 974
                    apply_func, apply_path,
                    sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
      if dflag: ob._p_deactivate()

    return result

  def resolve_url(self, path, REQUEST):
    """
    Attempt to resolve a url into an object in the Zope
    namespace. The url may be absolute or a catalog path
    style url. If no object is found, None is returned.
    No exceptions are raised.
    """
    script=REQUEST.script
    if string.find(path, script) != 0:
      path='%s/%s' % (script, path)
    try: return REQUEST.resolve_url(path)
    except: pass

  def resolve_path(self, path):
    """
    Attempt to resolve a url into an object in the Zope
    namespace. The url may be absolute or a catalog path
    style url. If no object is found, None is returned.
    No exceptions are raised.
    """
    try: return self.unrestrictedTraverse(path)
    except: pass

1002
  def manage_normalize_paths(self, REQUEST, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1003 1004 1005 1006 1007
    """Ensure that all catalog paths are full physical paths

    This should only be used with ZCatalogs in which all paths can
    be resolved with unrestrictedTraverse."""

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    if sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)

    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      paths = catalog.paths
      uids = catalog.uids
      unchanged = 0
      fixed = []
      removed = []

      for path, rid in uids.items():
        ob = None
        if path[:1] == '/':
          ob = self.resolve_url(path[1:],REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1023
        if ob is None:
1024 1025 1026 1027 1028 1029 1030 1031 1032
          ob = self.resolve_url(path, REQUEST)
          if ob is None:
            removed.append(path)
            continue
        ppath = string.join(ob.getPhysicalPath(), '/')
        if path != ppath:
          fixed.append((path, ppath))
        else:
          unchanged = unchanged + 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1033

1034 1035 1036 1037 1038 1039 1040
      for path, ppath in fixed:
        rid = uids[path]
        del uids[path]
        paths[rid] = ppath
        uids[ppath] = rid
      for path in removed:
        self.uncatalog_object(path, sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1041 1042 1043 1044 1045 1046

    return MessageDialog(title='Done Normalizing Paths',
      message='%s paths normalized, %s paths removed, and '
          '%s unchanged.' % (len(fixed), len(removed), unchanged),
      action='./manage_main')

1047
  def getTableIds(self, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1048 1049
    """Returns all tables of this catalog
    """
1050 1051 1052 1053
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getTableIds()
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1054

1055
  def getCatalogSearchResultKeys(self, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1056 1057 1058
    """Return selected tables of catalog which are used in JOIN.
       catalaog is always first
    """
1059 1060 1061 1062
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.sql_search_result_keys
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1063

1064
  def getCatalogSearchTableIds(self, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1065 1066 1067
    """Return selected tables of catalog which are used in JOIN.
       catalaog is always first
    """
1068 1069 1070 1071
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getCatalogSearchTableIds()
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1072

1073
  def getResultColumnIds(self, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1074 1075 1076
    """Return selected tables of catalog which are used
       as metadata
    """
1077 1078 1079 1080
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getResultColumnIds()
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1081

1082
  def getCatalogMethodIds(self, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1083 1084 1085
    """Find Z SQL methods in the current folder and above
    This function return a list of ids.
    """
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getCatalogMethodIds()
    return {}

  def manage_editFilter(self, REQUEST=None, RESPONSE=None, URL1=None, sql_catalog_id=None):
    """
    This methods allows to set a filter on each zsql method called,
    so we can test if we should or not call a zsql method, so we can
    increase a lot the speed.
    """
    if REQUEST is not None and sql_catalog_id is None:
      sql_catalog_id = REQUEST.get('sql_catalog_id', None)

    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      catalog.manage_editFilter(REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL1)

  def getFilterableMethodList(self, sql_catalog_id=None):
    """
    Returns only zsql methods wich catalog or uncatalog objets
    """
    catalog = self.getSQLCatalog(sql_catalog_id)
    if catalog is not None:
      return catalog.getFilterableMethodList()
    return []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143


Globals.default__class_init__(ZCatalog)


def p_name(name):
  return '_' + string.translate(name, name_trans) + '_Permission'

def absattr(attr):
  if callable(attr): return attr()
  return attr


class td(RestrictedDTML, TemplateDict):
  pass

def expr_match(ob, ed, c=InstanceDict, r=0):
  e, md, push, pop=ed
  push(c(ob, md))
  try: r=e.eval(md)
  finally:
    pop()
    return r

def mtime_match(ob, t, q, fn=hasattr):
  if not fn(ob, '_p_mtime'):
    return 0
  return q=='<' and (ob._p_mtime < t) or (ob._p_mtime > t)

def role_match(ob, permission, roles, lt=type([]), tt=type(())):
  pr=[]
  fn=pr.append
1144

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
  while 1:
    if hasattr(ob, permission):
      p=getattr(ob, permission)
      if type(p) is lt:
        map(fn, p)
        if hasattr(ob, 'aq_parent'):
          ob=ob.aq_parent
          continue
        break
      if type(p) is tt:
        map(fn, p)
        break
      if p is None:
        map(fn, ('Manager', 'Anonymous'))
        break

    if hasattr(ob, 'aq_parent'):
      ob=ob.aq_parent
      continue
    break

  for role in roles:
    if not (role in pr):
      return 0
  return 1