source: trunk/Collection.py @ 1860

Revision 1860, 24.6 KB checked in by jukka, 12 years ago (diff)

Closed #1452, closed #1417. LeMillReferences?, MultimediaMaterials?, Methods and Tools can be converted to each others. All necessary information is kept and the tool will warn if some field with text will be lost in new format. Visible only for managers until the UI is accepted by designers.

Line 
1# Copyright 2006 by the LeMill Team (see AUTHORS)
2#
3# This file is part of LeMill.
4#
5# LeMill is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# LeMill is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with LeMill; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
19from Products.Archetypes.public import *
20from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget
21from Products.CMFCore.permissions import ModifyPortalContent
22from Products.Archetypes.public import BaseContent, registerType, BaseFolder
23from Products.Archetypes.public import StringField
24from Products.Archetypes.public import TextAreaWidget
25from Products.Archetypes.atapi import DisplayList
26from Globals import InitializeClass
27from Products.CMFCore.utils import getToolByName
28from AccessControl import ClassSecurityInfo, Unauthorized
29from SharedMetadata import score
30
31from config import PROJECTNAME, ALL_CONTENT_TYPES, CONTENT_TYPES, DEFAULT_ICONS, ACTIVITY_TYPES, TOOLS_TYPES
32from Resources import Resource
33from permissions import MODIFY_CONTENT
34
35import sre
36from cStringIO import StringIO
37import zipfile
38from urllib2 import urlopen, HTTPError
39
40schema = BaseSchema + score + Schema((
41
42    StringField('description',
43        accessor='Description',
44        widget=TextAreaWidget(
45            label="Learning and teaching story",
46            description="",
47            label_msgid='label_learning_story',
48            description_msgid='description_description',
49            i18n_domain = "lemill",
50            visible={'view':'invisible','edit':'visible'},
51        ),
52    ),
53   
54    ReferenceField('refsToResources',
55        accessor = 'getRefsToResources',
56        relationship = 'References',
57        mutator = 'addRefsToResources',
58        allowed_types = ALL_CONTENT_TYPES,
59        multiValued = True,
60        widget = ReferenceBrowserWidget(
61            visible = {'view':'invisible', 'edit':'invisible'},
62            ),
63    ),
64    ReferenceField('relatedContent',
65        relationship = 'relatesToContent',
66        multiValued = True,
67        isMetadata = True,
68        languageIndependent = False,
69        index = 'KeywordIndex',
70        write_permission = ModifyPortalContent,
71        allowed_types= ALL_CONTENT_TYPES,
72        widget = ReferenceBrowserWidget(
73            allow_search = True,
74            allow_browse = True,
75            show_indexes = False,
76            force_close_on_insert = True,
77            startup_directory = "content",
78            size = 4,
79            i18n_domain = "lemill",
80            label = "Related Content",
81            label_msgid = "label_related_content",
82            description = "",
83            description_msgid = "help_story_related_content",
84            visible = {'edit' : 'invisible', 'view' : 'invisible' }
85            )
86        ),
87    ReferenceField('relatedMethods',
88        relationship = 'relatesToMethods',
89        multiValued = True,
90        isMetadata = True,
91        languageIndependent = False,
92        index = 'KeywordIndex',
93        write_permission = ModifyPortalContent,
94        allowed_types=('Document','Activity',),
95        widget = ReferenceBrowserWidget(
96            allow_search = True,
97            allow_browse = True,
98            show_indexes = False,
99            force_close_on_insert = True,
100            startup_directory = "methods",
101            size = 4,
102            i18n_domain = "lemill",
103            label = "Related Methods",
104            label_msgid = "label_related_methods",
105            description = "",
106            description_msgid = "help_story_related_methods",
107            visible = {'edit' : 'invisible', 'view' : 'invisible' }
108            )
109        ),
110    ReferenceField('relatedTools',
111        relationship = 'relatesToTools',
112        multiValued = True,
113        isMetadata = True,
114        languageIndependent = False,
115        index = 'KeywordIndex',
116        write_permission = ModifyPortalContent,
117        allowed_types=('Document','Tool',),
118        widget = ReferenceBrowserWidget(
119            allow_search = True,
120            allow_browse = True,
121            show_indexes = False,
122            force_close_on_insert = True,
123            startup_directory = "tools",
124            size = 4,
125
126            i18n_domain = "lemill",
127            label = "Related Tools",
128            label_msgid = "label_related_tools",
129            description = "",
130            description_msgid = "help_story_related_tools",
131            visible = {'edit' : 'invisible', 'view' : 'invisible' }
132            )
133        ),
134    ComputedField('goodStory',
135        index = 'FieldIndex',
136        expression = 'here.isThisGoodStory()',
137        isMetadata = True
138        )
139))
140
141schema = schema.copy()
142
143class Collection(Resource):
144    """Collection"""
145   
146    schema = schema
147    actions= (
148    {
149    'id':'view',
150    'name':'view',
151    'action':'string:${object_url}/collection_view',
152    'permission':('View',),
153    },
154    {
155    'id':'edit',
156    'name':'Edit',
157    'action':'string:${object_url}/base_edit',
158    'permission':('View',),
159    },
160    )
161    meta_type = "Collection"
162    archetype_name = "Collection" 
163    typeDescription="Collection of resources."
164    typeDescMsgId='description_collection'
165    global_allow = 1
166    security = ClassSecurityInfo()
167    _at_rename_after_creation = True
168
169    def at_post_create_script(self):
170        self.at_post_edit_script()
171
172    def at_post_edit_script(self):
173        self._renameAfterCreation()
174        self.setGoodStory()
175
176    def after_add_rename(self):
177        self._renameAfterCreation()
178       
179    def setGoodStory(self):
180        """ Update goodStory -flag """
181        # after trying to get field and then setting the field by recalculating self.isThisGoodStory()
182        # it appears to be *always* up-to-date. (field.get()==self.isThisGoodStory())
183        # so the problem is indexing.
184        self.reindexObject()
185               
186#        field = self.getField('goodStory')
187#        wasgood=field.get(self)
188#        isgood= self.isThisGoodStory()
189#        print 'setting story %s. wasgood:%s isgood:%s' % (self.getId(), wasgood, isgood)
190#        ct = getToolByName(self,'portal_catalog')
191#        print ct({'getGoodStory':True})
192#        self.reindexObject()
193#        print ct({'getGoodStory':True})
194#        if wasgood!=isgood:
195#            field.set(self, isgood)
196#            self.reindexObject()
197#            ct = self.getToolByName('portal_catalog')
198           
199
200    def getLargestCount(self, reftype='relatedContent'):
201        field = self.Schema().get(reftype)
202        rtype=field.relationship
203        f = self.getReferenceImpl(relationship=rtype)
204
205        highest = 1001
206        for a in f:
207            try:
208                highest = a.collection_position
209            except AttributeError:
210                pass
211        highest += 100
212        return highest
213
214
215    security.declareProtected(MODIFY_CONTENT,'addRelatedContent')
216    def addRelatedContent(self, ref, empty=0):
217        """ add reference to content """
218        self.addRefsToResources(ref, empty, reftype="relatedContent")
219        self.setGoodStory()
220
221    security.declareProtected(MODIFY_CONTENT,'addRelatedMethods')
222    def addRelatedMethods(self, ref, empty=0):
223        """ add reference to methods """
224        self.addRefsToResources(ref, empty, reftype="relatedMethods")
225        self.setGoodStory()
226
227    security.declareProtected(MODIFY_CONTENT,'addRelatedTools')
228    def addRelatedTools(self, ref, empty=0):
229        """ add reference to tools """
230        self.addRefsToResources(ref, empty, reftype="relatedTools")
231        self.setGoodStory()
232
233    security.declareProtected(MODIFY_CONTENT,'addRefsToResources')
234    def addRefsToResources(self, ref, empty=0, reftype=None):
235        """ add reference to resource """
236        from types import ListType, TupleType
237        if reftype:
238            field = self.Schema().get(reftype)
239        else:
240            if type(ref) == ListType or type(ref) == TupleType:
241                for x in ref: # if entry is a list of mixed type entries, run this method again for each component.
242                    self.addRefsToResources(x)
243                return 1
244            uc=getToolByName(self, 'uid_catalog')
245            obj=uc(UID=ref)
246            objtype=obj[0].portal_type
247            if objtype in CONTENT_TYPES:
248                reftype='relatedContent'
249            elif objtype in ACTIVITY_TYPES:
250                reftype='relatedMethods'
251            elif objtype in TOOLS_TYPES:
252                reftype='relatedTools'
253            else:
254                reftype='refsToResources'
255            field = self.Schema().get(reftype)
256
257        prev = field.getRaw(self)
258        new_value = []
259        if type(ref) == ListType or type(ref) == TupleType:
260            new_value = prev
261            if empty:
262                new_value = []
263            for x in ref:
264                new_value.append(x)
265        else:
266            new_value = prev+[ref,]
267        field.set(self, new_value, collection_position=self.getLargestCount(reftype))
268        self.setGoodStory()
269
270    def isThisGoodStory(self):
271        """ Check if there is content,method,tool and description """       
272        desc=self.Description()
273        c=self.getRelatedContent()
274        m=self.getRelatedMethods()
275        t=self.getRelatedTools()
276        wtool=getToolByName(self, 'portal_workflow')
277        r= wtool.getInfoFor(self,'review_state',None)!='deleted'
278        if desc and c and m and t and r:
279            return True
280        else:
281            return False
282
283    def getItemCount(self):
284        """ return how many items are in collection """
285        return len(self.getRelatedMethods())+len(self.getRelatedTools())+len(self.getRelatedContent())
286
287
288    def getRelatedContent(self):
289        """ make sure that related content comes in correct order even when programmer forgets to ask for it"""
290        return self.getResources()
291
292    def getSortedList(self, reftype='relatedContent'):
293        #f = self.getField('refsToResources')
294        field = self.Schema().get(reftype)
295        rtype=field.relationship
296        f = self.getReferenceImpl(relationship=rtype)
297        arr = []
298        err_base = 12345123
299        for a in f:
300            try:
301                i = a.collection_position
302            except AttributeError:
303                i = err_base + 100
304                a.collection_position = i
305            arr.append([i, a])
306        arr.sort()
307        return arr
308
309    def getBlurp(self):
310        """ Some 1000 chars or something FIXME TO FIND NICE PLACES TO CUT (<p><br> etc.)"""
311        lt = getToolByName(self, 'lemill_tool')
312        return lt.split_at_p_or_br(lt.shorten_link_names(lt.htmlify(self.Description())))
313
314    def getResources(self, reftype='relatedContent'):
315        """ ... """
316        #return self.getRefsToResources()
317        sorted = self.getSortedList(reftype)
318        arr = []
319        for x in sorted:
320            arr.append(x[1].getTargetObject())
321        # Only Tools and Methods should get sorted by name
322        if reftype != 'relatedContent':
323            mod_resources = [(x.Title(), x) for x in arr]
324            mod_resources.sort()
325            arr = [x[1] for x in mod_resources]
326        return arr
327
328
329    security.declareProtected(MODIFY_CONTENT,'delContent')
330    def delContent(self, objid,REQUEST=None):
331        """ front for delResources """
332        if objid:
333            self.delResources(objid, reftype='relatedContent')
334        if REQUEST:
335            return REQUEST.RESPONSE.redirect(self.absolute_url() + "/collection_edit")
336
337    security.declareProtected(MODIFY_CONTENT,'delMethods')
338    def delMethods(self, objid,REQUEST=None):
339        """ front for delResources """
340        if objid:
341            self.delResources(objid, reftype='relatedMethods')
342        if REQUEST:
343            return REQUEST.RESPONSE.redirect(self.absolute_url() + "/collection_edit")
344
345    security.declareProtected(MODIFY_CONTENT,'delTools')
346    def delTools(self, objid,REQUEST=None):
347        """ front for delResources """
348        if objid:
349            self.delResources(objid, reftype='relatedTools')
350        if REQUEST:
351            return REQUEST.RESPONSE.redirect(self.absolute_url() + "/collection_edit")
352
353    security.declareProtected(MODIFY_CONTENT,'delResources')
354    def delResources(self, objid, reftype='relatedContent'):
355        """ delete selected resource """
356        field = self.Schema().get(reftype)
357        objlist = field.get(self)
358
359        newlist = [o.UID() for o in objlist if o.id!=objid]
360        field.set(self, newlist)
361        # if collection is empty, delete it too
362#        if new == []:
363#            self.collections.delCollection(self.getId())
364#            return True
365#        else:
366#            return False
367        self.setGoodStory()
368        return False
369
370    def getCollectionContent(self):
371        """ Returns a list of content, methods and tools, ordered by their modification date """
372        objects=self.getRelatedContent()+self.getRelatedMethods()+self.getRelatedTools()
373        objects = [(x.ModificationDate(), x) for x in objects]
374        objects.sort()
375        return [x[1] for x in objects]
376       
377
378
379    security.declareProtected(MODIFY_CONTENT,'moveUpContent')
380    def moveUpContent(self, objid,REQUEST=None):
381        """ Front for more general moveUpResources """
382        if objid:
383            self.moveUpResources(objid, reftype='relatedContent')
384        return REQUEST.RESPONSE.redirect(self.absolute_url() + "/collection_edit")
385
386    security.declareProtected(MODIFY_CONTENT,'moveUpResources')
387    def moveUpResources(self, objid, reftype='relatedContent'):
388        """ move up """
389        field = self.getField(reftype)
390        sorted = self.getSortedList(reftype)
391        cur_pos = 0
392        count = 0
393        for x in sorted:
394            if x[1].getTargetObject().id == objid:
395                cur_pos = count
396                break
397            count += 1
398        if cur_pos > 0:
399            prev_uid = sorted[cur_pos-1][1].getTargetObject().UID()
400            prev_pos = sorted[cur_pos-1][1].collection_position
401            curr_uid = sorted[cur_pos][1].getTargetObject().UID()
402            curr_pos = sorted[cur_pos][1].collection_position
403
404            sorted.remove(sorted[cur_pos])
405            sorted.remove(sorted[cur_pos-1])
406            new_list = []
407            [ new_list.append(x[1].getTargetObject()) for x in sorted ]
408           
409            field.set(self, new_list)
410            new_list.append(curr_uid)
411            field.set(self, new_list, collection_position=prev_pos)
412            new_list.append(prev_uid)
413            field.set(self, new_list, collection_position=curr_pos)
414            #new_list = []
415            #for x in sorted:
416            #    new_list.append(x[1].getTargetObject())
417            #field.set(self, new_list)
418
419
420    security.declareProtected(MODIFY_CONTENT,'moveDownContent')
421    def moveDownContent(self, objid,REQUEST=None):
422        """ Front for more general moveDownResources """
423        if objid:
424            self.moveDownResources(objid, reftype='relatedContent')
425        return REQUEST.RESPONSE.redirect(self.absolute_url() + "/collection_edit")
426
427
428    security.declareProtected(MODIFY_CONTENT,'moveDownResources')
429    def moveDownResources(self, objid, reftype='relatedContent'):
430        """ move down """
431        field = self.getField(reftype)
432        sorted = self.getSortedList(reftype=reftype)
433        cur_pos = 0
434        count = 0
435        for x in sorted:
436            if x[1].getTargetObject().id == objid:
437                cur_pos = count
438                break
439            count += 1
440        if cur_pos+1 < len(sorted):
441            next_uid = sorted[cur_pos+1][1].getTargetObject().UID()
442            next_pos = sorted[cur_pos+1][1].collection_position
443            curr_uid = sorted[cur_pos][1].getTargetObject().UID()
444            curr_pos = sorted[cur_pos][1].collection_position
445
446            sorted.remove(sorted[cur_pos+1])
447            sorted.remove(sorted[cur_pos])
448            new_list = []
449            [ new_list.append(x[1].getTargetObject()) for x in sorted ]
450           
451            field.set(self, new_list)
452            new_list.append(curr_uid)
453            field.set(self, new_list, collection_position=next_pos)
454            new_list.append(next_uid)
455            field.set(self, new_list, collection_position=curr_pos)
456
457    def amIOwner(self):
458        """ check owner of object """
459        roles = self.portal_membership.getAuthenticatedMember().getRolesInContext(self)
460        return 'Owner' in roles
461
462
463    def manage_afterAdd(self, item, container):
464        #Replaces the left side portlets with the content type's own action portlet.
465        BaseContent.manage_afterAdd(self, item, container)
466        if not hasattr(item.aq_base, 'left_slots'):
467            self._setProperty('left_slots', ['here/portlet_%s_actions/macros/portlet' % item.meta_type.lower(),], 'lines')
468
469    security.declareProtected(MODIFY_CONTENT,'cleanRefsToResources')
470    def cleanRefsToResources(self):
471        """ Check if (deprecated) RefsToResources contains stuff that should be in relatedContent etc. """
472        if not self.Schema().get('relatedContent'): # update schema if old type collection
473            #print 'schema update required for %s' % self.getId()
474            self._updateSchema()
475        objlist=self.getRefsToResources()
476        field=self.getField('refsToResources')
477        newlist=[]
478        for o in objlist:
479            objtype=o.meta_type
480            if objtype in CONTENT_TYPES:
481                reftype='relatedContent'
482            elif objtype in ACTIVITY_TYPES:
483                reftype='relatedMethods'
484            elif objtype in TOOLS_TYPES:
485                reftype='relatedTools'
486            else:
487                reftype='keeper'
488
489            if reftype=='keeper':
490                newlist.append(o.UID())
491            else:
492                self.addRefsToResources(o.UID(),reftype=reftype)
493        field.set(self, newlist)
494
495    def getLearningStoryText(self):
496        """ will return the nice version for the story text """
497        lt = getToolByName(self, 'lemill_tool')
498        return lt.shorten_link_names(lt.htmlify(self.Description()))
499
500    def _buildZIP(self):
501        print '-------------- _buildZIP -------------'
502
503        def do_stuff(html, cache):  # change src urls, download and put them in zip
504            # get and remove base url from html
505            split_html = sre.split('(<base href=")(.*?)(".*?/>)', html)
506            base = split_html[2]
507            del split_html[1:4]
508            html = ''.join(split_html)
509
510            split_html = sre.split('(<[^>]+)src="(.*?)"', html)
511
512            srcs = {}
513            newnames = {}
514            src_urls = split_html[2::3]
515            for url in src_urls:
516                if not srcs.has_key(url):
517                    if cache.has_key(url):
518                        filename, content = cache[url]
519                        srcs[url] = (filename, content)
520                        print 'From cache:', url
521                    else:
522                        xurl = url
523                        try:
524                            if not url.startswith('http://'):
525                                xurl = base + '/' + url
526                            src = urlopen(xurl)
527                            print xurl
528                            media_type, subtype = src.headers.getheader('Content-Type').split('/')
529                            if media_type == 'image':
530                                tmp_url = src.url
531                                if src.url.startswith(self.portal_url()):
532                                    for s in ('/coverImage', '/image_large'):
533                                        i = src.url.find(s)
534                                        if i != -1:
535                                            tmp_url = list(src.url)
536                                            tmp_url[i] = '_'
537                                            tmp_url = ''.join(tmp_url[:i + len(s)])
538                                            break
539                                basename = tmp_url.split('/')[-1].rsplit('.', 1)[0]
540                                filename = '%s.%s' % (basename, subtype.split(';', 1)[0])
541                                newnames[filename] = newnames.get(filename, 0) + 1
542                                if newnames[filename] > 1:
543                                    filename = '%s-%d.%s' % (basename, newnames[filename] - 1, subtype)
544                            else:
545                                filename = src.url.split('/')[-1]
546                            url_content = src.read()
547                            srcs[url] = (filename, url_content)
548                            cache[url] = (filename, url_content)
549                        except HTTPError, e:
550                            print "Failed to download %s: %s" % (xurl, e)
551
552            return srcs, split_html
553
554        zipcontent = []
555
556        main_dir = self.getId()
557        url_cache = {}
558        zipcontent.append((main_dir, do_stuff(self.standalone_view(), url_cache)))
559        for content in self.getResources(reftype='relatedContent'):
560            zipcontent.append(('%s/content/%s' % (main_dir, content.getId()), do_stuff(content.standalone_view(), url_cache)))
561
562        for method in self.getResources(reftype='relatedMethods'):
563            zipcontent.append(('%s/methods/%s' % (main_dir, method.getId()), do_stuff(method.standalone_view(), url_cache)))
564
565        for tool in self.getResources(reftype='relatedTools'):
566            zipcontent.append(('%s/tools/%s' % (main_dir, tool.getId()), do_stuff(tool.standalone_view(), url_cache)))
567
568        file_ref_count = {}
569        for dir_, (srcs, split_html) in zipcontent:
570            for url in srcs.iterkeys():
571                file_ref_count[url] = file_ref_count.get(url, 0) + 1
572
573        s = StringIO()
574        zf = zipfile.ZipFile(s, 'w', compression=zipfile.ZIP_DEFLATED)
575
576        common_urls = [key for key, val in file_ref_count.iteritems() if val > 1]
577        for dir_, (srcs, split_html) in zipcontent:
578            for url, (newname, content) in srcs.items():
579                if url in common_urls:
580                    srcs[url] = ('%s/common_files/%s' % (main_dir, newname), content)
581                else:
582                    srcs[url] = ('%s/%s' % (dir_, newname), content)
583
584            def calc_url(link):
585                url = srcs.get(link, (link,))[0]
586                depth = dir_.count('/')
587                return "../" * depth + url.split('/', 1)[1]
588
589            new_html_l = ['%s%ssrc="%s"' % (stuff, tag, calc_url(link)) for stuff, tag, link in zip(split_html[::3], split_html[1::3], split_html[2::3])]
590            new_html_l.append(split_html[-1])
591            zf.writestr(dir_ + '/index.html', ''.join(new_html_l))
592
593        in_zip = {}
594        for dir_, (srcs, split_html) in zipcontent:
595            for url, (newname, content) in srcs.items():
596                if not in_zip.has_key(newname):
597                    in_zip[newname] = content
598                    zf.writestr(newname, content)
599                else:
600                    assert in_zip[newname] == content
601
602        print '-------------- _buildZIP done ------------'
603        return s, zf
604
605    def getZIP(self):
606        s, zf = self._buildZIP()
607        zf.close()
608        response = self.REQUEST.RESPONSE
609        response.setHeader('Content-Type', 'application/zip')
610        response.setHeader('Content-Disposition', 'attachment; filename="%s.zip"' % self.getId())
611        return s.getvalue()
612
613    def getSCORM(self):
614        """ hguriehguirehgre """
615        s, zf = self._buildZIP()
616        zf.close()
617        response = self.REQUEST.RESPONSE
618        response.setHeader('Content-Type', 'application/zip')
619        response.setHeader('Content-Disposition', 'attachment; filename="%s.zip"' % self.getId())
620        return s.getvalue()
621
622    #XXX These additional meta-type='' and obj=None might not be needed, but I will leave them here just to be on the safe side.
623    def getDefaultIcon(self, meta_type='', obj=None):
624        """ Will return a portrait of the creator or his default icon """
625        owner = self.Creator()
626        mtool = getToolByName(self, 'portal_membership')
627        member_folder = mtool.getHomeFolder(owner)
628        given_image = member_folder.getCoverImageURL()
629        return given_image
630       
631
632registerType(Collection, PROJECTNAME)
633
634class CollectionsFolder(BaseFolder):
635    """ container for collection """
636    schema = BaseSchema
637    id = "collections"
638    meta_type = "CollectionsFolder"
639    archetype_name = "CollectionsFolder" 
640
641    actions= (
642    {
643    'id':'view',
644    'name':'view',
645    'action':'string:${object_url}/collections_list',
646    'permission':('View',),
647    },
648    )
649               
650registerType(CollectionsFolder, PROJECTNAME)
Note: See TracBrowser for help on using the repository browser.