# -*- coding: utf-8 # Copyright 2006 by Meelis Mets from Products.Archetypes.public import BaseSchema, Schema from Products.Archetypes.public import TextField, ReferenceField, BooleanField from Products.Archetypes.public import TextAreaWidget, ReferenceWidget, BooleanWidget from Products.Archetypes.public import BaseContent, OrderedBaseFolder, registerType from Globals import InitializeClass from Products.CMFCore.utils import getToolByName from BaseFunctions import BaseFunctions from HedgehogTask import HedgehogFunctions from FlowerTask import FlowerFunctions from TMTTask import TMTFunctions from DragTask import DragFunctions from AccessControl import ClassSecurityInfo, Unauthorized from config import PROJECT_NAME schema_answer_folder = BaseSchema + Schema(( ReferenceField('refsToTests', accessor = 'getRefsToTests', relationship = 'References', mutator = 'addRefsToTests', allowed_types = ('ChoiceTest',), multiValued = True, widget = ReferenceWidget( visible = {'view':'invisible', 'edit':'invisible'}, ), ), )) class AnswerFolder(BaseContent, BaseFunctions, HedgehogFunctions, FlowerFunctions, TMTFunctions, DragFunctions): """ Psyhvel base ansewr object""" meta_type = "AnswerFolder" archetype_name = "AnswerFolder" global_allow = 0 exclude_from_nav = True filter_content_types = True security = ClassSecurityInfo() schema = schema_answer_folder actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/test_view', 'permissions': ('View',), }, { 'id':'edit', 'visible':False, }, { 'id':'metadata', 'name':'Info', 'visible':False, 'action':'string:${object_url}/base_metadata', 'permissions': ('Modify portal content',), }, { 'id':'report', 'name':'Report', 'action':'string:${object_url}/test_report', 'permissions': ('Modify portal content',), }, { 'id':'managment', 'name':'Managment', 'action':'string:${object_url}/test_managment', 'permissions': ('Modify portal content',), } ) def __init__(self, id): self.id = id self.isGame = False #def DBHasUserDB(self, username_as_id): #"""u""" #objects = self.objectValues(['UserData',]) #print objects def getUserData(self, user=False): """user data""" if not user: user = str(self.REQUEST.AUTHENTICATED_USER) homefolder = self.portal_membership.getHomeFolder(user) if homefolder: return homefolder return 0 #return self.createUserData(user) def getIsStimulus(self): """set view""" ud = self.getUserData() if ud: return ud.getIsStimulus(self.id) return True def getIsGame(self): """set view""" if not hasattr(self, 'isGame'): self.isGame = False return self.isGame def stripId(self, id): """strips id""" return id.replace(".","").replace("-","") def getDataFromDatabase(self): """returns data from database""" user_list = self.listLocked() data = {} for user in user_list: ud = self.getUserData(user) if ud: user_data = ud.getDataFromDatabase(self.id) data[user] = user_data return data def setDataToDatabase(self, sheet, answer): """set data to database kay as member id""" ud = self.getUserData() if ud: ud.setDataToDatabase(self.id, sheet, answer) else: print "ERROR 404: no user database, i searched, but not found" def getCurrentPage(self): """returns current page""" ud = self.getUserData() if ud: if hasattr(ud, 'getCurrentPage'): return ud.getCurrentPage(self.id) def setCurrentPage(self): """set data to database kay as member id""" ud = self.getUserData() if ud: ud.setCurrentPage(self.id) print "liiguti uuele lehele" def isLocked(self): """returns info""" ud = self.getUserData() if ud: return ud.isLocked(self.id) def listLocked(self): """list locked users""" if not hasattr(self, 'locked_users'): self.locked_users = [] return self.locked_users def removeLocked(self,REQUEST): """unlock users""" users = self.listLocked() new_users = [] keys = REQUEST.get('users') if keys != None: for u in users: if u not in keys: new_users.append(u) else: ud = self.getUserData(u) ud.removeLocked(self.id) self.locked_users = new_users self._p_changed = 1 print "users removed" return self.REQUEST.RESPONSE.redirect(self.absolute_url()) def setLocked(self): """set data to database kay as member id""" self.listLocked() user = str(self.REQUEST.AUTHENTICATED_USER) if user not in self.locked_users: self.locked_users.append(user) self._p_changed = 1 def getGroupsForLocked(self): """groups""" groupstool = getToolByName(self, 'portal_groups') groups = groupstool.listGroupIds() grs = [] for g in groups: if g not in ['Administrators', 'Reviewers']: gr = groupstool.getGroupById(g) lgm = gr.getGroupMemberIds() grs.append([g,len(lgm)]) return grs def removeUserFromLL(self, user): """rmu""" new_users = [] locked_list = self.listLocked() if user in locked_list: for lu in locked_list: if lu != user: if lu not in new_users: new_users.append(lu) self.locked_users = new_users self._p_changed = 1 security.declareProtected('Modify portal content', 'removeLockedByGroups') def removeLockedByGroups(self,REQUEST): """unlock users""" groups = REQUEST.get('groups') removed_users = 0 if groups != None and groups != "None": groupstool = getToolByName(self, 'portal_groups') for g in groups: if g != "None": gr = groupstool.getGroupById(g) for user in gr.getGroupMemberIds(): user = str(user) self.removeUserFromLL(user) ud = self.getUserData(user) if hasattr(ud, 'removeLocked'): ru = ud.removeLocked(self.id) if ru: removed_users = removed_users + 1 return self.REQUEST.RESPONSE.redirect(self.absolute_url()+"/test_managment") def nonii(self): """aaa""" self.locked_users = ['metz', 'kati', 'juku'] self._p_changed = 1 def getDescription(self): """return tests description""" return self.getRefsToTests()[0].getDescription() def getMetaType(self): """return tests description""" return self.getRefsToTests()[0].meta_type def getAutoPlay(self): """return autoplay""" return self.getRefsToTests()[0].getAutoPlay() def getTestSoundFile(self): """return sound file""" return self.getRefsToTests()[0].getTestSoundFile() def getFolderContents(self): """return folder contents""" return self.getRefsToTests()[0].getFolderContents() def getGameTableWidth(self): """return folder contents""" return self.getRefsToTests()[0].getTableWidth() def getGameTableHeight(self): """return folder contents""" return self.getRefsToTests()[0].getTableHeight() def getChoiceFromDatabase(self,user,exercise,choice): """return choice""" ud = self.getUserData(user) if ud: data = ud.getChoiceFromDatabase(self.id, exercise, choice) return data return 0 def getMultipleChoice(self): """return multiple choice""" return self.getRefsToTests()[0].getMultipleChoice() def getCurrentSheet(self): """return folder contents""" sheets = self.getFolderContents() ud = self.getUserData() if ud: nr = ud.getCurrentPage(self.id)-1 if len(sheets) > nr: return sheets[nr].getObject() else: print "lehed said otsa" else: print "kasutaja andmeid ei leitud" return False def getRefTests(self): """get and return ref tests added to this collection""" return self.getRefsToTests() def addTestFromLibrary(self, test): """take test from library and add it to collection""" self.addRefsToTests(test) security.declareProtected('Modify portal content', 'addRefsToTests') def addRefsToTests(self, ref, empty=0): """ add reference to tests """ field = self.Schema().get('refsToTests') prev = field.getRaw(self) new_value = [] from types import ListType, TupleType if type(ref) == ListType or type(ref) == TupleType: new_value = prev if empty: new_value = [] for x in ref: new_value.append(x) else: new_value = prev+[ref,] field.set(self, new_value,) security.declareProtected('Modify portal content', 'delFromTests') def delFromTests(self, REQUEST): """ delete selected resource """ field = self.Schema().get('refsToTests') prev = field.getRaw(self, aslist=True) counter = 1 new = [] for x in prev: if REQUEST.get('test_nr_'+str(counter)) != "on": new.append(x) counter = counter + 1 field.set(self, new) def nextPage(self): """send to next page""" self.setCurrentPage() if len(self.getFolderContents())>self.getCurrentPage()-1: self.REQUEST.RESPONSE.redirect(self.absolute_url()) else: self.endTest() def endTest(self): """end of test""" ud = self.getUserData() ud.setLocked(self.id) self.setLocked() return self.REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url()) def sendAnswer(self,REQUEST): """sets answer to db""" answer = None ans = 2 answers = {} ud = self.getUserData() current = False if hasattr(self, 'getCurrentSheet'): current = self.getCurrentSheet() if current: current_id = current.id answs = [] for sheet in current.getFolderContents(): answers[sheet.id] = 0 if current.meta_type in ['ChoiceTask','SoundTask']: answer=REQUEST.get('ch_name') if answer != None: if isinstance(answer, type('')): answs.append(answer) else: answs = answer for a in answs: chObject = getattr(current, a) rc1 = chObject.getRightChoice() rc2 = chObject.getRightChoice2() rca = 0 if not rc1 and not rc2: rca = 1 elif rc1 and rc2: rca = 2 elif not rc1 and rc2: rca = 3 elif rc1 and not rc2: rca = 4 answers[a] = rca if current.getAnswerRequired() and answer == None: return self.REQUEST.RESPONSE.redirect(self.absolute_url()+'?error=true') elif not current.getAnswerRequired() or answer != None: ud.setDataToDatabase(self.id, current_id, answers) print "datasse l2hevad "+str(current_id)+" ja "+str(answers) ud.setCurrentPage(self.id) self.submitToTheNextPage(REQUEST) else: print "Tekkis viga!" return 0 def submitToTheNextPage(self,REQUEST): """ a function for submitting """ if len(self.getFolderContents())>self.getCurrentPage()-1: print "ei olnud viimane" return self.REQUEST.RESPONSE.redirect(self.absolute_url()) else: self.endTest() def getAllTasks(self): """returns all tasks in this test""" objects = self.getFolderContents() tasks = [] for obj in objects: if obj.meta_type[-4:] == 'Task': tasks.append(obj) return tasks def dataReport(self): """build data for report""" trs = getToolByName(self, 'translation_service') tasks = self.getAllTasks() dataReport = [] for task in tasks: choices = [] if task.meta_type =='HedgehogTask': for landscape in ['answer','total','empty','hill','river','moves']: choices.append({'id':landscape,'title':trs.utranslate('psyhvel', landscape, self, self)}) elif task.meta_type =='FlowerTask': choices.append({'id':'choice','title':trs.utranslate('psyhvel', 'choice', self, self)}) choices.append({'id':'clicked','title':trs.utranslate('psyhvel', 'clicked', self, self)}) elif task.meta_type =='TMTTask': choices.append({'id':'choice','title':trs.utranslate('psyhvel', 'faults', self, self)}) choices.append({'id':'data','title':trs.utranslate('psyhvel', 'data', self, self)}) choices.append({'id':'start_time','title':trs.utranslate('psyhvel', 'from loading to end', self, self)}) choices.append({'id':'finish_time','title':trs.utranslate('psyhvel', 'from starting to end', self, self)}) elif task.meta_type =='DragTask': for choice in task.getObject().getFolderContents(): choices.append({'id':choice.id+'_quarter','title':choice.Title+':'+trs.utranslate('psyhvel', 'quarter', self, self)}) choices.append({'id':choice.id+'_place','title':choice.Title+':'+trs.utranslate('psyhvel', 'place', self, self)}) else: for choice in task.getObject().getFolderContents(): choices.append({'id':choice.id,'title':choice.Title}) dataReport.append({'id':task.id,'title':task.Title,'choices':choices}) return dataReport def dataCSV(self): """ build data for CSV """ data_r = self.dataReport() csv = "Id" + "\t" # first line, heading for d in data_r: for c in d['choices']: csv += d['title']+":"+c['title'] + "\t" csv=csv[:-2] csv += "\n" #first line has been written data = self.getDataFromDatabase() for m in data: csv += m + "\t" for d in data_r: for c in d['choices']: row = self.getChoiceFromDatabase(m,d['id'],c['id']) csv += str(row) + "\t" csv=csv[:-2] csv += "\n" self.REQUEST.RESPONSE.setHeader('Content-type','text/x-comma-separated-values') self.REQUEST.RESPONSE.setHeader('Content-disposition','attachment; filename='+self.Title()+'.csv') return csv registerType(AnswerFolder, PROJECT_NAME)