Changeset 1919 for trunk/GroupBlog.py


Ignore:
Timestamp:
08/08/07 01:48:48 (12 years ago)
Author:
jukka
Message:

Refactored groups to not use portal_groups. Things should be faster and users from weird sources shouldn't cause so much problems. Not much tested yet, but archetype update and quickinstaller reinstall works fine.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/GroupBlog.py

    r1876 r1919  
    4040 
    4141import time 
    42  
    43 monthNames = {'01':'month_jan', '02':'month_feb', '03':'month_mar', '04':'month_apr', '05':'month_may', '06':'month_jun', '07':'month_jul', '08':'month_aug', '09':'month_sep', '10':'month_oct', '11':'month_nov', '12':'month_dec'} 
    4442 
    4543# Same thing as with MemberFolder but easier: MemberBlogs contain the values of groups itself in indexable storage. 
     
    7977            ) 
    8078        ), 
    81     LinesField('recent_activity', 
    82         default= [], 
     79    LinesField('groupMembers', 
     80        default=[], 
     81        index = 'KeywordIndex:schema', 
    8382        widget = LinesWidget( 
    8483            visible = {'view':'invisible', 'edit':'invisible'}, 
     
    8685        ), 
    8786 
    88     LinesField('moderators', 
    89         default = [], 
    90         vocabulary = 'getMembersList', 
    91         widget = PicklistWidget(             
    92              label = 'Moderators', 
    93              label_msgid = 'label_group_moderators', 
    94              description = "Trusted members of group can help you to remove offensive posts and keep the group together.", 
    95              description_msgid = 'help_group_moderators', 
    96              i18n_domain = "lemill", 
    97              visible = {'view':'invisible', 'edit':'visible'}, 
    98              ) 
    99         ),         
    100  
    101  
    102     TagsField('banned', 
    103         default=[], 
    104         widget = TagsWidget( 
    105             label = 'Ban members', 
    106             label_msgid = 'label_ban_members', 
    107             description = "If someone repeatedly offends against group, group founder can ban him and prevent from joining the group again. Separate user id's with commas. User id's can be found by going to offending members member page and noticing the address in the browser. Id is the last part of address, after /community/.", 
    108             descriptio_msgid = 'help_ban_members', 
    109             i18n_domain = "lemill", 
    110             visible = {'view':'invisible', 'edit':'invisible'}, 
    111             ), 
    112         ), 
    113 )) 
     87 )) 
    11488 
    11589schema = schema.copy() 
     
    175149        mtool = getToolByName(self, 'portal_membership') 
    176150        memberfolder=mtool.getHomeFolder() 
    177         me = mtool.getAuthenticatedMember() 
    178151        if memberfolder!=None and type(memberfolder)=='MemberFolder': 
    179             memberfolder.note_action(item.UID(), item.portal_type, 'afterAdd') 
    180         self.content_status_modify(workflow_action='publish', msg='silent') 
     152            memberfolder.recalculateScore() 
    181153        if not hasattr(item.aq_base, 'left_slots'): 
    182154            self._setProperty('left_slots', ['here/portlet_%s_actions/macros/portlet' % item.meta_type.lower(),], 'lines') 
     
    193165    def at_post_edit_script(self): 
    194166        mtool = getToolByName(self, 'portal_membership') 
    195         ltool = getToolByName(self, 'lemill_tool') 
    196167        memberfolder=mtool.getHomeFolder() 
    197168        if memberfolder!=None: 
    198169            memberfolder.note_action(self.UID(), self.portal_type, 'post_edit') 
    199  
    200170        self.recalculateScore() 
    201         if hasattr(ltool,'allow_banning'): 
    202             if ltool.allow_banning: 
    203                 if self.getField('banned').widget.visible['edit']!='visible': 
    204                     self.getField('banned').widget.visible['edit']='visible' 
    205             else: 
    206                 if self.getField('banned').widget.visible['edit']!='invisible': 
    207                     self.getField('banned').widget.visible['edit']='invisible' 
    208  
    209  
    210     def setMeAsOwner(self): 
    211         mtool = getToolByName(self, 'portal_membership') 
    212         me = mtool.getAuthenticatedMember() 
    213         if [self.getId()] == self.users_with_local_role('Owner'): 
    214             self.manage_setLocalRoles(me.getId(), ['Owner']) 
    215             self.manage_addLocalRoles(me.getId(), ['Reviewer']) 
    216             #print self.users_with_local_role('Owner') 
    217171             
    218  
    219172    def getGroupMaterials(self, n=False): 
    220         """ Get resources used by group, uses portfolio-topic """ 
    221         results=self.portfolio.queryCatalog(getGroupsShared=self.getId())  
     173        """ Get resources edited by this group """ 
     174        pc=getToolByName(self, 'portal_catalog')         
     175        results=pc({'getRawGroupEditing':self.UID()}) 
    222176        if n: 
    223177            return len(results) 
    224         return results 
     178        else: 
     179            return results 
     180 
     181    def getGroupMembersNamesAndUrls(self): 
     182        memberids= self.getGroupMembers() 
     183        reslist=[] 
     184        for mid in memberids: 
     185            memberfolder=self.getMemberFolderById(mid) 
     186            if memberfolder: 
     187                reslist.append((memberfolder.NiceName(), memberfolder.absolute_url())) 
     188        return reslist 
    225189 
    226190    def getLatestEditDate(self): 
     
    230194    def getSamples(self): 
    231195        """ get n number of samples """ 
    232         q = {'review_state':'public', 'meta_type': self.getFeaturedTypes(), 'getHasCoverImage':True, 'getGroupsShared': self.getId()} 
    233         all = self.portfolio.queryCatalog(q) 
     196        all = self.getGroupMaterials() 
     197        all = [a for a in all if a.review_state=='public' and a.portal_type in self.getFeaturedTypes() and a.getHasCoverImage==True]  
    234198        import random 
    235199        n = min(3, len(all)) 
    236200        return random.sample(all,n) 
    237  
    238  
    239  
    240     def prefill_title(self): 
    241         # When GroupBlog is created we need to get same values as group itself here 
    242         # It seems that the marching order in creating a group sets these to 'x:s workspace' after creating object. 
    243         groupid = self.getId() 
    244         grouptool = getToolByName(self, 'portal_groups') 
    245         group=grouptool.getGroupById(groupid) 
    246         value= group.getTitle() 
    247         return value 
    248  
    249     def prefill_description(self): 
    250         # When GroupBlog is created we need to get same values as group itself here 
    251         groupid = self.getId() 
    252         grouptool = getToolByName(self, 'portal_groups') 
    253         group=grouptool.getGroupById(groupid) 
    254         value= group.getDescription() 
    255         return value 
    256201 
    257202    def getCoverImageURL(self, drafts=False): 
     
    262207        return 'images/default_group.png'  
    263208         
    264     def amIOwner(self): 
    265         """ check owner of object """ 
    266         roles = self.portal_membership.getAuthenticatedMember().getRolesInContext(self) 
    267         return 'Owner' in roles 
    268  
    269209    def isPost(self): 
    270         return False 
    271  
    272     def getMembersList(self, no_self=True): 
    273         groupid = self.getId() 
    274         grouptool = getToolByName(self, 'portal_groups') 
    275         usertool = getToolByName(self, 'lemill_usertool') 
    276         group=grouptool.getGroupById(groupid) 
    277         if no_self: 
    278             dll = [usertool.getLeMillMemberFolder(y.getId()) for y in group.getGroupMembers() if y.getId()!=self.Creator()] 
    279         else: 
    280             dll = [usertool.getLeMillMemberFolder(y.getId()) for y in group.getGroupMembers()] 
    281         dl = [(x.getId(), x.NiceName()) for x in dll] 
    282         return DisplayList(dl) 
    283  
    284     def getGroupMembers(self): 
    285         """ Public access to memberlist, returns tuple where (nicename, role, url) """ 
    286         groupid = self.getId() 
    287         grouptool = getToolByName(self, 'portal_groups') 
    288         usertool = getToolByName(self, 'lemill_usertool') 
    289         group=grouptool.getGroupById(groupid) 
    290         if group: 
    291             dll = [usertool.getLeMillMemberFolder(y.getId()) for y in group.getGroupMembers()] 
    292             return [(x.NiceName(), self.get_local_roles_for_userid(x.getId()),x.absolute_url()) for x in dll if dll] 
    293             return [] 
    294         else: 
    295             return [] 
    296          
     210        return False         
    297211         
    298212    def NiceName(self): 
     
    305219 
    306220    def isMember(self, memberid): 
    307         groupid = self.getId() 
    308         grouptool = getToolByName(self, 'portal_groups') 
    309         group=grouptool.getGroupById(groupid) 
    310         return memberid in [x.getId() for x in group.getGroupMembers()] 
    311  
     221        return memberid in self.getGroupMembers() 
    312222 
    313223    def canIModerate(self): 
    314         roles = self.getRoles() 
     224        roles = self.portal_membership.getAuthenticatedMember().getRolesInContext(self) 
    315225        return 'Manager' in roles or 'Reviewer' in roles 
    316  
    317  
    318     def getRoles(self, memberid=None): 
    319         # Helper method to get roles 
    320         if memberid: 
    321             return self.get_local_roles_for_userid(memberid) 
    322         else: 
    323             mtool = getToolByName(self, 'portal_membership') 
    324             user = mtool.getAuthenticatedMember()         
    325             return self.get_local_roles_for_userid(user.getId()) 
    326226         
    327227    def getPosts(self, batch=True, b_size=30, b_start=0): 
     
    354254    def getBlog(self): 
    355255        return self 
    356  
    357     def getRecent_activity(self): 
    358         """ Because I prefer lists, not tuples """ 
    359         return list(self.getField('recent_activity').get(self)) 
    360  
    361     security.declareProtected(MODIFY_CONTENT,'addRecent_activity') 
    362     def addRecent_activity(self, obj_uid, act_type): 
    363         """ Recent activity is a list of (obj_UID, date, activity type {'modified piece', 'created' etc.}) 
    364          that tracks member activities for all kinds of calculations """ 
    365  
    366         current_date = DateTime() 
    367         acts= self.getRecent_activity() 
    368         acts=[(obj_uid,current_date,act_type)]+acts 
    369         # pop out old collaboration proposals from tail of the list 
    370         while acts[-1][1] < (current_date-31): 
    371             acts.pop() 
    372         acts_field=self.getField('recent_activity') 
    373         acts_field.set(self, acts) 
    374256         
    375257    security.declareProtected(MODIFY_CONTENT,'addRecent_post') 
     
    398280        self.setRecent_posts(postlist)             
    399281 
    400     def do_joining(self, userid, groupid): 
    401         try: 
    402             self.acl_users.source_groups.addPrincipalToGroup(userid, groupid) 
    403         except: 
    404             return 1 
    405         return 0 
    406  
    407          
    408     def do_leaving(self, userid, groupid): 
    409         try: 
    410             self.acl_users.source_groups.removePrincipalFromGroup(userid, groupid) 
    411             if len(self.getGroupMembers()) <= 0: 
    412                 for x in self.getGroupMaterials(): 
    413                     x.getObject().setGroupsShared('no_group') 
    414                 groupTool = getToolByName(self, 'portal_groups') 
    415                 groupTool.removeGroups([self.getId()]) 
    416         except: 
    417             return 1 
    418         return 0 
     282#    def do_joining(self, userid, groupid): 
     283#        try: 
     284#            self.acl_users.source_groups.addPrincipalToGroup(userid, groupid) 
     285#        except: 
     286#            return 1 
     287#        return 0 
     288# 
     289#         
     290#    def do_leaving(self, userid, groupid): 
     291#        try: 
     292#            self.acl_users.source_groups.removePrincipalFromGroup(userid, groupid) 
     293#            if len(self.getGroupMembers()) <= 0: 
     294#                for x in self.getGroupMaterials(): 
     295#                    x.getObject().setGroupsShared('no_group') 
     296#                groupTool = getToolByName(self, 'portal_groups') 
     297#                groupTool.removeGroups([self.getId()]) 
     298#        except: 
     299#            return 1 
     300#        return 0 
     301 
     302 
     303    def addMember(self, memberid): 
     304        mtool = getToolByName(self, 'portal_membership') 
     305        memberfolder=mtool.getHomeFolder(memberid) 
     306        if not memberfolder: 
     307            print "We have a problem: %s cannot be found and is not added to group" % memberid 
     308            return False 
     309        mid=memberfolder.getMemberId() 
     310        users=list(self.getGroupMembers()) 
     311        if mid in users: 
     312            return False 
     313        self.setGroupMembers(users+[mid]) 
     314        return True 
     315             
     316    def removeMember(self, memberid): 
     317        mtool = getToolByName(self, 'portal_membership') 
     318        memberfolder=mtool.getHomeFolder(memberid) 
     319        if memberfolder: 
     320            mid=memberfolder.getMemberId() 
     321        else: 
     322            print "We have a problem: %s cannot be found. removing him from group anyway" % memberid 
     323            mid=memberid 
     324        users=list(self.getGroupMembers()) 
     325        if mid not in users: 
     326            return False 
     327        users=users.remove(mid) 
     328        self.setGroupMembers(users) 
     329        return True      
     330         
     331         
    419332             
    420333    def join_group(self): 
     
    425338        user = mtool.getAuthenticatedMember()         
    426339        userid = user.getId() 
    427         groupid = self.getId() 
    428         banned=self.getField('banned').get(self)         
    429         if userid in banned: 
    430             putils.addPortalMessage( _(u"You have been banned from this group and cannot join anymore.")) 
    431             return REQUEST.RESPONSE.redirect(self.community.absolute_url()) 
    432          
    433         join_res = 0 
    434         join_res = self.do_joining(userid, groupid) 
    435         if not join_res: 
     340        if self.addMember(userid): 
    436341            msg = _("You have joined the group '${title}'.", mapping={u'title' : self.title_or_id()}) 
    437342        else: 
    438             msg= _(u"Joining the group failed for some reason.") 
     343            msg= _(u"You are already member in this group.") 
    439344        putils.addPortalMessage(msg) 
    440345        return REQUEST.RESPONSE.redirect(self.absolute_url()) 
     
    447352        user = mtool.getAuthenticatedMember() 
    448353        userid = user.getId() 
    449         groupid = self.getId() 
    450         leave_res = 0 
    451         leave_res = self.do_leaving(userid, groupid) 
    452         if not leave_res: 
     354        if self.removeMember(userid): 
    453355            msg = _("You have left the group '${title}'.", mapping={u'title' : self.title_or_id()}) 
    454356        else: 
    455             msg= _(u"Leaving the group failed for some reason.") 
     357            msg= _(u"You are not member in this group.") 
    456358        putils.addPortalMessage(msg) 
    457359        return REQUEST.RESPONSE.redirect(self.community.absolute_url()) 
    458360 
    459  
    460 ### Mutators = default mutator + set group properties 
    461  
    462      
    463     security.declareProtected(MODIFY_CONTENT,'setProperties') 
    464     def setProperties(self, newprops=None, **kw): 
    465         """ Try to get mutator for each value and if there isn't one then change groups properties """ 
    466         if newprops is None: 
    467             newprops = kw 
    468         grouptool = getToolByName(self, 'portal_groups') 
    469         groupid=self.getId() 
    470         #print groupid +' changes properties:' + str(newprops) 
    471         for (key, value) in newprops.items(): 
    472             accessor='get'+str(key.capitalize()) 
    473             mutator='set'+str(key.capitalize()) 
    474  
    475             if hasattr(self, accessor): 
    476                 if eval('self.'+accessor+'()') != value: 
    477                     eval('self.'+mutator+'(value)') 
    478                     #print 'changing attribute with self.'+mutator+'(value), value='+str(value) 
    479                 else: 
    480                     group=grouptool.getGroupById(groupid) 
    481                     group.setProperties({key:value}) 
    482         self.reindexObject()          
    483  
    484     def setModerators(self, value, **kwargs): 
    485         field=self.getField('moderators') 
    486         old_mods=field.get(self) 
    487         if old_mods==None or old_mods=='' or old_mods==['']: old_mods=[] 
    488         if value==None or value=='' or value==['']: value=[] 
    489         additions= [x for x in value if x not in old_mods] 
    490         for member in additions: 
    491             if member != '': 
    492                 self.manage_setLocalRoles(member,['Reviewer']) 
    493         removals= [x for x in old_mods if x not in value] 
    494         for member in removals: 
    495             if 'Owner' not in self.get_local_roles_for_userid(member): 
    496                 self.manage_delLocalRoles(member)             
    497         field.set(self, value, **kwargs) 
    498          
    499     def setBanned(self, value, **kwargs): 
    500         field=self.getField('banned') 
    501         if type(value)==list or type(value)==tuple: 
    502             banlist=list(value) 
    503         else: 
    504             banlist= [x.strip() for x in value.split(',')] 
    505         if banlist==['']: banlist=[] 
    506         grouptool = getToolByName(self, 'portal_groups') 
    507         groupid=self.getId() 
    508         group=grouptool.getGroupById(groupid) 
    509         groupmembers= group.getGroupMemberIds() 
    510         those_who_need_a_kick= [x for x in banlist if x in groupmembers] 
    511         for kickee in those_who_need_a_kick:             
    512             if 'Owner' not in self.get_local_roles_for_userid(kickee): # can't kick yourself 
    513                 self.manage_delLocalRoles(kickee)                         
    514                 self.do_leaving(kickee, groupid) # kick! 
    515         field.set(self, value, **kwargs) 
     361  
    516362         
    517363 
     
    536382        self.reindexObject() 
    537383 
    538     def getArchDates(self): 
    539         """ Get years for Archives  """ 
    540         dates = [] 
    541         # The result should be something like this (but in reverse sorted order): 
    542         #['2006-10', '2006-01', '2007-11', '2006-07', '2007-04', '2007-02'] 
    543         results = self.objectValues('BlogPost') 
    544         for x in results: 
    545             cDate = x.CreationDate()[:7] 
    546             if cDate not in dates: 
    547                 dates.append(cDate) 
    548         dates.sort() 
    549         dates.reverse() 
    550          
    551         return dates 
    552  
    553  
    554     def interpritArchDates(self): 
    555         """ Interprit arch Dates given  """ 
    556         preresults = [] 
    557         results = [] 
    558         # This function splits the dates array elements by '-' in 2. And changes the code of the month by its name. 
    559         gotDates = self.getArchDates() 
    560         for y in gotDates: 
    561             preresults.append(y.split("-")) 
    562         for z in preresults: 
    563             item = z[1] 
    564             if item in monthNames.keys(): 
    565                 z[1] = monthNames[item] 
    566                 results.append(z) 
    567          
    568         return results 
    569384 
    570385    def recalculateScore(self): 
Note: See TracChangeset for help on using the changeset viewer.