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

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

moved StudyLevel? class from Academics.py back to Students.py,
cause this Change broke existing StudyLevel? Objects.

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