source: trunk/Extensions/Install.py @ 1337

Revision 1337, 38.4 KB checked in by tarmo, 13 years ago (diff)

Fixed typo.

Line 
1# Copyright 2006 by the LeMill Team (see AUTHORS)
2#
3# This file is part of Calibrate LeMill.
4#
5# Calibrate 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# Calibrate 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 Calibrate LeMill; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
19"""Plone product installer script"""
20
21from Products.CMFCore.utils import getToolByName
22from Products.Archetypes.Extensions.utils import install_subskin, installTypes
23from Products.Archetypes.public import listTypes
24from Products.CMFPlone.migrations.migration_util import safeEditProperty
25
26
27from StringIO import StringIO
28import string
29from itertools import chain
30
31from Products.LeMill.config import *
32from Products.LeMill.Resources import Resource
33from Products.LeMill.SectionFolder import SectionFolder
34
35def install(self):
36        """Installs this Plone product. Called by the quick_installer tool."""
37        # HOOK: This is executed when the Plone site with LeMill customization
38        # is created, or when a reinstall for the LeMill product is called from
39        # quick_installer.
40       
41        out = StringIO()
42        # Don't install the skin layer here - the configuration methods setup a
43        # whole new skin for us.
44
45        # Check whether we're upgrading or not
46        qi=getToolByName(self, 'portal_quickinstaller')
47        p=qi._getOb(PROJECTNAME, None)
48        if p:
49                oldVersion=p.getInstalledVersion()
50        else:
51                oldVersion="0"
52        newVersion=qi.getProductVersion(PROJECTNAME)
53
54
55        print >>out,"Installing content archetypes..."
56        installTypes(self, out, listTypes(PROJECTNAME), PROJECTNAME)
57
58        print >>out,"Installing portal tools..."
59        if not hasattr(self, 'lemill_search'):
60                addTool = self.manage_addProduct[PROJECTNAME].manage_addTool
61                # Add the tool by its meta_type
62                addTool('LeMillSearch')
63        if not hasattr(self, 'lemill_tool'):
64                addTool = self.manage_addProduct[PROJECTNAME].manage_addTool
65                # Add the tool by its meta_type
66                addTool('LeMillTool')
67        if not hasattr(self, 'lemill_usertool'):
68                addTool = self.manage_addProduct[PROJECTNAME].manage_addTool
69                # Add the tool by its meta_type
70                addTool('LeMillUserTool')
71
72
73        print >>out,"Registering remote search preference panel..."
74        # Register lemill_search_conf under controlpanel.
75        # admins can register additional search locations there.
76        # ticket #107
77        cp = getToolByName( self, 'portal_controlpanel')
78        REMOTE_SEARCH_ID='lemill_remote_search'
79        cp.unregisterConfiglet(REMOTE_SEARCH_ID)
80        cp.addAction(REMOTE_SEARCH_ID,
81                'LeMill search',
82                'string:${portal_url}/prefs_lemill_search_form',
83                permission='Manage portal',
84                category='Products',
85                appId='LeMill')
86
87        # Call migration script
88        migrate(self,out,oldVersion,newVersion)
89
90        print >>out,"Installation completed."
91        # Done, return whatever messages we got
92        return out.getvalue()
93
94def migrate(self,out,old,new):
95        """Migrate existing content. If we're installing a newer version
96        of LeMill over an existing one, we may need to alter the existing
97        content so that it's compatible with the new version."""
98
99        # Note that versions are strings, not numbers.
100       
101        if not old: return
102        if new==old: return
103        if new<old:
104                print >>out,"Can't downgrade content from %s to %s!" % (old,new)
105                return
106
107        print >>out,"Migrating from %s to %s" % (old,new)
108
109        # NB: All setupXXX methods from ConfigurationMethods are executed when
110        # running a reinstall from quick_installer.
111
112        # Example iteration, changing all content objects
113        # Adapt this to change objects so they are compatible with the
114        # changes made into the system
115        if 1 == 0: # Let's not really run it...
116                for ob in self.content.objectValues(('Piece','Material')):
117                        ob.edit(title=ob.Title()+"!")
118
119        if old<"0.3":
120                print >>out, "Migration not supported for versions below 0.3"
121                return
122
123        # Add migration stuff here, in ascending order of version
124        # NOTE: If you make a syntax error here, portal_quickinstaller
125        # will just report LeMill as "removed from Products folder"
126        # (running "python Extensions/Install.py" will report syntax errors)
127        if old<="0.3":
128                print >>out, "Starting migration from 0.3..."
129                # Migrate from 0.3
130                # Member information is no longer stored in memberdata tool
131                # This is the old property list:
132                old=(
133                        ('firstname', 'string',''),
134                        ('lastname', 'string',''),
135                        ('fullname', 'string','hidden'),
136                        ('nickname', 'string',''),
137                        ('messenger1', 'string',''),
138                        ('messenger2', 'string',''),
139                        ('messenger3', 'string',''),
140                        ('home_page', 'string',''),
141                        ('location_country', 'string',''),
142                        ('location_area', 'string',''),
143                        ('language_skills', 'lines',''),
144                        ('skills', 'lines',''),
145                        ('interests', 'lines',''),
146                        ('tags', 'lines','hidden'),
147                        ('used_content', 'lines','hidden'),
148                        )
149                # This is the current list:
150                current = MEMBER_PROPERTIES
151                mdat_tool = getToolByName(self, 'portal_memberdata')
152                # Remove any properties not in the current list
153                deleteThese=[]
154                for prop in old:
155                        if not prop[0] in [x[0] for x in current]:
156                                deleteThese.append(prop[0])
157                print >>out,"Removing these obsolete member properties: %s" % ", ".join(deleteThese)
158                mdat_tool.manage_delProperties(deleteThese)
159                print >>out,"Migration from 0.3 complete."
160               
161        if old<="0.3.1":
162                # Migrate from 0.3.1
163                # Add initial history entry to all objects
164                print >>out,"Starting migration from 0.3.1..."
165                def initiateHistory(objs):
166                        for ob in objs:
167                                if not ob.getHistory():
168                                        ob.storeInHistory(fields=(),summary='History information started.',storeAuthor=False)
169                print >>out,"Adding initial history entry to learning resources..."
170                initiateHistory(self.content.objectValues(('Material',)))
171                initiateHistory(self.activities.objectValues(('Activity',)))
172                initiateHistory(self.tools.objectValues(('Tool',)))
173                print >>out,"Updating left slots and state..."
174                for ob in self.community.objectValues(('GroupBlog','MemberFolder')) + \
175                        self.activities.objectValues(('Activity',)) + \
176                        self.tools.objectValues(('Tool',)):
177                    ob.content_status_modify(workflow_action='publish', msg='silent')
178                    if not hasattr(ob.aq_base, 'left_slots'):
179                        ob._setProperty('left_slots', ['here/portlet_%s_actions/macros/portlet' % ob.meta_type.lower(),], 'lines')
180
181                print >>out,"Migration from 0.3.1 complete."
182        if old<="0.3.2":
183            # Migrate from 0.3.2
184            # move history from LearningResource class to Resource class
185            print >>out,"Starting migration from 0.3.2..."
186            def moveHistory(objs):
187                for obj in objs:
188                    if hasattr(obj, '_LearningResource__history'):
189                        setattr(obj, '_Resource__history', getattr(obj, '_LearningResource__history'))
190                        del obj._LearningResource__history
191                    if not obj.getHistory():
192                        obj.storeInHistory(fields=(),summary='History information started.',storeAuthor=False)
193            print >>out,"Moving history information to Resource class"
194            moveHistory(self.content.objectValues(('Material', 'Piece')))
195            moveHistory(self.activities.objectValues(('Activity',)))
196            moveHistory(self.tools.objectValues(('Tool',)))
197        if old<="0.4":
198            print >>out, "Starting migration from 0.4"
199            for x in self.content.objectValues(('Material', 'Piece')):
200                tags = x.getTags()
201                x.setTags(', '.join(tags))
202            print >>out, "Attaching license"
203            for x in self.content.objectValues(('Piece',)):
204                x.setRights('CreativeCommons')
205            print >>out, "Migration from 0.4 complete"
206        if old<='0.4.1':
207            print >>out, "Starting migration from 0.4.1"
208            groupdatatool=getToolByName(self,"portal_groupdata")
209            for prop in ['tags','email','scope']:
210                if groupdatatool.hasProperty(prop):
211                    groupdatatool.manage_delProperties([prop])
212                print >>out, "Migration from 0.4.1 complete"
213        if old<='0.4.2':
214                print >>out, "Starting migration from 0.4.2"
215                for group in self.community.objectValues(('GroupBlog',)):
216                    for post in group.objectValues(('BlogPost',)):
217                        if hasattr(post.aq_base, 'left_slots'):
218                            post._updateProperty('left_slots', ['here/portlet_groupblog_actions/macros/portlet',])
219                        else:
220                            post._setProperty('left_slots', ['here/portlet_groupblog_actions/macros/portlet',], 'lines')
221                print >>out, "Migration from 0.4.2 complete"
222        if old<='0.5':
223            print >>out, "Starting migration from 0.5"
224            print >>out, "Converting Material to other types"
225            rtool = getToolByName(self, 'reference_catalog')
226            wftool = getToolByName(self, 'portal_workflow')
227            wftool.setChainForPortalTypes(MATERIAL_TYPES+('GroupBlog',), 'group_workflow')
228            new_ids = []
229            for m in self.content.objectValues('Material'):
230                print "Object:", m.meta_type, m.getId()
231                m_meta_type = m.meta_type
232                m_review_state = wftool.getInfoFor(m, 'review_state')
233                #print "review state::", m_review_state
234                m_id = m.getId()
235                m_Title = m.Title()
236                m_schema = m.Schema()
237                m_owner = m.getOwnerTuple()
238                m_creators = m.getAuthors()
239                m_local_roles = m.get_local_roles()
240                old_uid = m.UID()
241                m_fields = m_schema.fields()
242                template_id = m.getTemplateId()
243                if not template_id:
244                    print >>out, "Deleting Material %s" % m_id
245                    self.content._delObject(m_id)
246                    continue
247               
248                # templates to handle: presentation, text-and-images, simple-tex
249                obj = None
250                if template_id in ['text-and-images', 'simple-text']:
251                    obj = self.content._lemill_invokeFactory(self.content, 'MultimediaMaterial', m_id+'c', m_Title)
252                elif template_id == 'presentation':
253                    obj = self.content._lemill_invokeFactory(self.content, 'PresentationMaterial', m_id+'c', m_Title)
254                o_schema = obj.Schema()
255                o_fields = o_schema.fields()
256
257                for f in m_fields:
258                    if f.getName() == 'id': continue
259                    m_accessor = f.getAccessor(m)
260                    if m_accessor is None: # field that was but now is removed from schema. eg. age_group
261                        continue
262                    target_f = obj.getField(f.getName())
263                    if target_f and f.getName() not in ['refsToImages', 'refsToSlides']:
264                        mutator = target_f.getMutator(obj)
265                        mutator(m_accessor())
266                    else:
267                        if f.getName() in ['parentVersion', 'file', 'source', 'audio', 'templateId']:
268                            continue
269                        if template_id == 'presentation':
270                            # refsToSlides
271                            target_f = obj.getField('refsToImages')
272                            mutator = target_f.getMutator(obj)
273                            mutator(m_accessor())
274                        elif template_id == 'text-and-images':
275                            # refsToImages
276                            target_f = obj.getField('bodyText')
277                            chap_nr = target_f.getFirstChapter(obj)
278                            value = m_accessor()
279                            vv = []
280                            for x in value:
281                                vv.append(x.UID())
282                            target_f.setPieces(obj, ';'.join(vv), chap_nr)
283                    #print f.getName(), m_accessor(), obj.getField(f.getName())
284                # bodyText mutator appends modifying user to creators, so revert creators back to its old state
285                t_creators=obj.getField('creators')
286                t_creators.set(obj,m_creators) 
287       
288                new_ids.append([m_id, obj.getId()])
289                new_uid = obj.UID()
290                # get and change references to old uid
291                for r in rtool.getBackReferences(m):
292                    s = r.getSourceObject()
293                    if s.meta_type == 'Collection':
294                        old_uid_value = s.getRefsToResources()
295                        new_uid_value = []
296                        for o in old_uid_value:
297                            if o.UID() == old_uid:
298                                new_uid_value.append(new_uid)
299                            else:
300                                new_uid_value.append(o.UID())
301                        s.addRefsToResources(new_uid_value, empty=1)
302                    if s.meta_type == 'Story':
303                        fi = s.getField('relatedContent')
304                        acc = fi.getAccessor(s)
305                        mut = fi.getMutator(s)
306                        old_uid_value = acc()
307                        new_uid_value = []
308                        for o in old_uid_value:
309                            if o.UID() == old_uid:
310                                new_uid_value.append(new_uid)
311                            else:
312                                new_uid_value.append(o.UID())
313                        mut(new_uid_value)
314                # giving object back to user
315                acl_obj = self
316                acl_user = None
317                while 1:
318                    if hasattr(acl_obj, 'acl_users'):
319                        if acl_obj.acl_users.getUser(m_owner[1]):
320                           acl_user = acl_obj.acl_users.getUser(m_owner[1])
321                           break
322                    try:
323                        acl_obj = acl_obj.aq_parent
324                    except AttributeError:
325                        break
326                obj.changeOwnership(acl_user.__of__(self.acl_users))
327                for del_role in obj.get_local_roles():
328                    obj.manage_delLocalRoles((del_role[0],))
329                for user_role in m_local_roles:
330                    obj.manage_setLocalRoles(user_role[0], user_role[1])
331                rev_state = wftool.getInfoFor(obj, 'review_state')
332                if rev_state != m_review_state and m_review_state != 'draft':
333                    #print rev_state, m_review_state
334                    if m_review_state == 'hidden':
335                        wftool.doActionFor(obj, 'hide')
336                    if m_review_state == 'public':
337                        wftool.doActionFor(obj, 'publish')
338                # delete material
339                self.content._delObject(m_id)
340        if old<='0.6':
341            print >>out, "Migrating coverImages"
342            for x in self.content.objectValues(CONTENT_TYPES):
343                if x.meta_type == 'Piece':
344                    c = x.getCoverImage()
345                    embedded = x.embedIcon(c)
346                    coverImage = x.getField('coverImage')
347                    coverImage.set(x, embedded)
348                else:
349                    x.updateCoverImage()
350            print >> out, "Moving slide captions"
351            for x in self.content.objectValues('PresentationMaterial'):
352                f = x.getField('slide_captions')
353                for p in x.getRefsToSlides():
354                    caption = p.getDescription()
355                    uid = p.UID()
356                    f.setValue(x, uid, caption)
357            print >> out, "Adding order for collections"
358            for m in self.community.objectValues('MemberFolder'):
359                for cf in m.objectValues('CollectionsFolder'):
360                    for c in cf.objectValues('Collection'):
361                        objs = c.getRefsToResources()
362                        f = c.getField('refsToResources')
363                        f.set(c, [])
364                        i = 1001
365                        prev = []
366                        for o in objs:
367                            prev.append(o)
368                            f.set(c, prev, collection_position=i)
369                            i += 100
370            print >>out, "Migration from 0.6 complete"
371        if old<='0.8.1':
372            for (oid,m) in self.content.objectItems('MultimediaMaterial'):
373                print >>out, "Converting %s/%s..." % (oid,m.getId())
374                print "Converting %s/%s..." % (oid,m.getId())
375                try:
376                    field = m.getField('bodyText')
377                except AttributeError:
378                    print >>out, "Deleting invalid object %s" % oid
379                    self.content._delObject(oid)
380                    continue
381                try:
382                    chaps = field.getChapters(m)
383                except TypeError:
384                    print >>out, "Deleting invalid object %s" % oid
385                    self.content._delObject(oid)
386                    continue
387                chaps.sort()
388                texts = {}
389                pieces = {}
390                for c in chaps:
391                    texts[c] = field.getChapter(m, c)
392                    pieces[c] = field.getPieces(m, c)
393                m.setBodyText("")
394                m._updateSchema()
395                field = m.getField('bodyText')
396                for c in chaps:
397                    text = texts[c]
398                    if text:
399                        index = field.add_new_chapter(m)
400                        field.setChapter(m,text,index)
401                    for uid in pieces[c]:
402                        if uid:
403                            index = field.add_new_mediapiece(m)
404                            field.setPieces(m,uid,index)
405            print >>out, "Migration from 0.8.1 complete"
406
407        if old<='0.9':
408            for (oid,m) in self.content.objectItems('PresentationMaterial'):
409                print >>out, "Converting %s/%s..." % (oid,m.getId())
410                print "Converting %s/%s..." % (oid,m.getId())
411                try:
412                    description = m.getField('bodyText')
413                    image_ref_field = m.getField('refsToImages')
414                    captions = m.getField('slide_captions')
415                except AttributeError:
416                    print >>out, "Deleting invalid object %s" % oid
417                    print "Deleting invalid object %s" % oid
418                    self.content._delObject(oid)
419                    continue
420                if image_ref_field==None and captions==None:
421                    print >>out, "This object is using current schema. Skip."
422                    continue
423                try:
424                    image_refs = m.getRefsToSlides()
425                except TypeError:
426                    print >>out, "Deleting invalid object %s" % oid
427                    print "Deleting invalid object %s" % oid
428                    self.content._delObject(oid)
429                    continue
430                new_slides =[]
431                for slideRef in image_refs:
432                    slideUID=slideRef.UID()
433                    slide_caption=m.getSlideCaptionFor(slideRef)
434                    new_slides=new_slides+[slideUID, slide_caption]
435                # Wish me luck.
436                m.setBodyText("")
437                m._updateSchema()
438                m.setBodyText(new_slides)
439                try:
440                    m.setDescription(str(description))
441                except:
442                    print >>out, "Setting description for %s failed, tried to give value %s" % (oid, description)
443                    print "Setting description for %s failed, tried to give value %s" % (oid, description)
444            print >>out, "Migration from 0.9 complete"
445
446        #if old<='1.0.3':
447        if old<='1.0.1':
448            print >>out, "Rebuilding cover images for all resource types (this will take time)"
449
450            print >>out, "*** MEMBERS"
451            for x in self.community.objectValues('MemberFolder'):
452                if not hasattr(x, 'getHasCoverImage'):
453                    print >>out, "skipped %s" % x.getId()
454                    continue
455                if x.getHasCoverImage()==False:
456                    print >>out, "skipped %s" % x.getId()
457                    continue
458                old=None
459                try:
460                    old=getattr(self.portal_memberdata.portraits, x.getId(), None)
461                except:
462                    print >>out, "Getting portrait failed for %s" % x.getId()
463                    x.flagCoverImageOff()
464                if old!=None:
465                    x.resize_portrait(old, x.getId())
466                    x.flagCoverImageOn()
467                    print >>out, "Portrait resized for %s" % x.getId()
468
469            print >>out, "*** MATERIALS"
470            for x in self.content.objectValues(MATERIAL_TYPES):
471                if not hasattr(x, 'getOriginalCoverImage'): continue
472                if not hasattr(x, 'getHasCoverImage'):
473                    print >>out, "skipped %s" % x.getId()
474                    continue
475                if x.getHasCoverImage()==False:
476                    print >>out, "skipped %s" % x.getId()
477                    continue
478                print >>out, "%s.. has coverimage %s" % (x.getId(), x.getHasCoverImage())               
479                org=None
480                old=None
481                if hasattr(x, 'originalCoverImage'): org=x.originalCoverImage
482                if hasattr(x, 'coverImage'): old=x.coverImage
483                if org != None:
484                    print >>out, "%s resets to OriginalCoverImage" % x.getId()
485                    x.setCoverImage(org)               
486                if org==None and old != None:
487                    print >>out, "%s has coverimage but no original." % x.getId()
488                    print >>out, "Set coverimage as original."
489                    x.setOriginalCoverImage(old)
490                    x.setCoverImage(old)
491                if org==None and old==None:
492                    x.delCoverImage()
493                    print >>out, "Turned off flag hasCoverImage for: %s" % x.getId()
494            print >>out, "*** PIECES"
495            for x in self.content.objectValues('Piece'):
496                if x.isImage():
497                    print >>out, "Setting image to coverimage for piece %s" % x.getId()
498                    cover=x.getField('coverImage')
499                    x.setCoverImage(x.file)
500                else:
501                    if x.getHasCoverImage()==True:
502                        print >>out, "Piece %s is not image" % x.getId()
503                        x.delCoverImage()
504
505            print >>out, "*** TOOLS"
506            for x in self.tools.objectValues(TOOLS_TYPES):
507                if not hasattr(x, 'getOriginalCoverImage'): continue
508                if not hasattr(x, 'getHasCoverImage'):
509                    print >>out, "skipped %s" % x.getId()
510                    continue
511                if x.getHasCoverImage()==False:
512                    print >>out, "skipped %s" % x.getId()
513                    continue
514                print >>out, "%s.. has coverimage %s" % (x.getId(), x.getHasCoverImage())               
515                org=None
516                old=None
517                if hasattr(x, 'originalCoverImage'): org=x.originalCoverImage
518                if hasattr(x, 'coverImage'): old=x.coverImage
519                if org != None:
520                    print >>out, "%s resets to OriginalCoverImage" % x.getId()
521                    x.setCoverImage(org)               
522                if org==None and old != None:
523                    print >>out, "%s has coverimage but no original." % x.getId()
524                    print >>out, "Set coverimage as original."
525                    x.setOriginalCoverImage(old)
526                    x.setCoverImage(old)
527                if org==None and old==None:
528                    x.delCoverImage()
529                    print >>out, "Turned off flag hasCoverImage for: %s" % x.getId()
530
531            print >>out, "*** ACTIVITIES"
532            for x in self.activities.objectValues(ACTIVITY_TYPES):
533                if not hasattr(x, 'getOriginalCoverImage'): continue
534                if not hasattr(x, 'getHasCoverImage'):
535                    print >>out, "skipped %s" % x.getId()
536                    continue
537                if x.getHasCoverImage()==False:
538                    print >>out, "skipped %s" % x.getId()
539                    continue
540                print >>out, "%s.. has coverimage %s" % (x.getId(), x.getHasCoverImage())               
541                org=None
542                old=None
543                if hasattr(x, 'originalCoverImage'): org=x.originalCoverImage
544                if hasattr(x, 'coverImage'): old=x.coverImage
545                if org != None:
546                    print >>out, "%s resets to OriginalCoverImage" % x.getId()
547                    x.setCoverImage(org)               
548                if org==None and old != None:
549                    print >>out, "%s has coverimage but no original." % x.getId()
550                    print >>out, "Set coverimage as original."
551                    x.setOriginalCoverImage(old)
552                    x.setCoverImage(old)
553                if org==None and old==None:
554                    x.delCoverImage()
555                    print >>out, "Turned off flag hasCoverImage for: %s" % x.getId()
556
557            print >>out, "Cover image fixes complete"
558#        if old<='1.1':      # moved to 1.2.3
559        if old<='1.12':
560            print >>out, "Starting migration from 1.12"
561            print >>out, "Renaming categories in existing groups and posts"
562            for group in self.community.objectValues('GroupBlog'):
563                gcats=list(group.getCategories())
564                change=0
565                if 'blog post' in gcats:
566                    gcats[gcats.index('blog post')]='General'
567                    change=1
568                if 'collaboration proposal' in gcats:
569                    gcats[gcats.index('collaboration proposal')]='Collaboration proposal'
570                    change=1
571                if change==1:
572                    group.setCategories(gcats)
573
574                for b in group.objectValues('BlogPost'):
575                    bcats=b.getCategory()
576                    if type(bcats)==str:
577                        change=0
578                        if bcats=='blog post':
579                            bcats='General'
580                            change=1
581                        if bcats=='collaboration proposal':
582                            bcats='Collaboration proposal'
583                            change=1
584                        if change==1:
585                            b.setCategory([bcats])                   
586                    else:   
587                        bcats=list(b.getCategory())
588                        change=0
589                        if 'blog post' in bcats:
590                            bcats[bcats.index('blog post')]='General'
591                            change=1
592                        if 'collaboration proposal' in bcats:
593                            bcats[bcats.index('collaboration proposal')]='Collaboration proposal'
594                            change=1
595                        if change==1:
596                            b.setCategory(bcats)
597
598            print >>out, "Migration from 1.12 complete"
599        if old<='1.2':
600            print >>out, "Starting migration from 1.2"
601            print >>out, "Moving tips to new location..."
602            for member in self.community.objectValues('MemberFolder'):
603                storyfolder = member.getStoriesFolder()
604                for story in member.objectValues('Story'):
605                    member._delObject(story.getId())
606                    storyfolder._setObject(story.getId(),story)
607            print >>out, "Migration from 1.2 complete"
608        if old<='1.2.1':
609            print >>out, "Starting migration from 1.2.1"
610            print >>out, "Syncing ownership and author information..."
611            for x in chain(self.content.objectValues(CONTENT_TYPES),
612                           self.community.objectValues(COMMUNITY_TYPES),
613                           self.tools.objectValues(TOOLS_TYPES),
614                           self.activities.objectValues(ACTIVITY_TYPES)):
615                if isinstance(x, Resource):
616                    oldOwner = str(x.getOwner())
617                    newOwner = x.getField('creators').get(x)[0]
618                    x.changeOwnership(getattr(self.community,newOwner))
619                    x.manage_delLocalRoles([oldOwner,])
620                    x.manage_addLocalRoles(newOwner, ['Owner',])
621            print >>out, "Migration from 1.2.1 complete"
622
623        if old<='1.2.2':
624            print >>out, "Starting migration from 1.2.2"
625            print >>out, "Fixing categories for groups..."
626            for x in self.community.objectValues('GroupBlog'):
627                if x.getField('categories').get(x)[0]=='general, collaboration proposal':
628                    print >>out, "fixing group %s" % x.getId()
629                    gcats=list(x.getField('categories').get(x))
630                    newcats=['General','Collaboration proposal']+gcats[1:]
631                    x.setCategories(newcats)
632        if old<='1.3':
633            print >>out, "Starting migration from 1.2.3"
634            for x in chain(self.content.objectValues(CONTENT_TYPES),
635                           self.community.objectValues(COMMUNITY_TYPES),
636                           self.tools.objectValues(TOOLS_TYPES),
637                           self.activities.objectValues(ACTIVITY_TYPES)):
638                if isinstance(x, Resource):
639                    print x.getId()
640                    x.recalculateAuthors()
641            print >>out, "Migration from 1.2.3 complete"
642        if old<='1.3.01':
643            for x in self.community.objectValues('MemberFolder'):
644                if not hasattr(x.aq_base, 'left_slots'):
645                    x._setProperty('left_slots', ['here/portlet_member/macros/portlet',], 'lines')
646                else:
647                    x._updateProperty('left_slots', ['here/portlet_member/macros/portlet',])
648        if old<='1.3.2':
649            print >>out, "Starting migration from 1.3.01"
650            for x in chain(self.content.objectValues(CONTENT_TYPES),
651                           self.community.objectValues(COMMUNITY_TYPES),
652                           self.tools.objectValues(TOOLS_TYPES),
653                           self.activities.objectValues(ACTIVITY_TYPES)):
654                if isinstance(x, Resource):
655                    x.migrate_history()
656            print >>out, "Migration from 1.3.01 complete"
657        if old<='1.3.4':
658            print >>out, "Starting migration to 1.3.4"
659            for x in chain(self.content.objectValues(CONTENT_TYPES),
660                           self.community.objectValues(COMMUNITY_TYPES),
661                           self.tools.objectValues(TOOLS_TYPES),
662                           self.activities.objectValues(ACTIVITY_TYPES)):
663                if isinstance(x, Resource):
664                    print x.getId()
665                    x.recalculateAuthors()
666            print >>out, "Migration to 1.3.4 complete"
667        if old<='1.4':
668            print >>out, "Starting migration to 1.4.1"
669            # delete unnecessary topics from users
670            for member in self.community.objectValues('MemberFolder'):
671                for x in member.objectValues('Topic'):
672                    member._delObject(x.getId())
673            print >>out, "Migration to 1.4.1 complete"
674        if old<='1.5.2':
675            print >>out, "Starting migration from 1.5.2"
676            k = getToolByName(self, 'kupu_library_tool')
677            tag_exclusions = k.html_exclusions[0]
678            if 'img' not in tag_exclusions[0]:
679                #(('center', 'span', 'tt', 'big', 'small', 'u', 's', 'strike', 'basefont', 'font', 'table', 'th', 'td', 'tbody', 'thead', 'tr', 'div'), ())
680                new_tag_exclusions = (('center', 'span', 'tt', 'big', 'small', 'u', 's', 'strike', 'basefont', 'font', 'table', 'th', 'td', 'tbody', 'thead', 'tr', 'div', 'img'), ())
681                k.html_exclusions[0] = new_tag_exclusions
682            print >>out, "Migration from 1.5.2 complete"
683        if old<='1.5.3':
684            print >>out, "Starting migration from 1.5.3"
685            for x in self.community.objectValues('MemberFolder'):
686                if x.getPortraitURL().endswith('/defaultUser.gif'):
687                    x.getField('hasCoverImage').set(x, False)
688            print >>out, "Migration from 1.5.3 complete"
689
690        print >>out,"Migration completed."
691
692        if old<='1.6.0':
693            print >>out, "Starting migration from 1.6"
694            print >>out, "Removing strange local role bug"
695            for x in self.content.objectValues(MATERIAL_TYPES):
696                keys= self.acl_users._getAllLocalRoles(x).keys()
697                for k in keys:
698                    if isinstance(k, tuple):
699                        print >>out, 'Faulty item: %s has key %s in local roles' % (x.getId(), k)
700                        x.manage_delLocalRoles((k,))               
701
702            print >>out, "Moving stuff from Folders to Large Folders, this will take a while"
703
704            for (folder_old, new_type) in [(self.content, 'LargeContentFolder'), (self.activities, 'LargeActivityFolder'), (self.tools, 'LargeToolFolder'), (self.community, 'LargeCommunityFolder')]:
705                if isinstance(folder_old, SectionFolder):
706                    folder_id=folder_old.getId()
707                    print >>out, "Cut-pasting objects from %s to Large version of folder" % folder_id
708                    self.manage_renameObject(folder_id,folder_id+'_old')
709                    self.invokeFactory(id=folder_id,type_name=new_type)
710                    folder_new= getattr(self, folder_id)
711                    try:
712                        folder_old._delObject('syndication_information')
713                    except:
714                        print >>out, 'no syndication_information here'
715                   
716                    ### Set new folder properties ###
717                    safeEditProperty(folder_new,
718                        key='left_slots',
719                        value=folder_old.left_slots,
720                        data_type='lines')
721                    folder_new.setTitle(folder_old.title)
722                    if folder_id=='community':               
723                        folder_new.setCollaboration_proposals(folder_old.getCollaboration_proposals())
724                    folder_new.manage_permission(ADD_CONTENT_PERMISSION, ('Member',), acquire=1)
725                    folder_new.manage_permission(LIST_FOLDER_CONTENTS, ('Member',), acquire=1)
726                    folder_new.manage_permission(ADD_TOPICS, ('Member',), acquire=1)
727                    ### End setting new folder properties ###               
728                   
729                    objects=[o.getId() for o in folder_old.objectValues()]
730                   
731                    cb=folder_old.manage_cutObjects(objects) ## CUT
732                    folder_new.manage_pasteObjects(cb) ## PASTE
733                   
734                    self._delObject(folder_old.getId()) ## DELETE FOLDER
735                else:
736                    print >>out, 'Section %s is already large folder' % folder_old.getId()
737            print >>out, "Migration from 1.6 complete"
738
739        if old<='1.6.1':
740            print >>out, "Starting migration from 1.6.1"
741            print >>out, "Owners for collections and stories"
742            # Create collections and stories folders for those users who do not have then yet
743            for member in self.community.objectValues('MemberFolder'):
744                if not hasattr(member.aq_base, 'collections'):
745                    member.invokeFactory('CollectionsFolder', id='collections')
746                if not hasattr(member.aq_base, 'stories'):
747                    member.invokeFactory('StoryFolder', id='stories')
748            # Check if collections and stories folders have correct Owner, if not then just change the owner to the right one
749            for member in self.community.objectValues('MemberFolder'):
750                member_id = member.users_with_local_role('Owner')
751                member_as_owner = member.getId()
752                if member_id != member.collections.users_with_local_role('Owner'):
753                    to_delete_owner_collections = str(member.collections.getOwner())
754                    member.collections.changeOwnership(getattr(member.collections,member_as_owner))
755                    member.collections.manage_delLocalRoles([to_delete_owner_collections,])
756                    member.collections.manage_addLocalRoles(member_as_owner, ['Owner',])
757                if member_id != member.stories.users_with_local_role('Owner'):
758                    to_delete_owner_stories = str(member.stories.getOwner())
759                    member.stories.changeOwnership(getattr(member.stories,member_as_owner))
760                    member.stories.manage_delLocalRoles([to_delete_owner_stories,])
761                    member.stories.manage_addLocalRoles(member_as_owner, ['Owner',])
762            print >>out, "Migration from 1.6.1 complete"           
763
764
765def uninstall(self):
766        """ uninstall """
767        out = StringIO()
768        # We don't have any way of uninstalling, at this point.
769        return out.getvalue()
770
Note: See TracBrowser for help on using the repository browser.