# -*- coding: utf-8 # Copyright 2006 by Meelis Mets from Products.Archetypes.public import BaseSchema, Schema from Products.Archetypes.public import TextField, ReferenceField, BooleanField, LinesField from Products.Archetypes.public import TextAreaWidget, ReferenceWidget, BooleanWidget, MultiSelectionWidget 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_collection = BaseSchema + Schema(( TextField('description', accessor='getDescription', widget = TextAreaWidget( label="Description", description="", label_msgid='label_description', description_msgid='description_description', visible={'view':'visible','edit':'visible'}, i18n_domain="psyhvel", rows = 5 ) ), BooleanField('activeTest', accessor = 'getActiveTest', widget = BooleanWidget( label = 'Active test', description = 'Check to set this tests state to active - users can answer', label_msgid="label_active_test", description_msgid="desc_active_test", i18n_domain="psyhvel", visible = {'view': 'invisible', 'edit':'visible'}, ) ), LinesField('testTarget', accessor = 'getTestTarget', multiValued = True, vocabulary = 'getTargets', widget = MultiSelectionWidget( label = 'Test target', description = 'Groups who get this test', label_msgid="label_test_target", description_msgid="desc_test_target", i18n_domain="psyhvel", visible = {'view': 'invisible', 'edit':'visible'}, ) ), )) # see answer class läheb siit vasti minema schema_answer = BaseSchema + Schema(( ReferenceField('refsToTests', accessor = 'getRefsToTests', relationship = 'References', mutator = 'addRefsToTests', allowed_types = ('ChoiceTest',), multiValued = True, widget = ReferenceWidget( visible = {'view':'invisible', 'edit':'invisible'}, ), ), )) class Answer(BaseContent, BaseFunctions, HedgehogFunctions, FlowerFunctions, TMTFunctions, DragFunctions): """ Psyhvel base ansewr object""" meta_type = "Answer" archetype_name = "Answer" global_allow = 0 exclude_from_nav = True filter_content_types = True allowed_content_types = () security = ClassSecurityInfo() schema = schema_answer 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.database = {} self.currentPage = {} self.locked = {} self.isStimulus = {} self.elementXY = {} def getIsStimulus(self): """set view""" if not hasattr(self, "isStimulus"): self.isStimulus = {} user = str(self.REQUEST.AUTHENTICATED_USER) if self.isStimulus.has_key(user): return self.isStimulus[user] return True def stripId(self, id): """strips id""" return id.replace(".","").replace("-","") def getDataFromDatabase(self): """returns data from database""" if not hasattr(self,'database'): self.database = {} return self.database def setDataToDatabase(self, sheet, answer): """set data to database kay as member id""" user = str(self.REQUEST.AUTHENTICATED_USER) if not self.database.has_key(user): self.database[user] = {} self.createUserDBObject(user) self.database[user][sheet] = answer self._p_changed = 1 def getCurrentPage(self): """returns current page""" user = str(self.REQUEST.AUTHENTICATED_USER) if not hasattr(self,'currentPage'): self.currentPage = {} if not self.currentPage.has_key(user): self.currentPage[user] = 0 return self.currentPage[user] def setCurrentPage(self): """set data to database kay as member id""" user = str(self.REQUEST.AUTHENTICATED_USER) if self.currentPage.has_key(user): pageNr = self.currentPage[user] else: pageNr = 0 self.currentPage[user] = pageNr + 1 self._p_changed = 1 def isLocked(self): """returns info""" user = str(self.REQUEST.AUTHENTICATED_USER) if not hasattr(self,'locked'): self.locked = {} if self.locked.has_key(user): return True return False def listLocked(self): """list locked users""" return self.locked.keys() def removeLocked(self,REQUEST): """unlock users""" users = [] keys = REQUEST.get('users') if keys != None: if self.locked.has_key(str(keys)): del self.locked[keys] del self.currentPage[keys] else: for key in keys: del self.locked[key] del self.currentPage[key] self._p_changed = 1 return self.REQUEST.RESPONSE.redirect(self.absolute_url()) def setLocked(self): """set data to database kay as member id""" user = str(self.REQUEST.AUTHENTICATED_USER) self.locked[user] = True 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 getChoiceFromDatabase(self,user,exercise,choice): """return choice""" data = self.getDataFromDatabase() if data.has_key(user): if data[user].has_key(exercise): if data[user][exercise].has_key(choice): return data[user][exercise][choice] return 0 def getMultipleChoice(self): """return multiple choice""" return self.getRefsToTests()[0].getMultipleChoice() def getCurrentSheet(self): """return folder contents""" sheets = self.getFolderContents() nr = self.getCurrentPage()-1 if len(sheets) > nr: return sheets[nr].getObject() 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""" 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 = {} current = self.getCurrentSheet() current_id = current.id answs = [] for sheet in current.getFolderContents(): answers[sheet.id] = 0 if current.meta_type in ['ChoiceTask','SoundTask']: answer=REQUEST.get('choice') 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: self.setDataToDatabase(current_id,answers) print "datasse l2hevad "+str(current_id)+" ja "+str(answers) self.setCurrentPage() self.submitToTheNextPage(REQUEST) 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)}) 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(Answer, PROJECT_NAME) class Collection(OrderedBaseFolder, BaseFunctions): """ Psyhvel test collection""" meta_type = "Collection" archetype_name = "Collection" global_allow = 0 exclude_from_nav = True filter_content_types = True allowed_content_types = () security = ClassSecurityInfo() schema = schema_collection actions = ( { 'id':'view', 'name':'View', 'action':'string:${object_url}/collection_view', 'permissions': ('View',), }, { 'id':'edit', 'name':'Configuration', 'action':'string:${object_url}/base_edit', 'permissions': ('Modify portal content',), }, { 'id':'metadata', 'visible':False, 'permissions': ('Modify portal content',), }, ) security.declareProtected('View', 'getTargets') def getTargets(self): """ Classes massive """ classes = [] #'Nobody', groupstool = getToolByName(self, 'portal_groups') groups = groupstool.listGroupIds() for target in groups: target2 = groupstool.getGroupById(target) target = str(target) if target not in ['Administrators', 'Reviewers']: classes.append(target) return classes registerType(Collection, PROJECT_NAME)