/
ZCatalog.py
1063 lines (852 loc) · 35.8 KB
/
ZCatalog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
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
885
886
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
932
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
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
##############################################################################
#
# 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
$Id$
"""
import urllib, time, sys, string,logging
from Globals import DTMLFile, MessageDialog
import Globals
from OFS.Folder import Folder
from OFS.ObjectManager import ObjectManager
from DateTime import DateTime
from Acquisition import Implicit
from Persistence import Persistent
from DocumentTemplate.DT_Util import InstanceDict, TemplateDict
from DocumentTemplate.DT_Util import Eval
from AccessControl.Permission import name_trans
from Catalog import Catalog, CatalogError
from AccessControl.DTML import RestrictedDTML
from AccessControl.Permissions import \
manage_zcatalog_entries, manage_zcatalog_indexes, search_zcatalog
from ZCatalogIndexes import ZCatalogIndexes
from ZODB.POSException import ConflictError
from Products.PluginIndexes.common.PluggableIndex \
import PluggableIndexInterface
from Products.PluginIndexes.TextIndex import Splitter
from IZCatalog import IZCatalog
from ProgressHandler import ZLogHandler
LOG = logging.getLogger('Zope.ZCatalog')
manage_addZCatalogForm=DTMLFile('dtml/addZCatalog',globals())
def manage_addZCatalog(self, id, title,
vocab_id=None, # Deprecated
REQUEST=None):
"""Add a ZCatalog object
"""
id=str(id)
title=str(title)
c=ZCatalog(id, title, vocab_id, 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.
"""
__implements__ = IZCatalog
meta_type = "ZCatalog"
icon='misc_/ZCatalog/ZCatalog.gif'
manage_options = (
{'label': 'Contents', # TAB: Contents
'action': 'manage_main',
'help': ('OFSP','ObjectManager_Contents.stx')},
{'label': 'Catalog', # TAB: Cataloged Objects
'action': 'manage_catalogView',
'help':('ZCatalog','ZCatalog_Cataloged-Objects.stx')},
{'label': 'Properties', # TAB: Properties
'action': 'manage_propertiesForm',
'help': ('OFSP','Properties.stx')},
{'label': 'Indexes', # TAB: Indexes
'action': 'manage_catalogIndexes',
'help': ('ZCatalog','ZCatalog_Indexes.stx')},
{'label': 'Metadata', # TAB: Metadata
'action': 'manage_catalogSchema',
'help':('ZCatalog','ZCatalog_MetaData-Table.stx')},
{'label': 'Find Objects', # TAB: Find Objects
'action': 'manage_catalogFind',
'help':('ZCatalog','ZCatalog_Find-Items-to-ZCatalog.stx')},
{'label': 'Advanced', # TAB: Advanced
'action': 'manage_catalogAdvanced',
'help':('ZCatalog','ZCatalog_Advanced.stx')},
{'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',
'manage_catalogSchema', 'manage_catalogIndexes',
'manage_catalogAdvanced', 'manage_objectInformation',
'manage_catalogReindex', 'manage_catalogFoundItems',
'manage_catalogClear', 'manage_addColumn', 'manage_delColumn',
'manage_addIndex', 'manage_delIndex', 'manage_clearIndex',
'manage_reindexIndex', 'manage_main', 'availableSplitters',
'manage_setProgress',
# these two are deprecated:
'manage_delColumns', 'manage_deleteIndex'
],
['Manager']),
(search_zcatalog,
['searchResults', '__call__', 'uniqueValuesFor',
'getpath', 'schema', 'indexes', 'index_objects',
'all_meta_types', 'valid_roles', 'resolve_url',
'getobject', 'search'],
['Anonymous', 'Manager']),
(manage_zcatalog_indexes,
['getIndexObjects'],
['Manager']),
)
manage_catalogAddRowForm = DTMLFile('dtml/catalogAddRowForm', globals())
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())
manage_objectInformation = DTMLFile('dtml/catalogObjectInformation',
globals())
Indexes = ZCatalogIndexes()
threshold=10000
_v_total=0
_v_transaction = None
def __init__(self, id, title='', vocab_id=None, container=None):
# ZCatalog no longer cares about vocabularies
# so the vocab_id argument is ignored (Casey)
if container is not None:
self=self.__of__(container)
self.id=id
self.title=title
# vocabulary and vocab_id are left for backwards
# compatibility only, they are not used anymore
self.vocabulary = None
self.vocab_id = ''
self.threshold = 10000
self._v_total = 0
self._catalog = Catalog()
def __len__(self):
# Perform a migration of _catalog.__len__ to _catalog._length
# to avoid with new-style class caching issues (see #1332)
self._catalog.migrate__len__()
return len(self._catalog)
# getVocabulary method is no longer supported
# def getVocabulary(self):
# """ more ack! """
# return getattr(self, self.vocab_id)
def manage_edit(self, RESPONSE, URL1, threshold=1000, REQUEST=None):
""" edit the catalog """
if type(threshold) is not type(1):
threshold=int(threshold)
self.threshold = threshold
RESPONSE.redirect(
URL1 + '/manage_main?manage_tabs_message=Catalog%20Changed')
def manage_subbingToggle(self, REQUEST, RESPONSE, URL1):
""" toggle subtransactions """
if self.threshold:
self.threshold = None
else:
self.threshold = 10000
RESPONSE.redirect(
URL1 +
'/manage_catalogAdvanced?manage_tabs_message=Catalog%20Changed')
def manage_catalogObject(self, REQUEST, RESPONSE, URL1, urls=None):
""" index Zope object(s) that 'urls' point to """
if urls:
if isinstance(urls, str):
urls=(urls,)
for url in urls:
obj = self.resolve_path(url)
if not obj:
obj = self.resolve_url(url, REQUEST)
if obj is not None:
self.catalog_object(obj, url)
RESPONSE.redirect(
URL1 +
'/manage_catalogView?manage_tabs_message=Object%20Cataloged')
def manage_uncatalogObject(self, REQUEST, RESPONSE, URL1, urls=None):
""" removes Zope object(s) 'urls' from catalog """
if urls:
if isinstance(urls, str):
urls=(urls,)
for url in urls:
self.uncatalog_object(url)
RESPONSE.redirect(
URL1 +
'/manage_catalogView?manage_tabs_message=Object%20Uncataloged')
def manage_catalogReindex(self, REQUEST, RESPONSE, URL1):
""" clear the catalog, then re-index everything """
elapse = time.time()
c_elapse = time.clock()
pgthreshold = self._getProgressThreshold()
handler = (pgthreshold > 0) and ZLogHandler(pgthreshold) or None
self.refreshCatalog(clear=1, pghandler=handler)
elapse = time.time() - elapse
c_elapse = time.clock() - c_elapse
RESPONSE.redirect(
URL1 +
'/manage_catalogAdvanced?manage_tabs_message=' +
urllib.quote('Catalog Updated \n'
'Total time: %s\n'
'Total CPU time: %s' % (`elapse`, `c_elapse`)))
def refreshCatalog(self, clear=0, pghandler=None):
""" re-index everything we can find """
cat = self._catalog
paths = cat.paths.values()
if clear:
paths = tuple(paths)
cat.clear()
num_objects = len(paths)
if pghandler:
pghandler.init('Refreshing catalog: %s' % self.absolute_url(1), num_objects)
for i in xrange(num_objects):
if pghandler: pghandler.report(i)
p = paths[i]
obj = self.resolve_path(p)
if not obj:
obj = self.resolve_url(p, self.REQUEST)
if obj is not None:
try:
self.catalog_object(obj, p, pghandler=pghandler)
except ConflictError:
raise
except:
LOG.error('Recataloging object at %s failed' % p,
exc_info=sys.exc_info())
if pghandler: pghandler.finish()
def manage_catalogClear(self, REQUEST=None, RESPONSE=None, URL1=None):
""" clears the whole enchilada """
self._catalog.clear()
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogAdvanced?manage_tabs_message=Catalog%20Cleared')
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,
obj_permission=None):
""" Find object according to search criteria and Catalog them
"""
elapse = time.time()
c_elapse = time.clock()
words = 0
obj = REQUEST.PARENTS[1]
path = '/'.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,
apply_path=path)
elapse = time.time() - elapse
c_elapse = time.clock() - c_elapse
RESPONSE.redirect(
URL1 +
'/manage_catalogView?manage_tabs_message=' +
urllib.quote('Catalog Updated\n'
'Total time: %s\n'
'Total CPU time: %s'
% (`elapse`, `c_elapse`))
)
def manage_addColumn(self, name, REQUEST=None, RESPONSE=None, URL1=None):
""" add a column """
self.addColumn(name)
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogSchema?manage_tabs_message=Column%20Added')
def manage_delColumns(self, names, REQUEST=None, RESPONSE=None, URL1=None):
""" Deprecated method. Use manage_delColumn instead. """
# log a deprecation warning
import warnings
warnings.warn(
"The manage_delColumns method of ZCatalog is deprecated"
"since Zope 2.4.2.\n"
"This method is only kept for backwards compatibility "
"for a while\n"
"and will go away in a future release.\n"
"\n"
"Please use instead the manage_delColumn method.\n"
,DeprecationWarning)
self.manage_delColumn(names, REQUEST=REQUEST, RESPONSE=RESPONSE,
URL1=URL1)
def manage_delColumn(self, names, REQUEST=None, RESPONSE=None, URL1=None):
""" delete a column or some columns """
if isinstance(names, str):
names = (names,)
for name in names:
self.delColumn(name)
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogSchema?manage_tabs_message=Column%20Deleted')
def manage_addIndex(self, name, type, extra=None,
REQUEST=None, RESPONSE=None, URL1=None):
"""add an index """
self.addIndex(name, type,extra)
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogIndexes?manage_tabs_message=Index%20Added')
def manage_deleteIndex(self, ids=None, REQUEST=None, RESPONSE=None,
URL1=None):
""" Deprecated method. Use manage_delIndex instead. """
# log a deprecation warning
import warnings
warnings.warn(
"The manage_deleteIndex method of ZCatalog is deprecated"
"since Zope 2.4.2.\n"
"This method is only kept for backwards compatibility for a "
"while\n"
"and will go away in a future release.\n"
"\n"
"Please use instead the manage_delIndex method.\n"
,DeprecationWarning)
self.manage_delIndex(ids=ids, REQUEST=REQUEST, RESPONSE=RESPONSE,
URL1=URL1)
def manage_delIndex(self, ids=None, REQUEST=None, RESPONSE=None,
URL1=None):
""" delete an index or some indexes """
if not ids:
return MessageDialog(title='No items specified',
message='No items were specified!',
action = "./manage_catalogIndexes",)
if isinstance(ids, str):
ids = (ids,)
for name in ids:
self.delIndex(name)
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogIndexes?manage_tabs_message=Index%20Deleted')
def manage_clearIndex(self, ids=None, REQUEST=None, RESPONSE=None,
URL1=None):
""" clear an index or some indexes """
if not ids:
return MessageDialog(title='No items specified',
message='No items were specified!',
action = "./manage_catalogIndexes",)
if isinstance(ids, str):
ids = (ids,)
for name in ids:
self.clearIndex(name)
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogIndexes?manage_tabs_message=Index%20Cleared')
def reindexIndex(self, name, REQUEST, pghandler=None):
if isinstance(name, str):
name = (name,)
paths = self._catalog.uids.keys()
num_paths = len(paths) # inefficient
i = 0
if pghandler:
pghandler.init('reindexing %s' % name, num_paths)
for p in paths:
i+=1
if pghandler: pghandler.report(i)
obj = self.resolve_path(p)
if not obj:
obj = self.resolve_url(p, REQUEST)
if obj is None:
LOG.error('reindexIndex could not resolve '
'an object from the uid %r.' % p)
else:
# don't update metadata when only reindexing a single
# index via the UI
try:
self.catalog_object(obj, p, idxs=name,
update_metadata=0, pghandler=pghandler)
except TypeError:
# Fall back to Zope 2.6.2 interface. This is necessary for
# products like CMF 1.4.2 and earlier that subclass from
# ZCatalog and don't support the update_metadata argument.
# May be removed some day.
from warnings import warn
warn('catalog_object interface of %s not up to date'
% self.__class__.__name__,
DeprecationWarning)
self.catalog_object(obj, p, idxs=name, pghandler=pghandler)
if pghandler:
pghandler.finish()
def manage_reindexIndex(self, ids=None, REQUEST=None, RESPONSE=None,
URL1=None):
"""Reindex indexe(s) from a ZCatalog"""
if not ids:
return MessageDialog(title='No items specified',
message='No items were specified!',
action = "./manage_catalogIndexes",)
pgthreshold = self._getProgressThreshold()
handler = (pgthreshold > 0) and ZLogHandler(pgthreshold) or None
self.reindexIndex(ids, REQUEST, handler)
if REQUEST and RESPONSE:
RESPONSE.redirect(
URL1 +
'/manage_catalogIndexes'
'?manage_tabs_message=Reindexing%20Performed')
def availableSplitters(self):
""" splitter we can add """
return Splitter.availableSplitters
def catalog_object(self, obj, uid=None, idxs=None, update_metadata=1, pghandler=None):
""" wrapper around catalog """
if uid is None:
try: uid = obj.getPhysicalPath
except AttributeError:
raise CatalogError(
"A cataloged object must support the 'getPhysicalPath' "
"method if no unique id is provided when cataloging"
)
else: uid='/'.join(uid())
elif not isinstance(uid,str):
raise CatalogError('The object unique id must be a string.')
self._catalog.catalogObject(obj, uid, None, idxs,
update_metadata=update_metadata)
# None passed in to catalogObject as third argument indicates
# that we shouldn't try to commit subtransactions within any
# indexing code. We throw away the result of the call to
# catalogObject (which is a word count), because it's
# worthless to us here.
if self.threshold is not None:
# figure out whether or not to commit a subtransaction.
t = id(get_transaction())
if t != self._v_transaction:
self._v_total = 0
self._v_transaction = t
self._v_total = self._v_total + 1
# increment the _v_total counter for this thread only and get
# a reference to the current transaction.
# the _v_total counter is zeroed if we notice that we're in
# a different transaction than the last one that came by.
# self.threshold represents the number of times that
# catalog_object needs to be called in order for the catalog
# to commit a subtransaction. The semantics here mean that
# we should commit a subtransaction if our threshhold is
# exceeded within the boundaries of the current transaction.
if self._v_total > self.threshold:
get_transaction().commit(1)
self._p_jar.cacheGC()
self._v_total = 0
if pghandler:
pghandler.info('commiting subtransaction')
def uncatalog_object(self, uid):
"""Wrapper around catalog """
self._catalog.uncatalogObject(uid)
def uniqueValuesFor(self, name):
"""Return the unique values for a given FieldIndex """
return self._catalog.uniqueValuesFor(name)
def getpath(self, rid):
"""Return the path to a cataloged object given a 'data_record_id_'
"""
return self._catalog.paths[rid]
def getrid(self, path, default=None):
"""Return 'data_record_id_' the to a cataloged object given a 'path'
"""
return self._catalog.uids.get(path, default)
def getobject(self, rid, REQUEST=None):
"""Return a cataloged object given a 'data_record_id_'
"""
obj = self.aq_parent.unrestrictedTraverse(self.getpath(rid))
if not obj:
if REQUEST is None:
REQUEST=self.REQUEST
obj = self.resolve_url(self.getpath(rid), REQUEST)
return obj
def getMetadataForUID(self, uid):
"""return the correct metadata given the uid, usually the path"""
rid = self._catalog.uids[uid]
return self._catalog.getMetadataForRID(rid)
def getIndexDataForUID(self, uid):
"""return the current index contents given the uid, usually the path"""
rid = self._catalog.uids[uid]
return self._catalog.getIndexDataForRID(rid)
def getMetadataForRID(self, rid):
"""return the correct metadata for the cataloged record id"""
return self._catalog.getMetadataForRID(int(rid))
def getIndexDataForRID(self, rid):
"""return the current index contents for the specific rid"""
return self._catalog.getIndexDataForRID(rid)
def schema(self):
return self._catalog.schema.keys()
def indexes(self):
return self._catalog.indexes.keys()
def index_objects(self):
# This method returns unwrapped indexes!
# You should probably use getIndexObjects instead
return self._catalog.indexes.values()
def getIndexObjects(self):
# Return a list of wrapped(!) indexes
getIndex = self._catalog.getIndex
return [getIndex(name) for name in self.indexes()]
def _searchable_arguments(self):
r = {}
n={'optional':1}
for name in self._catalog.indexes.keys():
r[name]=n
return r
def _searchable_result_columns(self):
r = []
for name in self._catalog.schema.keys():
i = {}
i['name'] = name
i['type'] = 's'
i['parser'] = str
i['width'] = 8
r.append(i)
r.append({'name': 'data_record_id_',
'type': 's',
'parser': str,
'width': 8})
return r
def searchResults(self, REQUEST=None, used=None, **kw):
"""Search the catalog
Search terms can be passed in the REQUEST or as keyword
arguments.
The used argument is now deprecated and ignored
"""
return self._catalog.searchResults(REQUEST, used, **kw)
__call__=searchResults
def search(
self, query_request, sort_index=None, reverse=0, limit=None, merge=1):
"""Programmatic search interface, use for searching the catalog from
scripts.
query_request: Dictionary containing catalog query
sort_index: Name of sort index
reverse: Reverse sort order?
limit: Limit sorted result count (optimization hint)
merge: Return merged results (like searchResults) or raw
results for later merging.
"""
if sort_index is not None:
sort_index = self._catalog.indexes[sort_index]
return self._catalog.search(
query_request, sort_index, reverse, limit, merge)
## this stuff is so the find machinery works
meta_types=() # Sub-object types that are specific to this object
# Dont need this anymore -- we inherit from object manager
#def all_meta_types(self):
# pmt=()
# if hasattr(self, '_product_meta_types'): pmt=self._product_meta_types
# elif hasattr(self, 'aq_acquire'):
# try: pmt=self.aq_acquire('_product_meta_types')
# except AttributeError: pass
# return self.meta_types+Products.meta_types+pmt
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='',
apply_func=None, apply_path=''):
"""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
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
ob.PrincipiaSearchSource().find(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:
apply_func(ob, (apply_path+'/'+p))
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,
apply_func, apply_path)
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.
"""
if REQUEST:
script=REQUEST.script
if path.find(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
def manage_normalize_paths(self, REQUEST):
"""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."""
paths = self._catalog.paths
uids = self._catalog.uids
unchanged = 0
fixed = []
removed = []
for path, rid in uids.items():
ob = None
if path[:1] == '/':
ob = self.resolve_url(path[1:],REQUEST)
if ob is None:
ob = self.resolve_url(path, REQUEST)
if ob is None:
removed.append(path)
continue
ppath = '/'.join(ob.getPhysicalPath())
if path != ppath:
fixed.append((path, ppath))
else:
unchanged = unchanged + 1
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)
return MessageDialog(title='Done Normalizing Paths',
message='%s paths normalized, %s paths removed, and '
'%s unchanged.' % (len(fixed), len(removed), unchanged),
action='./manage_main')
def manage_setProgress(self, pgthreshold=0, RESPONSE=None, URL1=None):
"""Set parameter to perform logging of reindexing operations very
'pgthreshold' objects
"""
self.pgthreshold = pgthreshold
if RESPONSE:
RESPONSE.redirect(
URL1 + '/manage_main?manage_tabs_message=Catalog%20Changed')
def _getProgressThreshold(self):
if not hasattr(self, 'pgthreshold'):
self.pgthreshold = 0
return self.pgthreshold
def manage_convertBTrees(self, threshold=200):
"""Convert the catalog's data structures to use BTrees package"""
assert type(threshold) is type(0)
tt=time.time()
ct=time.clock()
self._catalog._convertBTrees(threshold)
tt=time.time()-tt
ct=time.clock()-ct
return 'Finished conversion in %s seconds (%s cpu)' % (tt, ct)
def manage_convertIndex(self, ids, REQUEST=None, RESPONSE=None, URL1=None):
"""convert old-style indexes to new-style indexes"""
from Products.PluginIndexes.KeywordIndex import KeywordIndex
from Products.PluginIndexes.FieldIndex import FieldIndex
from Products.PluginIndexes.TextIndex import TextIndex
converted = []
for id in ids:
idx = self.Indexes[id]
iface = getattr(idx,'__implements__',None)
if iface is None:
mt = idx.meta_type
converted.append(id)
self.delIndex(id)
if mt in ('Field Index','Keyword Index'):
self.addIndex(id,mt.replace(' ',''))
elif mt == 'Text Index':
# TODO: Lexicon handling to be added
self.addIndex(id,'TextIndex')
if converted:
RESPONSE.redirect(
URL1 +
'/manage_main?manage_tabs_message=Indexes%20converted')
else:
RESPONSE.redirect(
URL1 +
'/manage_main?'
'manage_tabs_message='
'No%20indexes%20found%20to%20be%20converted')
#
# Indexing methods
#
def addIndex(self, name, type,extra=None):
# Convert the type by finding an appropriate product which supports
# this interface by that name. Bleah
products = ObjectManager.all_meta_types(self, interfaces=(
PluggableIndexInterface,))
p = None
for prod in products:
if prod['name'] == type:
p = prod
break
if p is None:
raise ValueError, "Index of type %s not found" % type
base = p['instance']
if base is None:
raise ValueError, "Index type %s does not support addIndex" % type
# This code is *really* lame but every index type has its own
# function signature *sigh* and there is no common way to pass
# additional parameters to the constructor. The suggested way
# for new index types is to use an "extra" record.
if 'extra' in base.__init__.func_code.co_varnames:
index = base(name, extra=extra, caller=self)
elif 'caller' in base.__init__.func_code.co_varnames:
index = base(name, caller=self)
else:
index = base(name)
self._catalog.addIndex(name,index)
def delIndex(self, name ):
self._catalog.delIndex(name)
def clearIndex(self, name):
self._catalog.getIndex(name).clear()