source: products/qTopic/branches/plone2.1/qTopic.py

Last change on this file was 1, checked in by myroslav, 18 years ago

Building directory structure

File size: 8.7 KB
Line 
1from locale import strcoll
2from Products.CMFCore import CMFCorePermissions
3from Products.CMFCore.utils import getToolByName
4from AccessControl import ClassSecurityInfo
5from Acquisition import aq_parent, aq_inner
6
7from Products.ATContentTypes.content.base import updateActions
8from Products.ATContentTypes.content.topic import ATTopic, IGNORED_FIELDS
9from Products.ATContentTypes.interfaces import IATTopic
10from Products.ATContentTypes.types.criteria import _criterionRegistry
11from Products.ATContentTypes.permission import ChangeTopics, AddTopics
12from Products.CMFCore.permissions import View
13from Products.ATContentTypes.content.topic import ATTopicSchema
14from Products.ATContentTypes.interfaces import IATTopicSearchCriterion, IATTopicSortCriterion
15from Products.Archetypes.public import *
16from config import *
17from Products.CMFPlone.PloneBatch import Batch
18from Products.ATContentTypes.config import TOOLNAME
19
20qTopic_schema = ATTopicSchema.copy() + Schema((
21          StringField("catalog",
22                       default = "portal_catalog",
23                       vocabulary = "getCatalogList",
24                       widget = SelectionWidget(label="Catalog",
25                                       label_msgid="label_catalog",
26                                       description="Select catalog to query",
27                                       description_msgid="description_catalog")
28          ),
29          BooleanField("showHeader",
30                      schemata = "export",
31                      default = 1,
32                      widget = BooleanWidget(label="Print field headers",
33                                             label_msgid="label_print_headers",
34                                             description="Check if headers need to be printed",
35                                             description_msgid="description_print_headers")
36          ),
37          StringField("delimiter",
38                      default = ";",
39                      schemata = "export",
40                      widget = StringWidget(label="Values delimiter",
41                                            label_msgid="label_delimiter",
42                                            description="Select delimiter to be used in CSV",
43                                            description_msgid="description_delimiter",
44                                            size = 4)
45          ),
46          ))
47qTopic_schema["customViewFields"].schemata = "export"
48qTopic_schema["customViewFields"].vocabulary = "getFieldsList"
49qTopic_schema["customViewFields"].default=("id","getFullName","getEmail")
50
51class qTopic(ATTopic):
52    """A topic folder"""
53    meta_type      = "qTopic"
54    portal_type    = "qTopic"
55    archetype_name = "qTopic"
56    typeDescription= ("qTopic is the same topic but with "+
57                      "option of catlog selection")
58    typeDescMsgId  = "description_edit_topic"
59
60    schema = qTopic_schema
61    security       = ClassSecurityInfo()
62    actions = updateActions(ATTopic,
63        (
64        {
65        "id"          : "export_csv",
66        "name"        : "Export in CSV",
67        "action"      : "string:${folder_url}/result_csv",
68        "permissions" : (CMFCorePermissions.View,)
69        },
70       )
71    )
72
73    def getCatalogList(self):
74        """ return list of catalog ids
75        """
76        at_tool = getToolByName(self, "archetype_tool")
77        catalogs = at_tool.getCatalogsInSite()
78        return  DisplayList(zip(catalogs, catalogs))
79
80    def getFieldsList(self):
81        """ return DisplayList of fields
82        """
83        pcatalog = getToolByName( self, self.getCatalog() )
84        available = pcatalog.schema()
85        val = [ field
86                 for field in available
87                 if  field not in IGNORED_FIELDS
88               ]
89        val.sort(lambda x,y: strcoll(self.translate(x),self.translate( y)))
90        return [(i, i, i)for i in val]
91
92    security.declareProtected(ChangeTopics, "criteriaByIndexId")
93    def criteriaByIndexId(self, indexId):
94        """ get createrias bu index """
95        catalog_tool = getToolByName(self, self.getCatalog())
96        indexObj = catalog_tool.Indexes[indexId]
97        results = _criterionRegistry.criteriaByIndex(indexObj.meta_type)
98        return results
99
100    security.declareProtected(View, 'allowedCriteriaForField')
101    def allowedCriteriaForField(self, field, display_list=False):
102        """ Return all valid criteria for a given field.  Optionally include
103            descriptions in list in format [(desc1, val1) , (desc2, val2)] for
104            javascript selector."""
105        tool = getToolByName(self, self.getCatalog())
106        criteria = _criterionRegistry.listTypes()
107        allowed = [crit for crit in criteria
108                                if crit in self.criteriaByIndexId(field)]
109        if display_list:
110            flat = []
111            for a in allowed:
112                desc = _criterionRegistry[a].shortDesc
113                flat.append((a,desc))
114            allowed = DisplayList(flat)
115        return allowed
116    """
117    security.declareProtected(ChangeTopics, "listFields")
118    def listFields(self):
119        pcatalog = getToolByName( self, self.getCatalog() )
120        available = pcatalog.indexes()
121        val = [ field
122                 for field in available
123                 if  field not in IGNORED_FIELDS
124               ]
125        val.sort(lambda x,y: strcoll(self.translate(x),self.translate( y)))
126        return [(i, i, i)for i in val]
127     """
128    security.declareProtected(ChangeTopics, "listFields")
129    def listFields(self):
130        """Return a list of fields from portal_catalog.
131        """
132        tool = getToolByName(self, TOOLNAME)
133        return tool.getEnabledFields(catalog_name=self.getCatalog())
134
135    security.declareProtected(ChangeTopics, 'listAvailableFields')
136    def listAvailableFields(self):
137        """Return a list of available fields for new criteria.
138        """
139        return self.listFields()
140   
141    security.declareProtected(View, 'listMetaDataFields')
142    def listMetaDataFields(self, exclude=True):
143        """Return a list of metadata fields from portal_catalog.
144        """
145        tool = getToolByName(self, TOOLNAME)
146        catalog_name=self.getCatalog()
147        return tool.getMetadataDisplay(exclude,catalog_name=catalog_name)
148
149    security.declareProtected(CMFCorePermissions.View, "queryCatalog")
150    def queryCatalog(self, REQUEST=None, batch=False, b_size=None,
151                                                    full_objects=False, **kw):
152        """Invoke the catalog using our criteria to augment any passed
153            in query before calling the catalog.
154        """
155        if REQUEST is None:
156            REQUEST = getattr(self, 'REQUEST', {})
157        b_start = REQUEST.get('b_start', 0)
158
159        q = self.buildQuery()
160        if q is None:
161            # empty query - do not show anything
162            if batch:
163                return Batch([], 20, int(b_start), orphan=0)
164            return []
165        # Allow parameters to further limit existing criterias
166        for k,v in q.items():
167            if kw.has_key(k):
168                arg = kw.get(k)
169                if isinstance(arg, (ListType,TupleType)) and isinstance(v, (ListType,TupleType)):
170                    kw[k] = [x for x in arg if x in v]
171                elif isinstance(arg, StringType) and isinstance(v, (ListType,TupleType)) and arg in v:
172                    kw[k] = [arg]
173                else:
174                    kw[k]=v
175            else:
176                kw[k]=v
177        #kw.update(q)
178        pcatalog = getToolByName(self, self.getCatalog())
179        limit = self.getLimitNumber()
180        max_items = self.getItemCount()
181        # Batch based on limit size if b_szie is unspecified
182        if max_items and b_size is None:
183            b_size = int(max_items)
184        else:
185            b_size = 20
186        if limit and max_items and self.hasSortCriterion():
187            # Sort limit helps Zope 2.6.1+ to do a faster query
188            # sorting when sort is involved
189            # See: http://zope.org/Members/Caseman/ZCatalog_for_2.6.1
190            kw.setdefault('sort_limit', max_items)
191        __traceback_info__ = (self, kw,)
192        results = pcatalog.searchResults(REQUEST, **kw)
193        if full_objects and not limit:
194            results = [b.getObject() for b in results]
195        if batch:
196            batch = Batch(results, b_size, int(b_start), orphan=0)
197            return batch
198        if limit:
199            if full_objects:
200                return [b.getObject() for b in results[:max_items]]
201            return results[:max_items]
202        return results
203
204
205
206registerType(qTopic, PROJECTNAME)
207
208def modify_fti(fti):
209    """Remove folderlisting action
210    """
211    actions = []
212    for action in fti["actions"]:
213        if action["id"] == "folderlisting":
214                action["visible"] = False
215                #actions.append(action)
216    #fti["actions"] = tuple(actions)
Note: See TracBrowser for help on using the repository browser.