""" Answer Session """
__version__ = "$Revision$"[11:-2]
import re
import Globals
from Globals import Acquisition, Persistent
from Acquisition import aq_base, aq_inner, aq_parent, Explicit
from AccessControl import ClassSecurityInfo
from Products.BTreeFolder2.BTreeFolder2 import BTreeFolder2
from zope.interface import implements
from SOAPpy import SOAPProxy
from SOAPpy import Types
from common import commons
from Permissions import *
from AnswerObject import AnswerObject
from interfaces import IAnswerSession
class AnswerSession(BTreeFolder2, Persistent, Explicit, commons):
""" answer session """
meta_type = 'Answer Session'
security = ClassSecurityInfo()
security.declareObjectPublic()
implements(IAnswerSession)
manage_options = BTreeFolder2.manage_options
def __init__(self, id, test_id):
self.id = id
self.position = 0
self.test_id = test_id
self.ques = []
BTreeFolder2.__init__(self, self.id)
def submitAnswer(self, REQUEST):
""" """
if not self.checkToken(REQUEST): return " "
pos = self.getPosition() + 1
testQuestions = self.getTestQuestions()
# just in case last question submit is clicked more than one, avoid getting error
if pos > len(testQuestions):
return self.utranslate('test_completed_msg', 'Test completed.');
questionId = testQuestions[pos-1]
# in case one submit button will be clicked more than once in test
answered_ques = REQUEST.form.get('quesid', '')
if answered_ques and (questionId != answered_ques):
return REQUEST.RESPONSE.redirect('index_html')
send = ''
for k in REQUEST.form.keys():
#print 'formkey::', k, 'keyvalue::', REQUEST.form.get(k)
if k in ['token', 'ques', 'submit', 'quesid']: continue
v = REQUEST.form.get(k)
k = k.replace('[]', '')
if not isinstance(str(''), type(v)):
# array
send += "%s" % k
for vv in v:
send += "%s" % vv
send += ""
else:
if v == '':
v = ' '
send += '%s%s' % ( k, v)
send += ""
if not "RESPONSE_" in send:
return REQUEST.RESPONSE.redirect('index_html')
self.setPosition(pos)
#create answer object
rand_nr=self.random_generator('_answer_')
ans_id = questionId + rand_nr
a=AnswerObject(ans_id, send, questionId)
self._setObject(ans_id, a)
if len(testQuestions) != pos:
return REQUEST.RESPONSE.redirect('index_html')
else:
return REQUEST.RESPONSE.redirect('finish_test')
def submitAnswers(self, REQUEST):
""" """
if self.getDoneOrNot() == False:
test = self.getTestById(self.test_id)
token = REQUEST.get('token')
try:
self.sendQuesToR2Q2()
except:
return REQUEST.RESPONSE.redirect('finish_test?msg=fail')
test.deleteToken(token)
self.setDone()
self.setSubmitTime()
return self.utranslate('test_completed_msg', 'Test completed.');
def sendQuesToR2Q2(self):
for a in self.objectValues('Answer Object'):
qid = a.getQuesId()
send = a.getAnswerSend()
if send == '':
ques = self.getQuestionById(qid)
tmp = ques.getPreview()
a.setAnswerHtml(tmp)
else:
url = self.cache._checkCache(qid, send)
if url == None:
a.setAnswer()
else:
obj_url = url.split('/')
url_beginning = obj_url[0]+'//'+obj_url[2]+'/'
url = url.replace(url_beginning, '')
obj = self.unrestrictedTraverse(url)
html = obj.getAnswerHtml()
points = obj.getFirstPoints()
a.setAnswerHtml(html)
a.setPoints(points)
def setSubmitTime(self):
import time
submittime = time.strftime("%d.%m.%Y %H:%M", time.localtime())
self.submittime = submittime
def getSubmitTime(self):
return getattr(self, 'submittime', '')
def setDone(self):
self.done = True
def getDoneOrNot(self):
return getattr(self, 'done', False)
def setPosition(self, val):
self.position = val
def getPosition(self):
return self.position
def setTestQuestions(self, questions):
self.ques = questions
def getTestQuestions(self):
return self.ques
def index_html(self, REQUEST):
""" """
if not self.checkToken(REQUEST): return " "
if self.isCompleted(): return " "
pos = self.getPosition()
testQuestions = self.getTestQuestions()
q = testQuestions[pos]
ques = self.getQuestionById(q)
html = ques.getBodyWithOwnButtons()
head = ques.getHead()
testlen = len(self.getTestQuestions())
quespos = pos + 1
headtext = """
"""
tmp = """
%s
""" % (headtext, q, quespos, testlen, html)
REQUEST.RESPONSE.setHeader('Content-Type', 'text/html;charset=UTF-8')
REQUEST.RESPONSE.setHeader("Pragma", "no-cache")
REQUEST.RESPONSE.setHeader("Expires", "0")
REQUEST.RESPONSE.setHeader("Cache-Control", "no-store, no-cache, max-age=0, must-revalidate")
return tmp
def finish_test(self, REQUEST, msg=''):
""" """
if not self.checkToken(REQUEST): return " "
if not self.isCompleted(): return " "
if self.getDoneOrNot() == True: return " "
finish_test_label = self.utranslate('finish_test_label', 'Finish test')
finish_test_text = self.utranslate('finish_test_text', 'You have answered all the questions. For finishing test, click \'Finish test\' button.');
message_text = ""
if msg == "fail":
message_text = self.utranslate('finish_test_failure_msg', 'Submitting answers failed. Please try again later.')
tmp = """
TATS
""" % (message_text, finish_test_text, finish_test_label)
REQUEST.RESPONSE.setHeader('Content-Type', 'text/html;charset=UTF-8')
REQUEST.RESPONSE.setHeader("Pragma", "no-cache")
REQUEST.RESPONSE.setHeader("Expires", "0")
REQUEST.RESPONSE.setHeader("Cache-Control", "no-store, no-cache, max-age=0, must-revalidate")
return tmp
#security.declarePrivate('getScore')
def getScore(self):
""" returns score. """
score = 0
for a in self.objectValues('Answer Object'):
points = a.getPoints()
score += points
return score
def isCompleted(self):
queslen = len(self.getTestQuestions())
pos = self.getPosition()
if queslen > pos:
return False
else:
return True
def getAllAnswers(self):
answers = []
testques = self.getTestQuestions()
ansobjects = self.objectValues('Answer Object')
for ques in testques:
for ans in ansobjects:
if ques == ans.getQuesId():
answers.append(ans)
return answers
Globals.InitializeClass(AnswerSession)
#EOF