source: WAeUP_SRP/trunk/skins/waeup_custom/getContentInfo.py @ 348

Last change on this file since 348 was 306, checked in by joachim, 18 years ago

=fixed missing pts

File size: 9.8 KB
Line 
1## Script (Python) "getContentInfo"
2##bind container=container
3##bind context=context
4##bind namespace=
5##bind script=script
6##bind subpath=traverse_subpath
7##parameters=proxy=None, doc=None, level=0, cpsmcat=None
8##title=
9##
10# $Id: getContentInfo.py 31903 2006-01-21 23:50:55Z fguillaume $
11"""
12Return information about a content item (ie a proxy)
13
14level: 0 (default cost 1)
15  id, title, title_or_id, review_state, icon, rev, lang, type
16  time_str, creator, rpath, url
17level: 1 (cost 1.3)
18  level 0 + descr, size + doc + additional information from obj
19level: 2 (cost 4.6)
20  level 1 + states
21level: 3 (cost 7)
22  level 2 + history
23level: 4 (cost ???)
24  level 3 + archived
25"""
26
27from zLOG import LOG, DEBUG
28from Products.CMFCore.utils import getToolByName
29from AccessControl import Unauthorized
30
31# how many characters for the description
32DESCRIPTION_MAX_LENGTH = 150
33
34if cpsmcat is None:
35    cpsmcat = context.translation_service
36
37if proxy is None:
38    proxy = context
39
40wtool = getToolByName(context, 'portal_workflow')
41utool = getToolByName(context, 'portal_url')
42ptool = getToolByName(context, 'portal_proxies')
43mtool = getToolByName(context, 'portal_membership')
44portal = utool.getPortalObject()
45
46rpath = None
47if hasattr(proxy.aq_explicit, 'getRID'):
48    # this is a brain
49    # rpath is build with catalog path that include languageView selection
50
51    # FIXME: something is broken here when using virtual host monsters
52    rpath = utool.getRpathFromPath(proxy.getPath())
53
54    # change view to switch to have a sticky behaviour
55    from Products.CPSCore.utils import KEYWORD_SWITCH_LANGUAGE, \
56         KEYWORD_VIEW_LANGUAGE
57    rpath = rpath.replace(KEYWORD_VIEW_LANGUAGE, KEYWORD_SWITCH_LANGUAGE)
58    proxy = proxy.getObject()
59
60bmt = getattr(portal, 'Benchmarktimer', None)
61if bmt is not None:
62    bmt = bmt('getContentInfo for ' + proxy.getId(), level=-3)
63    bmt.setMarker('start')
64
65def getRpathTitle(rpath):
66    """Get object's title, or None if Unauthorized or nonexisting."""
67    try:
68        ob = portal.restrictedTraverse(rpath, None)
69        if ob is None:
70            return None
71        return ob.Title()
72    except Unauthorized:
73        return None
74
75
76def compute_states(no_history=0):
77    wf_vars = ['review_state', 'time']
78    docid = proxy.getDocid()
79    if docid:
80        proxies_info = ptool.getProxyInfosFromDocid(docid,
81                                                    workflow_vars=wf_vars)
82    else:
83        # Not a proxy
84        ob_info = {
85            'rpath': utool.getRpath(proxy),
86            'language_revs': {'en': 0},
87            'visible': mtool.checkPermission('View', proxy),
88            }
89        for var in wf_vars:
90            ob_info[var] = wtool.getInfoFor(proxy, var, None)
91        proxies_info = [ob_info]
92    states = []
93    for proxy_info in proxies_info:
94        # take in account only accessible proxies
95        if not proxy_info['visible']:
96            continue
97
98        lrpath = proxy_info['rpath'].split('/')
99        folder_rpath = '/'.join(lrpath[:-1])
100        folder_title = getRpathTitle(folder_rpath)
101        if not folder_title:
102            # Unauthorized
103            if len(lrpath) > 1:
104                folder_title = lrpath[-2]
105            else:
106                folder_title = '?'
107
108        proxy_info_proxy = None
109        portal_type = None
110        if proxy_info.has_key('object'):
111            proxy_info_proxy = proxy_info['object']
112            if hasattr(proxy_info_proxy, 'portal_type'):
113                portal_type = proxy_info_proxy.portal_type
114
115        d = {'rpath': folder_rpath,
116             'title': folder_title,
117             'type': portal_type,
118             'review_state': proxy_info['review_state'],
119             'rev': str(proxy_info['language_revs'].values()[0]),
120             'language': proxy_info['language_revs'].keys()[0],
121             'time': proxy_info['time'],
122             'time_str': context.getDateStr(proxy_info['time']),
123             'proxy': proxy_info_proxy,
124             }
125        d['lang'] = d['language']       # for compatibility
126        states.append(d)
127
128    history = []
129    if not no_history:
130        review_history = wtool.getFullHistoryOf(proxy)
131        if not review_history:
132            review_history = wtool.getInfoFor(proxy, 'review_history', ())
133            remove_redundant = 0
134        else:
135            remove_redundant = 1
136        for d in review_history:
137            if not (d.has_key('actor')
138                    and d.has_key('time')
139                    and d.has_key('action')):
140                continue
141            action = d['action']
142            # Internal transitions hidden from the user.
143            if action in ('unlock', 'checkout_draft_in'):
144                continue
145            # Skip redundant history (two transition when publishing).
146            if action == 'copy_submit' and remove_redundant:
147                continue
148            # Transitions involving a destination container.
149            if action in ('submit', 'copy_submit'):
150                d['has_dest'] = 1
151                dest_container = d.get('dest_container') or '?'
152                d['dest_container'] = dest_container
153                dest_title = getRpathTitle(dest_container)
154                if not dest_title:
155                    # Unauthorized
156                    dest_title = dest_container.split('/')[-1]
157                d['dest_title'] = dest_title
158            d['time_str'] = context.getDateStr(d['time'])
159            history.append(d)
160
161    def cmp_rs(a, b):
162        return -cmp(a['review_state'], b['review_state'])
163    states.sort(cmp_rs)
164
165    def cmp_date(a, b):
166        return -cmp(a['time'], b['time'])
167    history.sort(cmp_date)
168
169    return states, history
170
171def compute_archived():
172    archived = proxy.getArchivedInfos()
173    # Keep only frozen revisions.
174    archived = [d for d in archived if d['is_frozen']]
175    archived.reverse()
176    for d in archived:
177        d['time_str'] = context.getDateStr(d['modified'])
178    return archived
179
180# basic information level 0
181info = {}
182if rpath is None:
183    info['rpath'] = utool.getRpath(proxy)
184else:
185    info['rpath'] = rpath
186
187info['url'] = utool.getUrlFromRpath(info['rpath'])
188
189info['title_or_id'] = proxy.title_or_id()
190info['id'] = proxy.getId()
191try:
192    info['title'] = proxy.Title()
193except AttributeError:
194    raise AttributeError, 'invalid object: %s in %s' % (info['title_or_id'],
195                                                        info['rpath'])
196info['icon'] = proxy.getIcon(relative_to_portal=1)
197info['type'] = proxy.getPortalTypeName()
198
199if proxy.getTypeInfo() is not None:
200    info['type_l10n'] = cpsmcat(proxy.getTypeInfo().Title())
201else:
202    LOG("getContentInfo() pb getting Type Information",
203        DEBUG,
204        'Proxy :',
205        proxy)
206    info['type_l10n'] = ''
207info['review_state'] = wtool.getInfoFor(proxy, 'review_state', '')
208try:
209    info['rev'] = str(proxy.getRevision())
210    info['lang'] = proxy.getLanguage()
211except AttributeError:
212    # not a proxy
213    # FIXME: default lang should not be hardcoded
214    info['rev'] = '0'
215    info['lang'] = 'en'
216info['time'] = proxy.modified()
217
218# level 1
219if level > 0:
220    if doc is None:
221        doc = proxy.getContent()
222    info['time'] = doc.modified()
223    info['doc'] = doc
224    if hasattr(doc,"LongTitle"):
225        info['long_title'] = doc.LongTitle()
226    description = doc.Description() or ''
227    if len(description) > DESCRIPTION_MAX_LENGTH:
228        description = description[:DESCRIPTION_MAX_LENGTH] + '...'
229    info['description'] = description
230    if hasattr(doc.aq_explicit, 'get_size'):
231        try:
232            size = doc.get_size()
233        except:
234            size = 0
235
236        if size and size < 1024:
237            info['size'] = '1 K'
238        elif size > 1048576:
239            info['size'] = '%.02f M' % float(size/1048576.0)
240        elif size:
241            info['size'] = str(int(size)/1024)+' K'
242
243    if hasattr(doc.aq_explicit, 'start'):
244        if callable(doc.start):
245            start = doc.start()
246        else:
247            start = doc.start
248        if start:
249            info['start'] = start
250            info['start_str'] = context.getDateStr(start)
251
252    if hasattr(doc.aq_explicit, 'end'):
253        if callable(doc.end):
254            end = doc.end()
255        else:
256            end = doc.end
257        if end:
258            info['end'] = end
259            info['end_str'] = context.getDateStr(end)
260
261    for dc in ('Creator', 'Rights', 'Language',
262               'contributors', 'source', 'relation', 'coverage'):
263        key = dc.lower()
264        if key == 'contributors':
265            key = 'contributor'         # this is the real DC name
266        try:
267            meth = getattr(doc, dc)
268            if callable(meth):
269                value = meth()
270            else:
271                value = meth
272            if value and not same_type(value, ''):
273                value = ', '.join(value)
274            info[key] = value
275        except:
276            info[key] = ''
277
278    if hasattr(doc.aq_explicit, 'hidden_folder'):
279        info['hidden'] = doc.hidden_folder
280    else:
281        info['hidden'] = 0
282
283    if hasattr(doc.aq_explicit, 'getAdditionalContentInfo'):
284        add_info = doc.getAdditionalContentInfo(proxy)
285        info.update(add_info)
286
287    if info['review_state'] == 'published':
288        now = context.ZopeTime()
289        eff = doc.effective()
290        exp = doc.expires()
291        if now < eff:
292            info['review_state'] = 'deferred'
293            info['review_state_date'] = context.getDateStr(eff)
294        elif now > exp:
295            info['review_state'] = 'expired'
296            info['review_state_date'] = context.getDateStr(exp)
297
298# level 2
299if level == 2:
300    info['states'], ignore = compute_states(1)
301
302# level 3
303if level >= 3:
304    info['states'], info['history'] = compute_states()
305
306# level 4
307if level >= 4:
308    info['archived'] = compute_archived()
309
310info['level'] = level
311if info['time']:
312    info['time_str'] = context.getDateStr(info['time'])
313else:
314    info['time_str'] = ''
315
316
317if bmt is not None:
318    bmt.setMarker('stop')
319    bmt.saveProfile(context.REQUEST)
320
321return info
Note: See TracBrowser for help on using the repository browser.