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

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

added columns for semester credits passmark to courseslisting and
core_or_elective to certificate courses semester listing

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