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

Last change on this file since 447 was 440, checked in by joachim, 18 years ago

levels can be created
keyerror elective fixed
check for blanks in Id's checked

File size: 10.2 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.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'])
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    info['time'] = doc.modified()
235    info['doc'] = doc
236    if hasattr(doc,"LongTitle"):
237        info['long_title'] = doc.LongTitle()
238    description = doc.Description() or ''
239    if len(description) > DESCRIPTION_MAX_LENGTH:
240        description = description[:DESCRIPTION_MAX_LENGTH] + '...'
241    info['description'] = description
242    if hasattr(doc.aq_explicit, 'get_size'):
243        try:
244            size = doc.get_size()
245        except:
246            size = 0
247        if size and size < 1024:
248            info['size'] = '1 K'
249        elif size > 1048576:
250            info['size'] = '%.02f M' % float(size/1048576.0)
251        elif size:
252            info['size'] = str(int(size)/1024)+' K'
253
254    if hasattr(doc.aq_explicit, 'start'):
255        if callable(doc.start):
256            start = doc.start()
257        else:
258            start = doc.start
259        if start:
260            info['start'] = start
261            info['start_str'] = context.getDateStr(start)
262
263    if hasattr(doc.aq_explicit, 'end'):
264        if callable(doc.end):
265            end = doc.end()
266        else:
267            end = doc.end
268        if end:
269            info['end'] = end
270            info['end_str'] = context.getDateStr(end)
271
272    for dc in ('Creator', 'Rights', 'Language',
273               'contributors', 'source', 'relation', 'coverage'):
274        key = dc.lower()
275        if key == 'contributors':
276            key = 'contributor'         # this is the real DC name
277        try:
278            meth = getattr(doc, dc)
279            if callable(meth):
280                value = meth()
281            else:
282                value = meth
283            if value and not same_type(value, ''):
284                value = ', '.join(value)
285            info[key] = value
286        except:
287            info[key] = ''
288
289    if hasattr(doc.aq_explicit, 'hidden_folder'):
290        info['hidden'] = doc.hidden_folder
291    else:
292        info['hidden'] = 0
293
294    if hasattr(doc.aq_explicit, 'getAdditionalContentInfo'):
295        add_info = doc.getAdditionalContentInfo(proxy)
296        info.update(add_info)
297
298    if info['review_state'] == 'published':
299        now = context.ZopeTime()
300        eff = doc.effective()
301        exp = doc.expires()
302        if now < eff:
303            info['review_state'] = 'deferred'
304            info['review_state_date'] = context.getDateStr(eff)
305        elif now > exp:
306            info['review_state'] = 'expired'
307            info['review_state_date'] = context.getDateStr(exp)
308
309# level 2
310if level == 2:
311    info['states'], ignore = compute_states(1)
312
313# level 3
314if level >= 3:
315    info['states'], info['history'] = compute_states()
316
317# level 4
318if level >= 4:
319    info['archived'] = compute_archived()
320
321info['level'] = level
322if info['time']:
323    info['time_str'] = context.getDateStr(info['time'])
324else:
325    info['time_str'] = ''
326
327
328if bmt is not None:
329    bmt.setMarker('stop')
330    bmt.saveProfile(context.REQUEST)
331
332return info
Note: See TracBrowser for help on using the repository browser.