source: WAeUP_SRP/base/skins/cps_custom/getContentInfo.py @ 2897

Last change on this file since 2897 was 2217, checked in by Henrik Bettermann, 17 years ago

move content from waeup_custom to cps_custom

File size: 10.3 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 486 2006-09-06 10:09:39Z joachim $
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.id
190info['id'] = proxy.getId()
191try:
192    info['title'] = proxy.Title() #proxy.Title()
193except AttributeError:
194    raise AttributeError, 'invalid object: %s in %s' % (info['title_or_id'],
195                                                             info['rpath'])
196except TypeError:
197    info['title'] = proxy.getContent().id
198
199info['icon'] = proxy.getIcon(relative_to_portal=1)
200info['type'] = proxy.getPortalTypeName()
201
202if proxy.getTypeInfo() is not None:
203    info['type_l10n'] = cpsmcat(proxy.getTypeInfo().Title())
204else:
205##    LOG("getContentInfo() pb getting Type Information",
206##        DEBUG,
207##        'Proxy :',
208##        proxy)
209    info['type_l10n'] = ''
210info['review_state'] = wtool.getInfoFor(proxy, 'review_state', '')
211try:
212    info['rev'] = str(proxy.getRevision())
213    info['lang'] = proxy.getLanguage()
214except AttributeError:
215    # not a proxy
216    # FIXME: default lang should not be hardcoded
217    info['rev'] = '0'
218    info['lang'] = 'en'
219info['time'] = proxy.modified()
220
221# level 1
222if level > 0:
223    if doc is None:
224        doc = proxy.getContent()
225    if doc.portal_type == 'Course':
226        info['credits'] = doc.credits
227        info['semester'] = doc.semester
228        info['passmark'] = doc.passmark
229    elif doc.portal_type == 'CertificateCourse':
230        core = 'core'
231        if not doc.core_or_elective:
232            core = 'elective'
233        info['core_or_elective'] = core
234    elif doc.portal_type == 'Student':
235        try:
236            info['clearance'] = proxy.clearance.getContent()
237        except AttributeError:
238            info['clearance'] = None
239    info['time'] = doc.modified()
240    info['doc'] = doc
241    if hasattr(doc,"LongTitle"):
242        info['long_title'] = doc.LongTitle()
243    description = doc.Description() or ''
244    if len(description) > DESCRIPTION_MAX_LENGTH:
245        description = description[:DESCRIPTION_MAX_LENGTH] + '...'
246    info['description'] = description
247    if hasattr(doc.aq_explicit, 'get_size'):
248        try:
249            size = doc.get_size()
250        except:
251            size = 0
252        if size and size < 1024:
253            info['size'] = '1 K'
254        elif size > 1048576:
255            info['size'] = '%.02f M' % float(size/1048576.0)
256        elif size:
257            info['size'] = str(int(size)/1024)+' K'
258
259    if hasattr(doc.aq_explicit, 'start'):
260        if callable(doc.start):
261            start = doc.start()
262        else:
263            start = doc.start
264        if start:
265            info['start'] = start
266            info['start_str'] = context.getDateStr(start)
267
268    if hasattr(doc.aq_explicit, 'end'):
269        if callable(doc.end):
270            end = doc.end()
271        else:
272            end = doc.end
273        if end:
274            info['end'] = end
275            info['end_str'] = context.getDateStr(end)
276
277    for dc in ('Creator', 'Rights', 'Language',
278               'contributors', 'source', 'relation', 'coverage'):
279        key = dc.lower()
280        if key == 'contributors':
281            key = 'contributor'         # this is the real DC name
282        try:
283            meth = getattr(doc, dc)
284            if callable(meth):
285                value = meth()
286            else:
287                value = meth
288            if value and not same_type(value, ''):
289                value = ', '.join(value)
290            info[key] = value
291        except:
292            info[key] = ''
293
294    if hasattr(doc.aq_explicit, 'hidden_folder'):
295        info['hidden'] = doc.hidden_folder
296    else:
297        info['hidden'] = 0
298
299    if hasattr(doc.aq_explicit, 'getAdditionalContentInfo'):
300        add_info = doc.getAdditionalContentInfo(proxy)
301        info.update(add_info)
302
303    if info['review_state'] == 'published':
304        now = context.ZopeTime()
305        eff = doc.effective()
306        exp = doc.expires()
307        if now < eff:
308            info['review_state'] = 'deferred'
309            info['review_state_date'] = context.getDateStr(eff)
310        elif now > exp:
311            info['review_state'] = 'expired'
312            info['review_state_date'] = context.getDateStr(exp)
313
314# level 2
315if level == 2:
316    info['states'], ignore = compute_states(1)
317
318# level 3
319if level >= 3:
320    info['states'], info['history'] = compute_states()
321
322# level 4
323if level >= 4:
324    info['archived'] = compute_archived()
325
326info['level'] = level
327if info['time']:
328    info['time_str'] = context.getDateStr(info['time'])
329else:
330    info['time_str'] = ''
331
332
333if bmt is not None:
334    bmt.setMarker('stop')
335    bmt.saveProfile(context.REQUEST)
336
337return info
Note: See TracBrowser for help on using the repository browser.