# -*- coding: utf-8 # Copyright 2005 by Meelis Mets from Products.Archetypes.public import BaseSchema, Schema from Products.Archetypes.public import StringField, LinesField, DateTimeField, TextField, ReferenceField from Products.Archetypes.public import LinesWidget, TextAreaWidget, IdWidget, StringWidget, SelectionWidget, CalendarWidget, RichWidget from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget from Products.Archetypes.public import BaseContent, OrderedBaseFolder, registerType from Globals import InitializeClass from Products.CMFCore.utils import getToolByName from Products.CMFCore.permissions import View from Products.CMFCore.permissions import ModifyPortalContent from AccessControl import ClassSecurityInfo, Unauthorized from config import PROJECT_NAME, PERMISSIONS schema = BaseSchema class ToDo(BaseContent): """ ToDo """ meta_type = "ToDo" archetype_name = "ToDo" global_allow = 0 filter_content_types = True allowed_content_types = () security = ClassSecurityInfo() schema = schema + Schema(( DateTimeField('Deadline', required=1, accessor="getDeadline", isMetadata=1, searchable=1, widget=CalendarWidget( format="%d.%m.%Y", show_hm=False, label="Deadline", label_msgid='label_deadline', description="Deadline of task.", description_msgid='desc_deadline', visible={'view':'invisible','edit':'visible'}, i18n_domain="eportfolio"), ), LinesField('Target', required=1, accessor="getTarget", isMetadata=1, searchable=1, vocabulary='getTargets', widget=SelectionWidget( format="select", label="Target", label_msgid='label_target', description="Target whos get that task.", description_msgid='desc_target', visible={'view':'invisible','edit':'visible'}, i18n_domain="eportfolio"), ), TextField('task', accessor='getTask', isMetadata=0, required=True, searchable=True, primary=True, validators = ('isTidyHtmlWithCleanup',), default_output_type = 'text/x-html-safe', allowable_content_types = ('text/html',), widget = RichWidget( label="Task", description="", label_msgid='label_task', description_msgid='description_task', visible={'view':'visible','edit':'visible'}, i18n_domain="eportfolio", rows = 25)), )) actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/task_view', 'permissions': ('View',), }, { 'id':'answers', 'name':'Answers', 'action':'string:${object_url}/answers_view', 'permissions': ('Modify portal content',), }, { 'id':'edit', 'name':'Edit', 'action':'string:${object_url}/base_edit', 'permissions': ('Modify portal content',), }, { 'id':'metadata', 'name':'Properties', 'action':'string:${object_url}/base_metadata', 'permissions': ('Manage Portal',), }, ) def getTargets(self): """ Targets array """ targets = [] groupstool = getToolByName(self, 'portal_groups') #user = self.acl_users.getUserById('juku') #groups = user.getGroups() or [] #groups = [groupstool.getGroupById(elt) for elt in groups] groups = groupstool.listGroupIds() for target in groups: target = str(target) if target not in ['Administrators', 'Reviewers']: targets.append(target) return targets def getStudentsByTarget(self, target): """ students array """ students = [] groupstool = getToolByName(self, 'portal_groups') #user = self.acl_users.getUserById('juku') #groups = user.getGroups() or [] #groups = [groupstool.getGroupById(elt) for elt in groups] groups = groupstool.listGroupIds() roles = PERMISSIONS target = target[0] for group in groups: if str(target) == str(group): group2 = groupstool.getGroupById(group) for m in group2.getGroupMembers(): access = True for role in m.getRolesInContext(self): if role in roles['notInTaskList']: access = False if access: students.append(m.id) return students def getAnswerText(self, student): """ gets students answer if possible""" homeFolder = self.portal_membership.getHomeFolder(student) if hasattr(homeFolder, 'tasks'): taskFolder = getattr(homeFolder, 'tasks') answer_id = self.id+"-answer" if hasattr(taskFolder, answer_id): answerObj = getattr(taskFolder, answer_id) return answerObj.answer else: return "" else: return "" def getAnswersByTarget(self, target): """ gets students answer if possible""" answers = [] students = self.getStudentsByTarget(target) for student in students: answer = 'red_x.gif' url = self.absolute_url() answerObj = self.getAnswerByMember(student) if answerObj != False: answer = 'grey_v.gif' url = answerObj.absolute_url() if answerObj.accepted!='none': answer = 'green_v.gif' answers.append({'student':student,'answer':answer,'url':url}) return answers def getAnswerByMember(self, member): """ get answer by member """ homeFolder = self.portal_membership.getHomeFolder(member) if hasattr(homeFolder, 'tasks'): taskFolder = getattr(homeFolder, 'tasks') answer_id = self.id+"-answer" if hasattr(taskFolder, answer_id): return getattr(taskFolder, answer_id) return False def getAccepted(self, student): """ gets students answer if possible""" homeFolder = self.portal_membership.getHomeFolder(student) if hasattr(homeFolder, 'tasks'): taskFolder = getattr(homeFolder, 'tasks') answer_id = self.id+"-answer" if hasattr(taskFolder, answer_id): answerObj = getattr(taskFolder, answer_id) if answerObj.accepted!='none': return True return False def answerTask(self, REQUEST): """ Copies already made form to users forms folder """ user = str(REQUEST.AUTHENTICATED_USER) homeFolder = self.portal_membership.getHomeFolder(user) taskFolder = getattr(homeFolder, 'tasks') answer_id = str(self.id)+"-answer" if hasattr(taskFolder, answer_id): answerObj = getattr(taskFolder,answer_id) answerObj.answer = REQUEST.get('answer') else: #make new answer from Task import Answer new_answer = Answer(answer_id) taskFolder._setObject(new_answer.id, new_answer) answerObj=getattr(taskFolder, new_answer.id) answerObj.setTitle(self.title) answerObj.answer = REQUEST.get('answer') answerObj.task = self.getTask() answerObj.parent_task = self.Creator() answerObj.reindexObject() self._p_changed = 1 return answerObj def allowAccept(self, user): """ is accepting allowed no, not here """ return False registerType(ToDo, PROJECT_NAME) class Answer(BaseContent): """ Answer """ meta_type = "Answer" archetype_name = "Answer" global_allow = 0 filter_content_types = True allowed_content_types = () security = ClassSecurityInfo() schema = schema + Schema(( TextField('task', accessor='getTask', validators = ('isTidyHtmlWithCleanup',), default_output_type = 'text/x-html-safe', allowable_content_types = ('text/html',), widget = RichWidget( label="Task", description="", label_msgid='label_task', description_msgid='description_task', visible={'view':'visible','edit':'visible'}, i18n_domain="eportfolio", rows = 25), ), TextField('answer', accessor='getAnswer', validators = ('isTidyHtmlWithCleanup',), default_output_type = 'text/x-html-safe', allowable_content_types = ('text/html',), widget = RichWidget( label="Answer", description="", label_msgid='label_answer', description_msgid='description_answer', visible={'view':'visible','edit':'visible'}, i18n_domain="eportfolio", rows = 25), ), )) actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/task_view', 'permissions': ('View',), }, { 'id':'edit', 'name':'Edit', 'action':'string:${object_url}/base_edit', 'permissions': ('Manage Portal',), }, { 'id':'metadata', 'name':'Properties', 'action':'string:${object_url}/base_metadata', 'permissions': ('Manage Portal',), }, ) def saveTask(self, REQUEST): """ Saves data """ self.answer = REQUEST.get('answer') return 1 def getAnswerText(self, student): """ gets answer """ return self.answer def getComments(self): """ gets comments """ return self.comments def getAccepted(self, student): """ gets answer """ if self.accepted!='none': return True else: return False def acceptAnswer(self): """ Accept this answer """ self.accepted = "True" self._p_changed = 1 return 1 def addComment(self, REQUEST): """ Comment this answer """ name = str(REQUEST.AUTHENTICATED_USER) comment = REQUEST.get('comment') import time time = str(time.strftime('%d/%m/%Y')) self.comments.append({'name':name, 'time':time,'comment':comment}) self._p_changed = 1 return 1 def allowAccept(self, user): """ is accepting allowed """ if user in [self.parent_task,] and self.accepted=='none': return True return False def isAllowedToComment(self, member): """ returns rights""" if member.id in [self.Creator(),self.parent_task]: return True return False def __init__(self, id): self.id = id self.parent_task = "none" self.accepted = "none" self.comments = [] registerType(Answer, PROJECT_NAME) class LinkTo(BaseContent): """ LinkTo """ meta_type = "LinkTo" archetype_name = "Link To" global_allow = 0 filter_content_types = True allowed_content_types = () security = ClassSecurityInfo() schema = schema + Schema(( DateTimeField('Deadline', required=1, accessor="getDeadline", isMetadata=1, searchable=1, widget=CalendarWidget( format="%d.%m.%Y", show_hm=False, label="Deadline", label_msgid='label_deadline', description="Deadline of task.", description_msgid='desc_deadline', visible={'view':'invisible','edit':'visible'}, i18n_domain="eportfolio"), ), LinesField('Target', required=1, accessor="getTarget", isMetadata=1, searchable=1, vocabulary='getTargets', widget=SelectionWidget( format="select", label="Target", label_msgid='label_target', description="Target whos get that task.", description_msgid='desc_target', visible={'view':'invisible','edit':'visible'}, i18n_domain="eportfolio"), ), ReferenceField('link', accessor = 'getRefsToLink', relationship = 'References', mutator = 'addRefsToLink', allowed_types = (), multiValued = False, widget = ReferenceBrowserWidget( force_close_on_insert = True, startup_directory = "eportfolio", label = "Links", label_msgid = "label_link", description="Choose object you want to link with", description_msgid='desc_link', i18n_domain = "eportfolio", visible = {'view':'visible', 'edit':'visible'},) ), StringField('link2', accessor="getLink2", widget=StringWidget( label="Alternate link", label_msgid='label_alternate_link', description="Fill this field only, if you point to object with text url not as object", description_msgid='desc_alternate_link', visible={'view':'invisible','edit':'visible'}, i18n_domain="eportfolio"), ), )) actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/base_view', 'permissions': ('View',), }, { 'id':'edit', 'name':'Edit', 'action':'string:${object_url}/base_edit', 'permissions': ('Manage Portal',), }, { 'id':'metadata', 'name':'Properties', 'action':'string:${object_url}/base_metadata', 'permissions': ('Manage Portal',), }, ) def getLinkToObject(self): """ gets link to object """ object = self.getRefsToLink() if object: url = object.absolute_url() else: url = self.link2 return url def getTargets(self): """ Targets array """ targets = [] groupstool = getToolByName(self, 'portal_groups') groups = groupstool.listGroupIds() for target in groups: target = str(target) if target not in ['Administrators', 'Reviewers']: targets.append(target) return targets def addVisitor(self,member): """add member as visitor""" if member not in self.visitors: self.visitors.append(member) self._p_changed = 1 def getVisitors(self,member): """get member as visitor""" if member in self.visitors: return True return False def redirect(self,REQUEST): """ redirect to url """ url = self.getLinkToObject() member = str(REQUEST.AUTHENTICATED_USER) pm = getToolByName(self, 'portal_membership') memberObj = pm.getMemberById(member) if memberObj == None: school = '/' else: school = str(memberObj.school) self.addVisitor(member) url = url.replace('{member}', member) url = url.replace('{school}', school) return REQUEST.RESPONSE.redirect(url) def __init__(self, id): self.id = id self.parent_task = "none" self.accepted = "none" self.visitors = [] registerType(LinkTo, PROJECT_NAME) class TaskFolder(OrderedBaseFolder): """ TaskFolder """ meta_type = "TaskFolder" archetype_name = "TaskFolder" global_allow = 0 exclude_from_nav = True filter_content_types = True allowed_content_types = ('ToDo','Form','LinkTo') security = ClassSecurityInfo() schema = schema actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/tasks_view', 'permissions': ('View',), }, { 'id':'edit', 'name':'Edit', 'action':'string:${object_url}/base_edit', 'permissions': ('Manage Portal',), }, { 'id':'metadata', 'name':'Properties', 'action':'string:${object_url}/base_metadata', 'permissions': ('Manage Portal',), }, ) def __init__(self, id): self.id = id self.largeIcon = "presentation.gif" def getLargeIcon(self): """ returns subfolders large icon """ return self.largeIcon def getAllForms(self): """ gets all forms """ forms = [] query_string = {'meta_type': 'Form'} pcatalog = getToolByName(self, 'portal_catalog') results = pcatalog.searchResults(query_string) for ob in results: object = ob.getObject() if (object.formCopy==0): forms.append(object) return forms def cutTitle(self, title, lenght): """ cut tail of title """ if len(title)>lenght: return title[:lenght]+'...' return title registerType(TaskFolder, PROJECT_NAME) class WorkSheet(BaseContent): """ WorkSheet """ meta_type = "WorkSheet" archetype_name = "WorkSheet" global_allow = 0 exclude_from_nav = True filter_content_types = True security = ClassSecurityInfo() schema = schema actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/worksheet_view', 'permissions': ('View',), }, { 'id':'edit', 'name':'Edit', 'action':'string:${object_url}/base_edit', 'permissions': ('Manage Portal',), }, { 'id':'metadata', 'name':'Properties', 'action':'string:${object_url}/base_metadata', 'permissions': ('Manage Portal',), }, ) def __init__(self, id): self.id = id self.largeIcon = "forms.gif" security.declareProtected(View, 'getLargeIcon') def getLargeIcon(self): """ returns subfolders large icon """ return self.largeIcon # we take all groups with hasworksheet attribute security.declareProtected(View, 'getWorkSheets') def getWorkSheets(self): """ Worksheets array """ gr=[] groupstool = getToolByName(self, 'portal_groups') user = self.acl_users.getUserById(self.Creator()) groups = [] if user!=None: groups = user.getGroups() groups = [groupstool.getGroupById(elt) for elt in groups] for g in groups: if g.getProperty('hasworksheet'): gr.append(g) return gr # i need it? #security.declareProtected(View, 'getGroupsByPractice') #def getGroupsByPractice(self,practice): #""" Targets array """ #gr = [] #groupName = 'None' #groupstool = getToolByName(self, 'portal_groups') #user = self.acl_users.getUserById(self.Creator()) #groups = [] #if user!=None: # groups = user.getGroups() #groups = [groupstool.getGroupById(elt) for elt in groups] #for g in groups: # if hasattr(g,'practice'): # if g.getProperty('practice')==str(practice): # groupName = g.title #return groupName security.declareProtected(View, 'getThisTime') def getThisTime(self): """ Time """ import time return str(time.strftime('%Y/%m/%d')) security.declareProtected(View, 'getExpiration') def getExpiration(self, deadline): """ Expiration """ if deadline < self.getThisTime(): return True else: return False security.declareProtected(View, 'reverseDate') def reverseDate(self, date): """reverse date string yyyy/mm/dd to dd/mm/yyyy""" date = date.split('/') if len(date)>2: return date[2]+'/'+date[1]+'/'+date[0] #collectiong tasks ToDo and Form objects security.declareProtected(View, 'getTasks') def getTasks(self, target): """ Tasks """ tasks=[] query_string = {'SearchableText': {'operator': 'or', 'query': (str(target),)}} pcatalog = getToolByName(self, 'portal_catalog') results = pcatalog.searchResults(query_string) for task in results: if task.meta_type in ['ToDo','Form','LinkTo'] and str(task.id)[-4:]!='copy' and task.getObject().aq_parent.getId()=='tasks': tasks.append(task) return tasks security.declareProtected(View, 'createRegistrationTask') def createRegistrationTask(self,practice): """ creating registration task """ student = self.Creator() regDatabase = getattr(self,'schooldatabase') regStatus = regDatabase.getStateOfMember(practice, student) if practice==0: prac = 'registration_view' else: prac = 'registration_view' if regStatus == 'sleeping': status = '' elif regStatus == 'pending': status = '' elif regStatus == 'accepted': status = '' link = self.portal_url()+'/schooldatabase/'+prac deadline = '2006/09/01' groupstool = getToolByName(self, 'portal_groups') user = self.acl_users.getUserById(self.Creator()) groups = [] if user!=None: groups = user.getGroups() groups = [groupstool.getGroupById(elt) for elt in groups] for g in groups: if hasattr(g,'practice'): if str(g.getProperty('practice'))==str(practice): deadline = g.getProperty('deadline') title = 'Registreeru praktikale' locked = self.getExpiration(deadline) return {'deadline':deadline,'title':title,'status':status,'locked':locked,'link':link} # here we collect some info for listing tasks security.declareProtected(View, 'getTaskList') def getTaskList(self, target): """ Tasks """ taskList = [] student = self.Creator() practice=target.getProperty('practice') if practice!='': regTask = self.createRegistrationTask(int(practice)) taskList.append(regTask) #tasks for task in self.getTasks(str(target)): owner = task.Creator worksheetOwner = self.Creator() print worksheetOwner ownerFolder = self.portal_membership.getHomeFolder(owner) taskFolder = getattr(ownerFolder, 'tasks') answerFolder = getattr(self.aq_parent, 'tasks') if task.meta_type=='ToDo': answer_id = task.id+"-answer" elif task.meta_type=='Form': answer_id = task.id+"-copy" elif task.meta_type=='LinkTo': answer_id = task.id answerFolder = getattr(ownerFolder, 'tasks') task_obj = getattr(taskFolder, task.id) deadline = str(task_obj.Deadline) locked = self.getExpiration(deadline) title = task.Title status = '' if hasattr(answerFolder, answer_id): answerObj = getattr(answerFolder, answer_id) if answerObj.meta_type=='Answer': if answerObj.accepted == "none": link = answerObj.absolute_url() status = '' else: status = '' link = answerObj.absolute_url() if answerObj.meta_type=='LinkTo': if answerObj.getVisitors(worksheetOwner): status = '' else: status = '' link = answerObj.absolute_url()+'/redirect' else: status = '' link = answerObj.absolute_url() else: status = '' link = task_obj.absolute_url() taskList.append({'deadline':deadline,'title':title,'status':status,'locked':locked,'link':link}) taskList.sort() return taskList security.declareProtected(View, 'getList') def getList(self,target): """ get list with all students with all todos """ data = [] students = self.getStudentsByTarget(target) todos = self.getTasks(str(target)) for student in students: tasks= [] for task in todos: owner = task.Creator ownerFolder = self.portal_membership.getHomeFolder(owner) taskFolder = getattr(ownerFolder, 'tasks') studentFolder = self.portal_membership.getHomeFolder(student) answerFolder = getattr(studentFolder, 'tasks') if task.meta_type=='ToDo': answer_id = task.id+"-answer" elif task.meta_type=='Form': answer_id = task.id+"-copy" elif task.meta_type=='LinkTo': answer_id = task.id answerFolder = getattr(ownerFolder, 'tasks') task_obj = getattr(taskFolder, task.id) deadline = str(task_obj.Deadline) locked = self.getExpiration(deadline) title = task.Title status = '' if hasattr(answerFolder, answer_id): answerObj = getattr(answerFolder, answer_id) if answerObj.meta_type=='Answer': if answerObj.accepted == "none": link = answerObj.absolute_url() status = 'grey_v.gif' else: status = 'green_v.gif' link = answerObj.absolute_url() if answerObj.meta_type=='LinkTo': if answerObj.getVisitors(student): status = 'green_v.gif' else: status = 'red_x.gif' link = answerObj.absolute_url()+'/redirect' else: status = 'green_v.gif' link = answerObj.absolute_url() else: status = 'red_x.gif' link = task_obj.absolute_url() tasks.append({'deadline':deadline,'title':title,'status':status,'locked':locked,'link':link}) tasks.sort() data.append({'student':student,'tasks':tasks}) return data security.declareProtected(View, 'getStudentsByTarget') def getStudentsByTarget(self, target): """ students array """ students = [] perm='notInTaskList' if target.getProperty('practice')!='': perm='notInPracticeTaskList' groupstool = getToolByName(self, 'portal_groups') groups = groupstool.listGroupIds() roles = PERMISSIONS for group in groups: if str(target) == str(group): for m in groupstool.getGroupById(group).getGroupMembers(): access = True for role in m.getRolesInContext(self): if role in roles[perm]: access = False if access: students.append(m.id) return students security.declareProtected(View, 'getStudentsByGroup') def getStudentsByGroup(self, group_name): """ returns students of requested group """ group = self.prefs_user_group_search(group_name, 'groups') group = group[0] return group.getGroupMembers() security.declareProtected(View, 'getTargets') def getTargets(self, practice, member): """ Targets array """ targets = [] groupstool = getToolByName(self, 'portal_groups') groups = groupstool.listGroupIds() for target in groups: target2 = groupstool.getGroupById(target) if hasattr(target2,'practice'): if member in target2.getGroupMembers() and target2.getProperty('practice')==practice: targets.append(str(target)) return targets security.declareProtected(View, 'getTasksDoneByStudent') def getTasksDoneByStudent(self, student, task): """ gets task from students home folder if it exists """ homeFolder = self.portal_membership.getHomeFolder(student) if hasattr(homeFolder, 'tasks'): taskFolder = getattr(homeFolder, 'tasks') answer_id = task+"-answer" if hasattr(taskFolder, answer_id): answerObj = getattr(taskFolder, answer_id) if answerObj.accepted == "none": return {'status':'O','url':answerObj.absolute_url()} else: return {'status':'V','url':answerObj.absolute_url()} return {'status':'X','url':'None'} security.declareProtected(View, 'getTasksDoneByLector') def getTasksDoneByLector(self, lector, task): """ gets task from lectors home folder if it exists """ homeFolder = self.portal_membership.getHomeFolder(lector) if hasattr(homeFolder, 'tasks'): taskFolder = getattr(homeFolder, 'tasks') task_id = task if hasattr(taskFolder, task_id): taskObj = getattr(taskFolder, task_id) return taskObj.absolute_url() return False security.declareProtected(View, 'hasAccessToSee') def hasAccessToSee(self, who, what): """if user has access to see it""" allowedRoles = PERMISSIONS userRoles = who.getRolesInContext(self) for role in allowedRoles[what]: if role in userRoles: return True return False registerType(WorkSheet, PROJECT_NAME)