# -*- coding: utf-8
# Copyright 2007 by Vahur Rebas
from Products.CMFCore.utils import getToolByName
from Permissions import *
import time
class CommonMix:
""" useful methods and common methods for all classes. """
#XXX this is temporary script for deleting spam and ham too
#def deleteAllTB(self):
# """ deleteallstuff """
# for mf in self.Members.objectValues('Eportfolio'):
# for mb in mf.objectValues('BlogFolder'):
# for mbe in mb.objectValues('BlogEntry'):
# trackbacks = mbe.getTrackbacks()
# for tb in trackbacks.keys():
# f = mbe.getField('trackbacks').delValue(mbe, [tb])
# trackbacksmade = mbe.getTrackbacksmade()
# for tbm in trackbacksmade.keys():
# f = mbe.getField('trackbacksmade').delValue(mbe, [tbm])
# return "done"
def vocReportUsers(self):
""" get a list of users for report """
ms = getToolByName(self, 'portal_membership')
users = ms.listMembers()
results = []
for u in users:
tmp = [u.getId(),'']
fn = u.getProperty('fullname')
if fn:
tmp[1] = u.getId() +' ('+ fn +')'
else:
tmp[1] = u.getId()
results.append(tmp)
results.sort()
#results.reverse()
return results
def vocReportGroups(self):
""" get a list of groups for report """
groups = self._getGroups()
results = []
for g in groups:
tmp = [g.getId(), '']
tit = g.getProperty('title')
if tit:
tmp[1] = tit
else:
tmp[1] = g.getId()
if g.getId() not in ['Administrators', 'Reviewers',]:
results.append(tmp)
results.sort()
#results.reverse()
return results
security.declareProtected('View', 'getGroups')
def getGroups(self, only_id=0):
"""returns list of groups"""
sta = time.time()
user = str(self.REQUEST.AUTHENTICATED_USER)
ms = getToolByName(self, 'portal_membership')
member = ms.getMemberById(user)
groups = self._getGroups()
g = []
for group in groups:
groupmembers = self._getGroupMembers(group)
if member in groupmembers:
if not only_id:
g.append(group)
else:
g.append(group.id)
end = time.time()
print "getGroups:", end-sta
return g
def getGroupById(self,id):
"""returns group"""
user = str(self.REQUEST.AUTHENTICATED_USER)
ms = getToolByName(self, 'portal_membership')
member = ms.getMemberById(user)
gt = getToolByName(self, 'portal_groups')
group = gt.getGroupById(id)
if member in self._getGroupMembers(group):
return group
def getGroupTasks(self, group):
"""group tasks"""
if group is None:
return []
pc = getToolByName(self, 'portal_catalog')
from config import TASK_TYPES
res = pc({'portal_type':TASK_TYPES, 'getTarget':group.id},sort_on='getDeadline', sort_order='descending')
return [ x.getObject() for x in res ]
def getHasTasks(self):
"""does user have any tasks?"""
from config import TASK_TYPES
user = str(self.REQUEST.AUTHENTICATED_USER)
groups = self.REQUEST.AUTHENTICATED_USER.getGroups()
groups.append(user)
pc = getToolByName(self, 'portal_catalog')
res = pc({'portal_type':TASK_TYPES, 'getTarget':groups})
length = len(res)
return length
security.declareProtected('View', 'getFullName')
def getFullName(self, username):
""" gets members fullname """
if username == None:
return ''
user_obj = self.portal_membership.getMemberById(username)
if not user_obj:
return ''
f_name = user_obj.getProperty('fullname')
if f_name == '':
f_name = username
return f_name
def isUserinTarget(self, user, target, only_id=0):
"""for cal results"""
# ms = getToolByName(self, 'portal_membership')
# member = ms.getMemberById(user)
groups = self._getGroups()
gr = []
gr.append(user)
members = []
for group in groups:
members = []
for mem in self._getGroupMembers(group):
members.append(str(mem))
if user in members:
if not only_id:
gr.append(str(group))
else:
gr.append(str(group.id))
isTarget = 0
if str(target) != '':
for g in gr:
if g in target:
isTarget = 1
return isTarget
def calResults(self, user, results, only_id=0):
"""what boxes to display"""
types = []
groups = self._getGroups()
gr = []
gr.append(user)
for group in groups:
members = []
for mem in self._getGroupMembers(group):
members.append(str(mem))
if str(user) in members:
if not only_id:
gr.append(str(group))
else:
gr.append(str(group.id))
for result in results:
resultType = str(result.Type)
if resultType == 'StructuredTask' or resultType == 'ReflectionTask':
resTarget = result.getTarget
for g in gr:
if str(g) in resTarget:
if resultType not in types:
types.append(resultType)
if resultType == 'BlogEntry':
if str(result.Creator) == str(user):
resultType = 'MyBlogEntry'
else:
resultType = 'OthersBlogEntry'
if resultType not in types:
types.append(resultType)
return types
def formatDate(self, date):
"""" """
date = time.strptime(date, "%Y-%m-%d %H:%M:%S")
date = time.strftime("%d.%m.%Y [%H:%M]", date)
return date
def formatDateShort(self, date):
"""" """
date = time.strptime(date, "%Y-%m-%d %H:%M:%S")
date = time.strftime("%d.%m.%y", date)
return date
def structureTime(self, time):
"""structures time"""
timeData = str(time).split("/")
timeLen = len(timeData)
timeString = ""
if timeLen > 2:
timeString += timeData[2]+"."
if timeLen > 1:
timeString += timeData[1]+"."
if timeLen > 0:
timeString += timeData[0]
from time import gmtime, strftime
currentTime = strftime("%Y/%m/%d", gmtime())
c1 = ""
c2 = ""
if str(time) == currentTime:
c1 = ""
elif str(time) < currentTime:
c1 = ""
return c1+timeString+c2
security.declareProtected('Modify portal content', 'delObjectById')
def delObjectById(self, REQUEST):
"""del object by id"""
ob_id = REQUEST.get("id")
if hasattr(self,ob_id):
self._delObject(ob_id)
else:
if hasattr(self,'blog'):
blog = getattr(self,'blog')
if hasattr(blog, ob_id):
blog._delObject(ob_id)
return REQUEST.RESPONSE.redirect(self.absolute_url())
def getLocalRolesByPerson(self, person):
roles = []
local_roles = self.getLocalRoles()
if local_roles:
for tuples in local_roles:
if str(tuples[0]) == str(person):
roles = roles + list(tuples[1])
return tuple(roles)
def getLocalRoles(self):
o=self.aq_base
if hasattr(o,'get_local_roles'):
return o.get_local_roles()
return False
def setPermissionsHere(self,targets,role):
"""lets set some permissions"""
for lr in self.getLocalRoles():
if lr[0] not in targets and 'Owner' not in lr[1]:
new_roles = ()
for r in lr[1]:
if role!=r:
new_roles += (r,)
if not new_roles:
self.manage_delLocalRoles((lr[0],)) #delRoles takes tuple!
else:
self.manage_setLocalRoles(lr[0],new_roles)
for target in targets:
old_roles = self.getLocalRolesByPerson(target)
if 'Owner' not in old_roles and role not in old_roles:
self.manage_setLocalRoles(target,old_roles+(role,))
def setModerators(self,REQUEST):
"""set group moderators"""
g_managers = REQUEST.get('group_managers')
g_moderators = REQUEST.get('group_moderators')
if g_managers:
if isinstance(g_managers,str):
g_managers = [g_managers]
self.setPermissionsHere(g_managers, 'Manager')
if g_moderators:
if isinstance(g_moderators,str):
g_moderators = [g_moderators]
self.setPermissionsHere(g_moderators, 'Moderator')
return self.REQUEST.RESPONSE.redirect(self.absolute_url())
def showEditableBorder(self, **args):
return 0
def displayContentsTab(self):
return 0;
def eportletowner(self, meta, creator, parent, user):
""" """
if meta == 'Groups' or meta == 'Dashboard':
return parent
if meta == 'StructuredTask' or meta == 'ReflectionTask':
return user
return creator
def getUserGroupMembers(self):
""" """
user = str(self.REQUEST.AUTHENTICATED_USER)
ms = getToolByName(self, 'portal_membership')
member = ms.getMemberById(user)
groups = self._getGroups()
g = []
for group in groups:
groupmembers = self._getGroupMembers(group)
if member in groupmembers:
for mem in groupmembers:
added = 0
if mem in g:
continue
if user == str(mem):
continue
g.append(mem)
return g
def getBlogrollLinks(self):
return self.blog.getBlogrollLinks()
def getTasks(self):
""" get tasks to lecturer"""
from config import TASK_TYPES
user = str(self.REQUEST.AUTHENTICATED_USER)
pc = getToolByName(self, 'portal_catalog')
res = pc({'portal_type':TASK_TYPES, 'getLecturer':user},sort_on='getDeadline', sort_order='descending')
print "bb:", [x.getObject() for x in res ]
return [ x.getObject() for x in res ]
def _getGroups(self):
gt = getToolByName(self, 'caching_tool')
return gt._getGroups()
def _getGroupMembers(self, group):
ct = getToolByName(self, 'caching_tool')
return ct._getGroupMembers(group)
# def getHelpTopicByTag(self, keyword):
# """ """
# helptext = ''
# for x in self.help.objectValues('HelpTopic'):
# keys = x.getKeywords()
# if keyword in keys:
# helptext += helptext + x.getTopic()
# chapters = self.help.objectValues('HelpChapter')
# for c in chapters:
# for htopic in c.objectValues('HelpTopic'):
# keys = htopic.getKeywords()
# if keyword in keys:
# helptext += htopic.getTopic()
# return helptext
def postTraceback(self, REQUEST):
""" post a traceback """
user = str(REQUEST.AUTHENTICATED_USER)
tb_url= REQUEST.form.get('tb_url')
if not tb_url: raise 'no tb_url'
pm = getToolByName(self, 'portal_membership')
blog = getattr(pm.getHomeFolder(user), 'blog', None)
if blog is None:
raise 'Critical error'
nr = 0
mid = "feedb-"+self.getId()+"-"+str(nr)
while hasattr(blog, "feedb-"+self.getId()+"-"+str(nr)):
nr += 1
mid = "feedb-"+self.getId()+"-"+str(nr)
id = blog.invokeFactory("BlogEntry", id = mid)
obj = getattr(blog, id)
if self.meta_type == "ReflectionAnswer":
obj.setBody(self.getAnswer())
obj.content_status_modify(workflow_action='restrict')
obj.RestrictItem(obj.getId(), {'access': 'groupmembers'}, self.Creator())
#obj.setTrackbacklink(tb_url)
#obj.setTitle("Feedback on...")
#obj.sendTrackback(tb_url)
return REQUEST.RESPONSE.redirect(obj.absolute_url()+'/edit?trackbackurl='+tb_url)