widget=SelectionWidget(
                 label="Referrer",
                 description="How did you hear about Connexions?",
             )),
 TextField(
     'description',
     required=1,
     default_content_type='text/html',
     default_output_type='text/html',
     widget=TextAreaWidget(
         label="Comment",
         description='Your feedback about Connexions (html is allowed)',
     )),
 ImageField(
     'portrait',
     widget=ImageWidget(
         label="Portrait",
         description='Feel free to include a small portrait of yourself',
     )),
 BooleanField(
     'quote_permission',
     default=1,
     widget=BooleanWidget(
         label=
         "Will you allow Connexions to display a quote from your feedback on the Web site?",
         description=
         "Allow Connexions to display a quote from their feedback on the Web site?",
     )),
 BooleanField(
     'name_permission',
     default=1,
     widget=BooleanWidget(
Beispiel #2
0
 ),
 StringField(
     "AccreditationReference",
     schemata="Accreditation",
     write_permission=ManageBika,
     widget=StringWidget(
         label=_("Accreditation Reference"),
         description=_("The reference code issued to the lab by the "
                       "accreditation body"),
     ),
 ),
 ImageField(
     "AccreditationBodyLogo",
     schemata="Accreditation",
     widget=ImageWidget(
         label=_("Accreditation Logo"),
         description=_(
             "Please upload the logo you are authorised to use on your "
             "website and results reports by your accreditation body. "
             "Maximum size is 175 x 175 pixels.")),
 ),
 TextField(
     "AccreditationPageHeader",
     schemata="Accreditation",
     default=DEFAULT_ACCREDITATION_PAGE_HEADER,
     widget=TextAreaWidget(
         label=_("Accreditation page header"),
         description=_(
             "Enter the details of your lab's service accreditations here. "
             "The following fields are available:  lab_is_accredited, "
             "lab_name, lab_country, confidence, accreditation_body_name, "
             "accreditation_standard, accreditation_reference<br/>"),
Beispiel #3
0
    IntegerField('internal_id',
        searchable=False,
        isMetadata=True,
        mutator="setInternal_id",
        widget=IntegerWidget(label='Internal ID',
            description='',
            visible={'view':'invisible','edit':'hidden'},
            ),
        ),

    ImageField('category_image',
        widget=ImageWidget(label='Category image',
            description='',
            label_msgid='label_category_image',
            description_msgid='help_category_image',
            i18n_domain='plone',
            ),
        sizes={ 'icon':(16,16)},
        ),

    ),
    marshall=PrimaryFieldMarshaller(),
    )

finalizeATCTSchema(COREBlogCategorySchema)

class COREBlogCategory(ATCTFolder):
    """
    Category class for coreblog2
    """
Beispiel #4
0
        required=False,
        primary=True,
        storage=FileSystemStorage(),
        widget=FileWidget(
            description=
            "Select the file to be added by clicking the 'Browse' button.",
            description_msgid="help_file",
            label="File",
            label_msgid="label_file",
            i18n_domain="plone",
            show_content_type=False,
        )),
    ImageField('image',
               required=False,
               sizes={
                   'mini': (40, 40),
                   'thumb': (80, 80),
               },
               storage=FileSystemStorage(),
               widget=ImageWidget()),
    TextField('text',
              required=False,
              storage=FileSystemStorage(),
              widget=TextAreaWidget()),
),
                       marshall=PrimaryFieldMarshaller())

FSSItemSchema = BaseSchema.copy() + BaseItemShema.copy()
ATFSSItemSchema = ATContentTypeSchema.copy() + BaseItemShema.copy()


class FSSItem(BaseContent):
Beispiel #5
0
     required=1,
     default_output_type='text/x-html-safe',
     widget=RichWidget(
         description='',
         description_msgid='help_text',
         i18n_domain="plone",
         label='Text',
         label_msgid='label_text',
     )
 ),
 ImageField(
     name='image',
     widget=ImageWidget(
         description="This image is used as preview for the referenced objects.",
         description_msgid="help_image",
         i18n_domain='plonegazette',
         label='Preview image',
         label_msgid="label_preview_image",
     ),
     storage=AttributeStorage(),
     sizes={'normal': (200, 130), },
 ),
 OrderableReferenceField(
     'references',
     languageIndependent=1,
     required=0,
     allowed_types=(),
     multiValued=1,
     relationship='references',
     widget=ReferenceBrowserWidget(
         allow_browse=1,
         allow_search=1,
from Products.Archetypes.public import BaseSchema
from Products.Archetypes.public import Schema
from Products.Archetypes.public import ImageField
from Products.Archetypes.public import ImageWidget
from Products.Archetypes.public import BaseContent
from Products.Archetypes.public import registerType

from Products.Archetypes.Marshall import PrimaryFieldMarshaller
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from Products.Quills.config import PROJECTNAME

WeblogTopicSchema = BaseSchema.copy() + Schema((
    ImageField('topicImage',
        required=1,
        sizes={'64' : (64,64),},
           widget=ImageWidget(label="Image",
               description="An image for your topic. The image should be 64x64.  If the image is larger it will be scaled down automatically to fit within a 64x64 square."),
        ),
    ),
    marshall=PrimaryFieldMarshaller(),
    )


WeblogTopicSchema['allowDiscussion'].default=0


class WeblogTopic(BaseContent):
    """Weblog Topic"""
    topicImage = ''
    default_topic_image='default-topic-icon.jpg',
    schema = WeblogTopicSchema
Beispiel #7
0
class QuizResult(ATFolder):
    """Keeps together all the questions results for a specific student from a quiz in a specific lecture."""
   
    
    
    schema = ATFolderSchema.copy() + Schema((
        
        StringField('title',
                required=True,
                searchable=0,
                default='Quiz result',
                widget=StringWidget(
                    label='Title',
                    description='The main title of the tutorial.',
                    i18n_domain='plone'),
               
            ),
        BooleanField('openquest',
                     default=0,
                      widget=BooleanWidget(visible={'edit':'invisible', 'view':'invisible'}, ),),
        BooleanField('haveanswer',
                     default=0,
                      widget=BooleanWidget(visible={'edit':'invisible', 'view':'invisible'}, ),
                  ),
                     
        ImageField('CurrentQuestionImage',
                   #original_size=(600,600),
                   #max_size=(600,600),
                   sizes={ 'mini' : (80,80),
                           'normal' : (200,200),
                            'big' : (100,100),
                            'maxi' : (500,500),
                           },
                   widget=ImageWidget(label='quis question image',
                                      description='Image for the current question, displayed to the right of main text of the slide. Possible formats for uploaded images are: png, gif and jpeg.', 
                                      #macro='tutorwebimage',
                             # condition ='object/isImageFormat',
                                       )),
        ReferenceField('StudentQuestions',
                    #vocabulary="getAvailableCourses",
                    widget=ReferenceWidget(
                           label="quiz question",
                           description='A question student has been asked',
                           destination=".",
                           #destination_types=("QuestionResult",),
                           #visible={'edit':'invisible'},
                           
                           ),
                       multiValued=True,
                       relationship='hasQuestion',
                       allowed_types= ("InvisibleQuestion",),
                        
                   ),  

        ReferenceField('CurrentQuestion',
                    #vocabulary="getAvailableCourses",
                    widget=ReferenceWidget(
                           label="quiz question which is open",
                           description='A question student is being asked',
                           destination=".",
                           #destination_types=("QuestionResult",),
                           #visible={'edit':'invisible'},
                           
                           ),
                       multiValued=False,
                       relationship='hasOpenQuiz',
                       allowed_types= ("InvisibleQuestion",),
                        
                   ),  
        ComputedField('grade',
                  expression='context.computeGrade()',
                  widget=StringWidget(visible={'edit':'invisible','view':'invisible' },),
          
            ),
        IntegerField('totalattempts',
                     default='0',
                     widget=IntegerWidget(description='Number of times students has submitted a questions to quiz.', 
                                         visible={'edit':'invisible','view':'invisible'}, ),
                  ),
         IntegerField('correctattempts',
                        default='0',
                     widget=IntegerWidget(description='Number of times students has submitted a questions to quiz.', 
                                         visible={'edit':'invisible', 'view':'invisible'}, ),
                  ),
         FloatField('totscore',
                     default=0.0,
                     widget=IntegerWidget(description='total score so far.', 
                                       visible={'edit':'invisible','view':'invisible' },   ),
                  ),
           StringField('lasteightgrades',
                       default='[]',
                     widget=StringWidget(description='Number of times students has submitted a questions to quiz.', 
                                         visible={'edit':'invisible','view':'invisible' }, ),),
         StringField('studentRandId',
                       default='',
                     widget=StringWidget(description='random generated id to identify student.', 
                                         visible={'edit':'invisible','view':'invisible' }, ),
        ),
        StringField('studentId',
                       default='',
                     widget=StringWidget(description='login id of student.', 
                                         visible={'edit':'invisible','view':'invisible' }, ),                   
       ),

          #StringField('chosenquestid',
          #             default='',
          #           widget=StringWidget(description='Number of times students has submitted a questions to quiz.', 
          #                               visible={'view':'invisible', 'edit':'invisible'}, ),
          #        ),

       #StringField('chosenquestpath',
       #                default='',
       #              widget=StringWidget(description='Number of times students has submitted a questions to quiz.', 
        #                                 visible={'view': 'invisible', 'edit':'invisible'}, ),
         #         ),
       
     ))
    __implements__ = (ATFolder.__implements__)
    
    global_allow = False
    meta_type = 'QuizResult'          # zope type name
    portal_type = meta_type          # plone type name
    archetype_name = 'QuizResult' # friendly type name
    #_at_rename_after_creation = True  #automatically create id
    security = ClassSecurityInfo()
    
    # ATT: Make sure this work when create from twmigrate.py
    changed = True
    studentgrade = atapi.ATFieldProperty('grade')
    totalscore = atapi.ATFieldProperty('totscore')
    scoresofar = []
    # REMEMBER check if reversed or not when displayed????????
    lasteight = atapi.ATFieldProperty('lasteightgrades')
    quizattempts = atapi.ATFieldProperty('totalattempts')
    correctquizattempts = atapi.ATFieldProperty('correctattempts')
    chosenquestionid = atapi.ATFieldProperty('chosenquestid')
    chosenquestionpath = atapi.ATFieldProperty('chosenquestpath')
    #openquestion = atapi.ATFieldProperty('openquest')
    
    def __init__(self, oid=None, **kwargs):
        self.changed = True
        ATFolder.__init__(self, oid, **kwargs)
    
    # Must add:

    # getVocabulary is now in Lecture.py
    # returns the answers
    # getSelectedItem() in Lecture.py
    # questionIsInline in Lecture.py
    # isCorrect(item) in Lecture.py
    #
    # get chosen question already here
    #   then must transformR(True)
    #   then transformquizquestion
    #   getQuestionData()
    #   inlineAnswer()
    #  getQuestImg and getQuestionImageTag
    #
    def getQuestionResultForQuestion(self, question):
        qresults = question.getFolderContents(contentFilter={"portal_type": "QuestionResult"})
        return qresults[0].getObject()
    def getVocabulary(self):
        """return the possible answers formatted as vocabulary"""
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
            suggestedAnswerIds = (qr.getSuggestedAnswer())
            idl = DisplayList()
            ans = question.getAnswerDisplay().values()
       
            for id in suggestedAnswerIds:
                idl.add(id, ans[int(id)])
            return Vocabulary(idl, self, None)
        else:
            '''bad error no open question'''
            return ''
        
    def isCorrect(self, item):
        question = self.getCurrentQuestion()
        if (question):
            answers = question.getAnswerList()
            for row in answers:
                if (row['answerid'] == str(item)):
                    if (row['correct'] == '1'):
                        return True
            return False
        else:
            return False
    def startQuiz(self):
        '''student has asked for a question in quiz'''
        parent = aq_parent(self)
        lec = aq_parent(parent)
        if (DEBUG):
            tmpout = tempfile.mkdtemp()
            tex_fd, tex_absname = tempfile.mkstemp(dir=tmpout, suffix='.startQuiz')
            os.write(tex_fd, 'Starting selection of quiz question\n')
        
        hasq = self.openQuiz()
        msg = []
        msg.append(True)
        # taken care of that - set no answer and written to log
        # close that question
        if (hasq):
            msg.append('question replaced')
        else:
            msg.append('A question has been saved to quiz')
        msg.append(self.Creator())
        #parent = aq_parent(self)
        if (DEBUG):
            usable_question = lec.getQuizQuestion(tex_fd, True)
        else:
            usable_question = lec.getQuizQuestion()
        if (usable_question[0] == -1):
            '''no questions available'''
            msg[0] = False
            msg[1] = 'Sorry but no questions available in Lecture ' + usable_question[1] + '. Please contact your instructor if you believe you have found an error in the system, including the given error message'
            return msg
        elif(usable_question[0] == False):
            '''False could not create result for student'''
            msg[0] = False
            msg[1] = 'Fatal error could not start quiz in Lecture ' + usable_question[1] + '. Please contact your instructor if you believe you have found an error in the system, including the error message'
            return msg
        elif (usable_question[0] == -2):
            '''no answers set for the question'''
            msg[0] = False
            msg[1] = 'Sorry but no answers have been set for the selected question: ' + usable_question[2] + ' located in ' + usable_question[3] + '. Please try again or contact your instructor if you believe you have found and error in the system, including this message'
            return msg
        elif (usable_question[0] == -3):
            '''no answer set as correct in question'''
            msg[0] = False
            msg[1] = 'Sorry but no correct answer has been set to the selected question: ' + usable_question[2] + ' located in ' + usable_question[3] + '. Please try again or contact your instructor if you believe you have found an error in the system, including this error message'
            return msg
                
        else:
            '''have a valid question'''
            origquest = usable_question[0]
            if (DEBUG):
                os.write(tex_fd, '###########################\n')
                os.write(tex_fd, 'question used in quiz\n')
                os.write(tex_fd, str(origquest.getId()) + '\n')
                os.write(tex_fd, str(origquest.getRawQuestion()) + '\n')
        
            # set as invisble question with questionresult
            newq = self.createQuestion()
            qr = newq.createQuestionResult()
            # this info is repeated, but leave for now
            # FIXME
            if (len(self.getStudentRandId()) > 0):
                qr.setStudentId(self.getStudentRandId())
            else:
                # find from other location
                quiz = aq_parent(self)
                lec = aq_parent(quiz)
                tut = aq_parent(lec)
                dep = aq_parent(tut)
                mysite = aq_parent(dep)
                studentlistobj = mysite.getFolderContents(contentFilter={"portal_type": "StudentList"})
                if (len(studentlistobj) > 0):
                    studentlist = studentlistobj[0].getObject()
                    studentlist.addStudent(self.Creator())
                    randid = studentlist.getStudentIdNumber(self.Creator())
                    self.setStudentRandId(randid)
                    qr.setStudentId(randid)
            qr.setLecPath(lec.getPhysicalPath())
            # have created a quiz question with corresponding questuionresults
            # now set information from original question to quiz question
            # I probably don't need all the info but lets start by that
            questiontext = origquest.getRawQuestion()
            texttype = origquest.question.getContentType()
            mutated = origquest.getAnswerList()
            answertype = origquest.getAnswerFormat()
            newq.setQuestionText(questiontext, mimetype=texttype)
            newq.setAnswerList(mutated)
            newq.setAnswerFormat(answertype)
        
            # if its r or r/latex questions then need to be updated
            if (texttype == 'text/r' or texttype == 'text/r-latex'):
                newq.initializeObject()
               
            else:    
                newq.ans = origquest.ans
                newq.NOTAinQuestion = origquest.NOTAinQuestion
                newq.inlineanswer = origquest.inlineanswer
                newq.transformrquestion = origquest.transformrquestion
                newq.setQuizQuestion(origquest.getRawQuizQuestion(), mimetype=origquest.quizQuestion.getContentType())
                # add the image if any
                # ATT
                # asuming r-images do not contain image
                # would be generated within the r code itself?
                # HMMMMM
                img = origquest.getQuestionImage()
                newq.setQuestionImage(img)
            # add image url if any
            imgurl = origquest.getImageUrl()
            if (len(imgurl) > 0):
                newq.setImageUrl(imgurl)
            newq.numcorrect = origquest.numcorrect
            newq.numaskedfor = origquest.numaskedfor
            # need additionally to set:
            # quisQuestion
            
            
            newq.setQuizQuestionExplanation(origquest.getRawQuizQuestionExplanation(), mimetype='text/html')
           
           
            newq.setOriginalQuestion(origquest)
            
            # instead of using original question
            # use the invisible question
            suggestedanswers = newq.makeNewTest()
            grid = newq.getWrappedField('AnswerList')
            correctAnswerIds = []
            rowcorrect = grid.search(newq, correct='1')
            for row in rowcorrect:
                correctAnswerIds.append(row['answerid'])
            
            qr.setNewQuestion(suggestedanswers, correctAnswerIds, origquest.getPhysicalPath(), origquest.UID())
            
            
            if (len(suggestedanswers) > 0):
                '''set the first element in value as selected
                answer, anything will do'''
                qr.setSelectedAnswer(suggestedanswers[0])
                 
            else:
                '''what to do bad error'''
                msg[0] == False
                msg[1] = 'Fatal error'
                return msg
            qr.reindexObject()
            newq.reindexObject()
            self.reindexObject()
            if (DEBUG):
                os.write(tex_fd, str(newq.getId()) + '\n')
                os.write(tex_fd, str(newq.getRawQuestion()) + '\n')
                os.close(tex_fd)
            
            return msg
        
    def setTotalscore(self, val):
        self.setTotscore(val)
        #self.totalscore = val
    def setLastEightList(self, val):
        tmp = []
        for s in val:
            tmp.append(int(s))
        self.scoresofar = tmp
        tmpstr0 = str(val)
        tmpstr1 = tmpstr0.replace(',', '')
        self.setLasteightgrades(tmpstr1)
    def setLastEight(self, val):
        # value is a string
       
        tmpstr0 = val.replace(',', '')
        tmpstr1 = tmpstr0.replace('[', '')
        tmpstr2 = tmpstr1.replace(']','')
        scorelist = tmpstr2.split()
       
        tmp = []
        for s in scorelist:
            if (len(s) > 0):
                tmp.append(int(s))
        self.scoresofar = tmp
        self.setLasteightgrades(tmpstr0)
    def setScoresofar(self, val):
        self.scoresofar = val
    def getCreator(self):
        return self.Creator()
    def getSelectedAnswerToQuestion(self, question):
        #qr =  self.getStudentQuestionResult() 
        qr = self.getQuestionResultForQuestion(question)
        value = qr.getSelectedAnswer()
        #value = qr.getCandidateAnswer()
       
        answerdisplay = question.getAnswerDisplay()
        #index = int(value[0])
       
        return answerdisplay.getValue(value)
    def getSelectedItem(self):
        question = self.getCurrentQuestion()
        qr = self.getQuestionResultForQuestion(question)
        return qr.getSelectedAnswer()
    def questionIsInline(self):
        question = self.getCurrentQuestion()
        if (question > 0):
            return question.inlineAnswer()
        else:
            return False
    def getCandidateAnswerInTest(self):
        
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
            return (qr.getCandidateAnswer())
    security.declareProtected(PERMISSION_STUDENT, 'getOriginalQuestion')
    def getOriginalQuestion(self, quest):
        return quest.getOriginalQuestion()
        
    security.declareProtected(PERMISSION_STUDENT, 'getChosenQuestion')
    def getChosenQuestion(self):
        # always assume we are dealing with the last question
        question = self.getCurrentQuestion()
        if (question):
            return question
        else:
            return False
       
       
    def computeGrade(self):
        return float(self.getTotscore())
    def getSuggestedAnswerInTest(self):
        qr = self.getQuestionResultForQuestion(question)
        return (qr.getSuggestedAnswer())
    def setSelectedAnswerInTest(self, value):
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
            qr.setSelectedAnswer(value)
            qr.reindexObject()
    def unsetCandidateAnswerToQuestion(self):
        #qr =  self.getStudentQuestionResult()
        #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"})
        #qr = qresults[0].getObject()
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
            qr.unsetCandidateAnswer()
            qr.reindexObject()
    def setCandidateAnswerToQuestion(self, value):
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)               
            qr.gotAnswer()
            origquestion = question.getOriginalQuestion()
            qr.setCandidateAnswer([value], origquestion)
            qr.writetolog()
            correctans = qr.getCorrectAnswer()
            l = qr.getSuggestedans().split('\t')
            v = l[int(value)-1]
            if v in correctans:
                # this can lead ot database conflict error   
                origquestion.numcorrect = origquestion.numcorrect + 1
                correct = 1
            else:
                correct = 0
                #qr.gotAnswer()
            self.setScore(correct)
            qr.reindexObject()
    def computeAverageGrade(self):
        '''return average grade of student'''
        # compute the average grade of the student for this lecture
        # Average grade is at the moment computed according to points given
        # for the last eight answers:
        # Correct answer gives +1 points
        # Wrong answer gives -0.5 points
        # no answers given or all answers incorrect, grade starts at -0.5
        # Highest average grade is +1, all answers correct       
        # r = number correct answers of last m= 8 answers
        # average grade = ((-0.5)*(m-r)+r)/m
        # later more complex methods of computing grades need to be specified.
    
        numcorrect = 0
        for i in self.scoresofar:
            if float(i) > 0.0:
                numcorrect = numcorrect + 1
        # average grade is computed from the last 8 answers
        m = 8.0
        return ((-0.5)*(m-float(numcorrect))+float(numcorrect))/m
    def computeGrade1(self, remove):
        #tmpout = tempfile.mkdtemp()
        #tex_fd, tex_absname = tempfile.mkstemp(dir=tmpout, suffix='.computegradae1')
        #os.write(tex_fd, 'computegrade1\n')

        #tmp1 = self.getTotscore()
        #tmp = float(tmp1)
        #if (remove == 0):
        #    tmp = tmp + 0.5
        #else:
        #    tmp = tmp - 1.0
        #lastscore = self.scoresofar[0]
        #if (lastscore == 0):
        #    tmp = tmp - 0.5
        #else:
        #    tmp = tmp + 1.0
        
        total = 0.0
        for i in self.scoresofar:
            if float(i) == 0.0:
                total = total - 0.5
            else:
                total = total + 1
        self.setTotscore(total)
        
        #questions = self.getStudentQuestions()
        #portal_catalog = getToolByName(self, 'portal_catalog')
        ##questions = self.portal_catalog.searchResults(
        ##    portal_type = "InvisibleQuestion",
        ##    sort_on="Date",
        ##    path='/'.join(self.getPhysicalPath()),
        ##    )
        ##total = 0.0
        ##self.scoresofar = []
        ##for q in questions:
         ##   qr = self.getQuestionResultForQuestion(q.getObject())
         ##   if (qr.candidateAnswer == qr.correct):
          ##      total = total + 1.0
           ##     self.scoresofar.insert(0,1)
          ##  else:
          ##      total = total - 0.5
          ##      self.scoresofar.insert(0,0)
        ##self.setLasteightgrades(str(self.scoresofar))    
        ##self.setTotscore(total)
        self.reindexObject()
        #os.write(tex_fd, str(self.scoresofar) + '\n')
        #os.write(tex_fd, str(total) + '\n')
        #os.write(tex_fd, str(self.getPhysicalPath()) + '\n')
        #bla = '/'.join(self.getPhysicalPath())
        #os.write(tex_fd, str(bla) + '\n')
        #os.write(tex_fd, str(len(questions)) + '\n')
        
        return self.getLasteightgrades()    
    def getLastPoint(self):
        if (len(self.scoresofar) > 0):
            return self.scoresofar[0]
        else:
            return None
    security.declarePublic('setScore')
    def setScore(self, s):
        numinscore = 8
        if (len(self.scoresofar) == numinscore):
            tmp = self.scoresofar[numinscore-1]
            self.scoresofar = self.scoresofar[:numinscore-1]
            #self.scoresofar = self.scoresofar + [s]
            self.scoresofar.insert(0, s)
            self.setLasteightgrades(str(self.scoresofar))
            self.computeGrade1(tmp)
            #self.setLasteightgrades(str(self.scoresofar))
        else:
            tmp = float(self.getTotscore())
            if (s is 0):
                tmp = tmp - 0.5
            else:
                tmp = tmp + 1.0
            self.setTotscore(tmp)
            #tmp = 0           
            #self.computeGrade1(tmp)
            #self.scoresofar = self.scoresofar + [s]
            self.scoresofar.insert(0, s)
            self.setLasteightgrades(str(self.scoresofar))
            #self.computeGrade1(tmp)
        temp = self.getTotalattempts()
        temp = temp + 1
        self.setTotalattempts(temp)
        if (s is not 0):
            temp = self.getCorrectattempts()
            temp = temp + 1
            self.setCorrectattempts(temp)
        self.reindexObject()
    def closedQuiz(self):
        msg = []                                  
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
            if (not qr.hasSubmittedQuestion()):
                '''this could only happen if double click on button'''
                # what to do, student want to submit the same answer twice
                # no don't allow that
                msg.append(True)
                msg.append('Already answered')
                return msg
            else:
                msg.append(False)
                msg.append('Your answer has been saved.') 
                return msg
    def openQuiz(self):
        #qr = self.getStudentQuestionResult()
        # get the last question
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
            if (qr.hasSubmittedQuestion()):       
                #Set this question as false
                # For the moment the result is not restored
                # should print out results for wrong question
                 
                #self.setCandidateAnswerToQuestion('no answer')
                value = 'no answer'
                qr.setCandidateAnswer([value], question.getOriginalQuestion())
                correctans = qr.getCorrectAnswer()
                if value in correctans:
                    origquestion = question.getOriginalQuestion()
                    # this can lead to database conflict error
                    # WHAT TO DO????
                    #qobj = question[0].getObject()
                    origquestion.numcorrect = origquestion.numcorrect + 1
                    correct = 1
                else:
                    correct = 0
                qr.gotAnswer()
                self.setScore(correct)
                qr.reindexObject()
            #quizquestionstring = qr.getQuizInfo()
                self.writetolog(qr)       
                return True
            else:
                return False
        else:
            '''no question set yet'''
            return False
    security.declareProtected(PERMISSION_STUDENT, 'writetolog')
    def writetolog(self, qr):
        # FIXME !!!!
        # add code to check if dir exists and then create..
        logdir = productdir + '/log'
        if (not (os.path.exists(logdir))):
            os.mkdir(logdir)
        f = open(logdir+'/questionandanswer.txt','a')
        #qr = self.getStudentQuestionResult()
        #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"})
        #qr = qresults[0].getObject()
        text = qr.getQuizInfo()
        text = text + str(datetime.now()) + "\n"
        f.write(text)
        f.close()
        #os.system('echo ' + text + ' >> /tmp/twquiz/questionandanswer.txt')
    
    def setNewQuestionInTest(self, suggestedanswer, correctids, questpath, qid):
        
        #notify(NewQuizQuestionEvent(self, suggestedanswer, correctids, questpath, qid))
        question = self.getCurrentQuestion()
        if (question):
            qr = self.getQuestionResultForQuestion(question)
        #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"})
        #qr = qresults[0].getObject()
        #self.manage_delObjects(qresults)
        ##randid = qr.getStudid()
        ##lecpath = qr.getLecturepath()
        ##ids = self.objectIds() # Plone 3 or older
        #ids = folder.keys()      # Plone 4 or newer
        
        #ids = []
        ##if len(ids) > 0:
            #manage_delObject will mutate the list
            # so we cannot give it tuple returned by objectIds()
         ##   ids = list(ids)
         ##   self.manage_delObjects(ids)
        ##qr = self.createQuestionResult()
        ##qr.setStudentId(self.Creator())
        
        #parent = aq_parent(self)
        #lecpath = parent.getPhyisicalPath()
        ##qr.setLecturepath(lecpath)
        ##self.setStudentQuestionResult(qr)
        
        ##transaction.begin()

            qr.setNewQuestion(suggestedanswer, correctids, questpath, qid)
        ##qr._p_changed = True
        ##self._p_changed = True
        ##transaction.commit()
        #portal_catalog = getToolByName(self, 'portal_catalog')
        #students = portal_catalog.unrestrictedSearchResults({'portal_type' : 'StudentList'})
        #if (len(students) > 0):
        #    numlists = str(len(students))
            
        #    objid = students[0].getObject()
            #objid.addStudent(candidateId)
        #    randid = objid.getStudentIdNumber(self.Creator())
            
        ##qr.setStudentId(randid)
            qr.reindexObject()
    # This method is only called once after object creation.
    #security.declarePrivate('at_post_create_script')
    #def at_post_create_script(self):
    #    self.tryWorkflowAction("publish", ignoreErrors=True)
        
    def at_post_edit_script(self):
        '''function called after edit in the main edit view of the tutorial.'''
    #    self.changed = True
   
        #qresults = self.getFolderContents(contentFilter={"portal_type": "QuestionResult"})
        #if (len(qresults) > 0):
        #    qr = qresults[0].getObject()
        #    self.setStudentQuestionResult(qr) 
    #security.declarePrivate('tryWorkflowAction')
    #def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
    #    wtool = self.portal_workflow
    #    wf = wtool.getWorkflowsFor(self)[0]
    #    if wf.isActionSupported(self, action):
    #        if comment is None:
    #            #userId = getSecurityManager().getUser().getId()
    #            comment = 'State changed' 
    #        wtool.doActionFor(self, action, comment=comment)
    #    elif not ignoreErrors:
    #        raise TypeError('Unsupported workflow action %s for object %s.'
    #                        % (repr(action), repr(self)))
    #def getError(self):
    #    self.portal_factory.doCr()
    #def createQuestionResult(self):
    #    """Create a new questionresult object for student and initialize it."""
    #    typeName = 'QuestionResult'
    #    id=self.generateUniqueId(typeName)
    #    if self.portal_factory.getFactoryTypes().has_key(typeName):
    #        o = self.restrictedTraverse('portal_factory/' + typeName + '/' + id)
    #    else:
    #        newId = self.invokeFactory(id=id, type_name=typeName)
    #        if newId is None or newId == '':
    #            newId = id
    #        o=getattr(self, newId, None)
    
    #    if o is None:
    #        raise Exception
    #    o = self.portal_factory.doCreate(o, id)
    #    o.setTitle('Question result')
    #    o.reindexObject()
    #    return o
    def removeQuestion(self):
        portal_catalog = getToolByName(self, 'portal_catalog')
        questions = self.portal_catalog.searchResults(
            portal_type = "InvisibleQuestion",
            sort_on="Date",
            path='/'.join(self.getPhysicalPath()),
            )

        
        if (len(questions) > 7):
            '''should removes the oldest one'''
            self.manage_delObjects([questions[0].getId])

    def createQuestion(self):
        """Create a new questionresult object for student and initialize it."""
        # if neede delete a question
        # only keep 8 questons going
        typeName = 'InvisibleQuestion'
        self.removeQuestion()
        id=self.generateUniqueId(typeName)
        if self.portal_factory.getFactoryTypes().has_key(typeName):
            o = self.restrictedTraverse('portal_factory/' + typeName + '/' + id)
        else:
            newId = self.invokeFactory(id=id, type_name=typeName)
            if newId is None or newId == '':
                newId = id
            o=getattr(self, newId, None)
    
        if o is None:
            raise Exception
        o = self.portal_factory.doCreate(o, id)
        #o.setTitle('Question result')
        
        invquest = self.getStudentQuestions()
        invquest.append(o)
        self.setStudentQuestions(invquest)
        self.setCurrentQuestion(o)
        
        return o   
     loadFile
from Products.PloneArticle import proxy as pa_proxies
from Products.PloneArticle.field import InnerContentContainer

from Products.CMFPlone.utils import _createObjectByType

test_types_names = [
    'BaseInnerContentProxy',
    'FileInnerContentProxy',
    'ImageInnerContentProxy',
    'LinkInnerContentProxy',
]

schema = Schema((
    FileField('file'),
    ImageField('image'),
    StringField('remoteUrl'),
), )

test_proxies = (
    (
        'file',
        'FileInnerContentProxy',
    ),
    (
        'image',
        'ImageInnerContentProxy',
    ),
    (
        'link',
        'LinkInnerContentProxy',
Beispiel #9
0
        ),
    ReferenceField(
        'referencedContent',
        relationship='article_image',
        keepReferencesOnCopy=True,
        widget=ReferenceBrowserWidget(
            label='Referenced image',
            label_msgid='label_referenced_image',
            i18n_domain='plonearticle',
            ),
        ),
    ImageField(
        'attachedImage',
        attached_content=True,
        widget=ImageWidget(
            label='Attached image',
            label_msgid='label_attached_image',
            i18n_domain='plonearticle',
            ),
        ),
    ))

ImageInnerContentProxySchema['title'].required = False

class ImageInnerContentProxy(BaseFileContentProxy):
    """Proxy implementing IImageContent. It means this proxy has a getImage
    method.

    getImage returns attached image by default if existing otherwise returns
    the referenced content.
    """
Beispiel #10
0
class NewsletterRichReference(BaseContent, PropertyManager):

    portal_type = meta_type = 'NewsletterRichReference'
    archetype_name = 'Newsletter RichReference'  #this name appears in the 'add' box

    security = ClassSecurityInfo()

    schema = BaseSchema + Schema((
        TextField('text',
                  default='',
                  searchable=1,
                  required=1,
                  default_output_type='text/x-html-safe',
                  widget=RichWidget(label='Text',
                                    description='',
                                    label_msgid='label_text',
                                    description_msgid='help_text',
                                    i18n_domain="plone")),
        ImageField(
            name='image',
            widget=ImageWidget(
                label_msgid="label_preview_image",
                description=
                "This image is used as preview for the referenced objects.",
                description_msgid="help_image",
                label='Preview image',
                i18n_domain='plonegazette',
            ),
            storage=AttributeStorage(),
            sizes={
                'normal': (200, 130),
            }),
        ReferenceField(
            'references',
            languageIndependent=1,
            required=0,
            allowed_types=(),
            multiValued=1,
            relationship='references',
            widget=ReferenceBrowserWidget(
                label='References',
                description='Select one or more remote objects',
                label_msgid='label_references',
                description_msgid='help_references',
                i18n_domain='plonegazette',
                allow_search=1,
                allow_browse=1,
                show_indexes=0,
            ),
        ),
    ))

    # Make sure we get title-to-id generation when an object is created
    _at_rename_after_creation = True

    security.declarePublic('getObjects')

    def getObjects(self):
        """
        """
        return self.getReferences()

    security.declareProtected(View, 'imagetag')

    def imagetag(self, **kwargs):
        """Generate image tag using the api of the ImageField
        
        this method is needed because one must not access
        ImageField.tag in pagetemplates
        """
        if 'title' not in kwargs:
            kwargs['title'] = self.Title()
        return self.getField('image').tag(self, **kwargs)

    # uncommant lines below when you need
    factory_type_information = {
        'allowed_content_types': [],
        'global_allow': 0,
        'content_icon': 'NewsletterReference.gif',
        'immediate_view': 'newsletterreference_view',
        'filter_content_types': 0
    }

    actions = ({
        'id': 'view',
        'name': 'View',
        'category': 'object',
        'action': 'string:${object_url}/NewsletterRichReference_view',
        'permissions': ('View', )
    }, )
            description_msgid='help_options',
            i18n_domain='simplecartitem',
            columns={
                'option' : Column("Option", label_msgid='label_column_option'),
                'price_adjustment' : Column("Price Adjustment", label_msgid='label_column_priceadjustment'),
            },
        ),
    ),

    ImageField(
        name='image',
        default_output_type='image/jpeg',
        allowable_content_types=('image/*',),
        widget=ImageWidget(
            label='Image',
            description='Optionally upload a picture of the item',
            macro_view='flex_image',
            label_msgid='label_image',
            description_msgid='help_image',
            i18n_domain='simplecartitem',
        ),
    ),

    BooleanField(
        name='instock',
        index='FieldIndex:schema',
        default=True,
        widget=BooleanWidget(
            label='Is this item in stock?',
            description="""If it is not in stock, shoppers can see all the information about it, but cannot actually add it to their cart.""",
            label_msgid='label_instock',
Beispiel #12
0
class Sponsor(base.ATCTContent):
    """A sponsor for a tutor-web site, Department or a Tutorial which could typically be viewed on a tutor-web site or
    on printed content belonging to tutor-web. Can contain a logo, url and additional text as well as a title.
    A sponsor is implemented as base contents and uses interface, ISponsor.
    """

    schema = schemata.ATContentTypeSchema.copy() + Schema((
        StringField(
            'title',
            required=True,
            searchable=0,
            default='tutor-web sponsor',
            widget=StringWidget(label='Title',
                                description='A title for the sponsor.',
                                i18n_domain='plone'),
        ),
        StringField(
            'sponsorurl',
            searchable=0,
            default='http://sponsor-url.com',
            widget=StringWidget(
                label='Specify the web address of the sponsor',
                description='url for sponsor',
            ),
        ),
        TextField(
            'sponsortext',
            searchable=0,
            default='',
            default_content_type='text/plain',
            allowable_content_types=('text/plain'),
            widget=TextAreaWidget(
                label=
                'Additional text, more detailed information about the sponsor.',
                description='additional sponsor text',
            ),
        ),
        ImageField(
            'sponsorlogo',
            #original_size=(600,600),
            max_size=(200, 200),
            #sizes={ 'mini' : (80,80),
            #        'normal' : (200,200),
            #         'big' : (100,100),
            #         'maxi' : (500,500),
            #        },
            widget=ImageWidget(
                label='Sponsor logo',
                description='logo',
            ),
        ),
    ))

    implements(ISponsor)
    global_allow = False
    meta_type = 'Sponsor'  # zope type name
    portal_type = meta_type  # plone type name
    archetype_name = 'Sponsor'  # friendly type name
    _at_rename_after_creation = True  #automatically create id
    security = ClassSecurityInfo()

    def initializeObject(self):
        """Called after the creatation of Sponsor
           publish sponsor so it becomes available for viewing for all users
        """
        self.tryWorkflowAction("publish", ignoreErrors=True)

    security.declarePrivate('tryWorkflowAction')

    def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
        """publish sponsor"""
        wtool = self.portal_workflow
        wf = wtool.getWorkflowsFor(self)[0]
        if wf.isActionSupported(self, action):
            if comment is None:
                #userId = getSecurityManager().getUser().getId()
                comment = 'State changed'
            wtool.doActionFor(self, action, comment=comment)
        elif not ignoreErrors:
            raise TypeError('Unsupported workflow action %s for object %s.' %
                            (repr(action), repr(self)))

    def publishAll(self, typeofobject=None, originalobj=None):
        """publish sponsor"""
        self.tryWorkflowAction("publish", ignoreErrors=True)

    def haveChanged(self):
        parent = aq_parent(self)
        parenttype = parent.Type()
        # should use interface instead FIXME
        # only letting tutorial know of changes not lecture as no sponsor info in lectures at the moment
        if (parenttype == 'Tutorial'):
            parent.editedObject()
Beispiel #13
0
class Slide(ATFolder):
    """The basic slide represents a part of a lecture consisting of several slides.
    The basic component of the tutor-web is the slide. A slide can contain four main components:
    maintext, and main graphic, explanation text and explanation graphic. Additionally related material relevant to a given
slide can be set, detailed material, examples handouts and alternative material.
    """
    IMAGE_FORMATS = DisplayList((
        ('none', 'No image'),
        ('image', 'png, gif or jpeg'),
        ('fig', 'Fig'),
        ('r', 'R'),
        ('gnuplot', 'gnuplot'),
    ))

    schema = ATFolderSchema.copy() + Schema((
        StringField(
            'id',
            widget=StringWidget(
                description=
                'Change ID to become more readable. Slides appear in alphabetical order based on this value.',
                modes='edit',
            ),
            required=1,
        ),
        StringField(
            'title',
            required=True,
            searchable=0,
            default='Slide',
            widget=StringWidget(
                label='Title',
                description='The main title of the slide',
            ),
        ),
        ReferenceField(
            'ExtraMaterials',
            widget=ReferenceBrowserWidget(
                label="Extra material",
                description='Extra material connected to the slide material.',
                destination=".",
                destination_types=("File", ),
                visible={'edit': 'invisible'},
            ),

            #required = 1,
            multiValued=True,
            relationship='hasExtraMaterial',
            allowed_types=("File", ),
        ),
        BooleanField(
            "UpdateSlideText",
            default=1,
            widget=BooleanWidget(
                label='Update transformable slide text data',
                description='Check this box if you want transformable text data '
                'to be updated.',
            ),
        ),
        BooleanField(
            "SlideTextChanged",
            default=0,
            widget=BooleanWidget(
                label=
                'This is a control parameter to check if text has been changed recently.',
                #label_msgid='randomize_answer_order_label',
                description='Slide is updated if text has been changed.',
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'SlideText',
            searchable=0,
            default_content_type='text/latex',
            default_output_type='text/latex',
            accessor='SlideTextRaw',
            mutator='setSlideText',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'SlideTextView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
        StringField(
            'SlideImageFormat',
            vocabulary=IMAGE_FORMATS,
            default='none',
            widget=SelectionWidget(
                label='Image format',
                description=
                'Select the format of the main image. It can be a file with format png, gif or jpeg. Or the main image can be rendered from a text based image format of type R, Gnuplot or Fig.',
            ),
        ),
        TextField(
            'SlideImageText',
            allowable_content_types=(),
            default_output_type='text/plain',
            default_content_type='text/plain',
            widget=RichWidget(
                label='Image definnition',
                description=
                'Main image for slide, displayed to the right of main text of the slide. Possible formats are: fig, gnuplot and R.',
                allow_file_upload=1,
                macro='tutorwebtext_notkupu',
                #condition ='not:object/isImageFormat',
            ),
        ),
        StringField(
            'SlideImageCaption',
            widget=TextAreaWidget(
                label="Main image caption",
                description="Main image caption",
            ),
        ),
        ImageField(
            'SlideImage',
            #original_size=(600,600),
            max_size=(600, 600),
            #sizes={ 'mini' : (80,80),
            #        'normal' : (200,200),
            #         'big' : (100,100),
            #         'maxi' : (500,500),
            #        },
            widget=ImageWidget(
                label='Slide image',
                description=
                'Main image for slide, displayed to the right of main text of the slide. Possible formats for uploaded images are: png, gif and jpeg.',
                macro='tutorwebimage',
                # condition ='object/isImageFormat',
            )),
        ImageField(
            'SlideImageWWW',
            max_size=(300, 300),
            widget=ImageWidget(
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of explanation text. Possible formats for uploaded images are: png, gif and jpeg.',
                macro='tutorwebimage',
                modes='view',
                visible={
                    'view': 'invisible',
                    'edit': 'invisible'
                },
            ),
        ),
        TextField(
            'Explanation',
            searchable=0,
            accessor='ExplanationRaw',
            mutator='setExplanation',
            default_content_type='text/latex',
            default_output_type='text/latex',
            allowable_content_types=(
                'text/latex',
                'text/plain',
                'text/structured',
                'text/restructured',
                'text/html',
            ),
            widget=RichWidget(
                label='Explanation text',
                description=
                'Explantory material, displayed at the bottom of the slide',
                macro='tutorwebtext_notkupu_small',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'ExplanationView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                #macro='tutorwebtext_notkupu', allow_file_upload=1,
                visible={'edit': 'invisible'},
            ),
        ),
        StringField(
            'ExplanationImageFormat',
            vocabulary=IMAGE_FORMATS,
            default='none',
            widget=SelectionWidget(
                label='Image format',
                description=
                'Select the format of the explanation image. It can be a file with format png, gif or jpeg. Or the main image can be rendered from a text based image format of type R, Gnuplot or Fig.',
                #visible = {'edit': 'invisible'},
            ),
        ),
        TextField(
            'ExplanationImageText',
            allowable_content_types=(),
            default_output_type='text/plain',
            default_content_type='text/plain',
            widget=RichWidget(
                label='Image definition',
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of the explanation text. Possible formats are: fig, gnuplot and R',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
                #visible={'edit': 'invisible'},
            ),
        ),
        StringField(
            'ExplanationImageCaption',
            widget=TextAreaWidget(
                label="Explanation image caption",
                description="Explanation image caption",
                #visible={'edit': 'invisible'},
            ),
        ),
        ImageField(
            'ExplanationImage',
            max_size=(600, 600),
            widget=ImageWidget(
                label='Explanation image',
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of explanation text. Possible formats for uploaded images are: png, gif and jpeg.',
                #visible={'edit':'invisible'},
            ),
        ),
        ImageField(
            'ExplanationImageWWW',
            max_size=(200, 200),
            widget=ImageWidget(
                description=
                'Explanation image for slide, displayed at the bottom of the slide to the right of explanation text. Possible formats for uploaded images are: png, gif and jpeg.',
                macro='tutorwebimage',
                modes='view',
                visible={
                    'view': 'invisible',
                    'edit': 'invisible'
                },
            ),
        ),
        TextField(
            'Details',
            searchable=0,
            accessor='DetailsRaw',
            mutator='setDetails',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=(
                'text/latex',
                'text/plain',
                'text/structured',
                'text/restructured',
            ),
            widget=RichWidget(
                description=
                'Detailed information on the topic of the slide which can be accessed from the main slide view and is part of the pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'DetailsView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'Examples',
            searchable=0,
            accessor='ExamplesRaw',
            mutator='setExamples',
            default_content_type='text/latex',
            default_output_type='text/latex',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                description=
                'Examples for slide which can be accessed from the main slide view and is part of the pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'ExamplesView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                #macro='tutorwebtext_notkupu', allow_file_upload=1,
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'Alternative',
            searchable=0,
            accessor='AlternativeRaw',
            mutator='setAlternative',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=(
                'text/latex',
                'text/plain',
                'text/structured',
                'text/restructured',
                'text/html',
            ),
            widget=RichWidget(
                description=
                'Alternate educational material for slide which can be accessed from the main slide view.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'AlternativeView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'Handout',
            searchable=0,
            accessor='HandoutRaw',
            mutator='setHandout',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                description=
                'Handout for slide which can be accessed from the main slide view and is part of the pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'HandoutView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                #macro='tutorwebtext_notkupu', allow_file_upload=1,
                visible={'edit': 'invisible'},
            ),
        ),
        TextField(
            'SlideReference',
            searchable=0,
            accessor='SlideReferenceRaw',
            mutator='setSlideReference',
            default_content_type='text/latex',
            default_output_type='text/html',
            allowable_content_types=('text/latex', 'text/plain',
                                     'text/structured', 'text/restructured',
                                     'text/html'),
            widget=RichWidget(
                label='Reference',
                description=
                'Slide references are printed as part of a pdf document which can be displayed for each tutorial.',
                macro='tutorwebtext_notkupu',
                allow_file_upload=1,
            ),
        ),
        StringField(
            'SlideReferenceView',
            searchable=0,
            widget=StringWidget(
                label='Main text',
                description='Main content of the slide',
                macro='tutorwebtext_view',
                visible={'edit': 'invisible'},
            ),
        ),
    ))

    implements(IPrintable, ISlide, IOrderedTutorWebContent)
    security = ClassSecurityInfo()
    # This prevents the Questions from showing up as a portal content type
    global_allow = False
    meta_type = 'Slide'  # zope type name
    portal_type = meta_type  # plone type name
    archetype_name = 'Slide'  # friendly type name
    changed = True

    def useExplanationFig(self):
        return EXPLANATION_FIG

    def publishAll(self, typeofobject=None, originalobj=None):
        '''publich content'''
        # publish slide
        self.tryWorkflowAction("publish", ignoreErrors=True)

    def RawSlideText(self):
        return self.getRawSlideText()

    def RawExplanation(self):
        return self.getRawExplanation()

    def RawDetails(self):
        return self.getRawDetails()

    def RawExamples(self):
        return self.getRawExamples()

    def RawAlternative(self):
        return self.getRawAlternative()

    def RawHandout(self):
        return self.getRawHandout()

    def SlideTextRaw(self):
        return self.getSlideTextView()

    def ExplanationRaw(self):
        return self.getExplanationView()

    def DetailsRaw(self):
        return self.getDetailsView()

    def ExamplesRaw(self):
        return self.getExamplesView()

    def AlternativeRaw(self):
        return self.getAlternativeView()

    def HandoutRaw(self):
        return self.getHandoutView()

    def SlideReferenceRaw(self):
        return self.getSlideReferenceView()

    def setSlideText(self, value, **kwargs):
        '''set main slide text'''
        f = self.getField('SlideText')
        f.set(self, value, raw=True, **kwargs)
        self.setSlideTextView(value)

    def setSlideTextView(self, value):
        """update and render appropriate slide text material"""
        if (self.UpdateSlideText):
            f = self.getField('SlideTextView')
            text = self.getRawSlideText()
            type = self.SlideText.getContentType()
            value = self.transformText(type, text, 'slidetext')
            f.set(self, value)
            self.setSlideTextChanged(1)

    def setSlideTextView2(self, value):
        f = self.getField('SlideTextView')
        f.set(self, value)

    def setSlideTextView3(self, value):
        f = self.getField('SlideTextView')
        text = self.getRawSlideText()
        type = self.SlideText.getContentType()
        val = self.transformText(type, text, 'slidetext')
        f.set(self, val)

    def setSlideTextView1(self, value):
        f = self.getField('SlideTextView')
        text = self.getRawSlideText()
        type = self.SlideText.getContentType()
        val = self.transformText(type, text, 'slidetext')
        f.set(self, val)
        f1 = self.getField('ExplanationView')
        text1 = self.getRawExplanation()
        type1 = self.Explanation.getContentType()
        value1 = self.transformText(type1, text1, 'explanation')
        f1.set(self, value1)
        f2 = self.getField('DetailsView')
        text2 = self.getRawDetails()
        type2 = self.Details.getContentType()
        value2 = self.transformText(type2, text2, 'details')
        f2.set(self, value2)
        f3 = self.getField('ExamplesView')
        text3 = self.getRawExamples()
        type3 = self.Examples.getContentType()
        value3 = self.transformText(type3, text3, 'examples')
        f3.set(self, value3)
        f4 = self.getField('HandoutView')
        text4 = self.getRawHandout()
        type4 = self.Handout.getContentType()
        value4 = self.transformText(type4, text4, 'handout')
        f4.set(self, value4)
        f5 = self.getField('AlternativeView')
        text5 = self.getRawAlternative()
        type5 = self.Alternative.getContentType()
        value5 = self.transformText(type5, text5, 'alternative')
        f5.set(self, value5)
        f6 = self.getField('SlideReferenceView')
        text6 = self.getRawSlideReference()
        type6 = self.SlideReference.getContentType()
        value6 = self.transformText(type6, text6, 'reference')
        f6.set(self, value6)
        return 'success'

    def setExplanation(self, value, **kwargs):
        '''set explanation with raw data and explanation view with transformed data.'''
        f = self.getField('Explanation')
        f.set(self, value, raw=True, **kwargs)
        self.setExplanationView(value)

    def setExplanationView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('ExplanationView')
            text = self.getRawExplanation()
            type = self.Explanation.getContentType()
            value = self.transformText(type, text, 'explanation')
            f.set(self, value)
            self.setSlideTextChanged(1)

    def setDetails(self, value, **kwargs):
        '''set details text'''
        f = self.getField('Details')
        f.set(self, value, raw=True, **kwargs)
        self.setDetailsView(value)

    def setDetailsView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('DetailsView')
            text = self.getRawDetails()
            type = self.Details.getContentType()
            value = self.transformText(type, text, 'details')
            f.set(self, value)

    def setExamples(self, value, **kwargs):
        '''set examples text'''
        f = self.getField('Examples')
        f.set(self, value, raw=True, **kwargs)
        self.setExamplesView(value)

    def setExamplesView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('ExamplesView')
            text = self.getRawExamples()
            type = self.Examples.getContentType()
            value = self.transformText(type, text, 'examples')
            f.set(self, value)

    def setAlternative(self, value, **kwargs):
        '''set alternative text'''
        f = self.getField('Alternative')
        f.set(self, value, raw=True, **kwargs)
        self.setAlternativeView(value)

    def setAlternativeView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('AlternativeView')
            text = self.getRawAlternative()
            type = self.Alternative.getContentType()
            value = self.transformText(type, text, 'alternative')
            f.set(self, value)

    def setHandout(self, value, **kwargs):
        '''set handout text'''
        f = self.getField('Handout')
        f.set(self, value, raw=True, **kwargs)
        self.setHandoutView(value)

    def setHandoutView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('HandoutView')
            text = self.getRawHandout()
            type = self.Handout.getContentType()
            value = self.transformText(type, text, 'handout')
            f.set(self, value)

    def setSlideReference(self, value, **kwargs):
        '''set slide reference'''
        f = self.getField('SlideReference')
        f.set(self, value, raw=True, **kwargs)
        self.setSlideReferenceView(value)

    def setSlideReferenceView(self, value):
        if (self.UpdateSlideText):
            f = self.getField('SlideReferenceView')
            text = self.getRawSlideReference()
            type = self.SlideReference.getContentType()
            value = self.transformText(type, text, 'reference')
            f.set(self, value)

    def setSlideImageW(self):
        # only works for image for the moment
        value = self.getSlideImage()
        #calc heigth and width
        if (value):
            f = self.getField('SlideImageWWW')
            f.set(self, value)
        if (EXPLANATION_FIG):
            value = self.getExplanationImage()
            #calc heigth and width
            if (value):
                f = self.getField('ExplanationImageWWW')
                f.set(self, value)
        self.changed = False

    security.declarePublic('imageHasChanged')

    def imageHasChanged(self):
        return self.changed

    security.declarePublic('getSlideImageFactor')

    def getSlideImageFactor(self, maxw, maxh, fieldname):
        #ct, width, heigth = getImageInfo(self.getSlideImage())
        #value = self.getSlideImage()
        #calc heigth and width
        #f = self.getField('SlideImageWWW')
        #f.set(self, value)
        f = self.getField(fieldname)
        #w = f.getAttr(self, 'width')
        width, heigth = f.getSize(self)
        #width = 350
        #heigth = 120
        if width > maxw or \
                       heigth > maxh:
            factor = min(float(300) / float(width), float(300) / float(heigth))
        else:
            factor = 1

        return factor
        #return w
    def getImage(self):
        return 1, 1

    security.declarePrivate('initializeObject')

    def initializeObject(self):
        self.tryWorkflowAction("publish", ignoreErrors=True)
        parent = aq_parent(self)
        parent.orderObjects("id")
        parent.plone_utils.reindexOnReorder(parent)
        #self.reindexObject()
        self.changed = True
        self.renderImages()

    def editedObject(self, objtype=None):
        parent = aq_parent(self)
        parent.editedObject()
        self.renderImages()

    def renderImages(self):
        self.renderMainImage()
        if (EXPLANATION_FIG):
            self.renderExplanationImage()
        self.setSlideImageW()

    def setChanged(self, ch):
        #self.changed = ch
        lec = aq_parent(self)
        lec.setChanged(True)

    def setChanged(self, ch):
        #self.changed = ch
        lec = aq_parent(self)
        lec.setChanged(True)
        tut = aq_parent(lec)
        tut.setChanged(True)

    security.declarePrivate('tryWorkflowAction')

    def tryWorkflowAction(self, action, ignoreErrors=False, comment=None):
        wtool = self.portal_workflow
        wf = wtool.getWorkflowsFor(self)[0]
        if wf.isActionSupported(self, action):
            if comment is None:
                #userId = getSecurityManager().getUser().getId()
                comment = 'State changed'
            wtool.doActionFor(self, action, comment=comment)
        elif not ignoreErrors:
            raise TypeError('Unsupported workflow action %s for object %s.' %
                            (repr(action), repr(self)))

    def haveChanged(self):
        self.changed = True
        self.renderImages()

    security.declareProtected(View, 'transformSlideText')

    def transformSlideText(self, val):
        type = self.SlideText.getContentType()
        data = self.transformText(type, val, 'slidetext')
        self.setSlideTextView(data)

    security.declareProtected(View, 'updateTransformableText')

    def updateTransformableText(self):
        #use loop to go through everything...
        type = self.SlideText.getContentType()
        transformtext = self.getRawSlideText()
        data = self.transformText(type, transformtext, 'slidetext')
        #self.setSlideTextView(data)
        f = self.getField('SlideTextView')
        f.set(self, data)
        #self.SlideTextView.setContentType(self, 'text/html')
        type = self.Explanation.getContentType()
        transformtext = self.getRawExplanation()
        data = self.transformText(type, transformtext, 'explanation')
        self.setExplanationView(data)
        #self.ExplanationView.setContentType(self, 'text/html')
        type = self.Details.getContentType()
        transformtext = self.getRawDetails()
        data = self.transformText(type, transformtext, 'details')
        self.setDetailsView(data)
        #self.DetailsView.setContentType(self, 'text/html')
        type = self.Examples.getContentType()
        transformtext = self.getRawExamples()
        data = self.transformText(type, transformtext, 'examples')
        self.setExamplesView(data)
        #self.ExamplesView.setContentType(self, 'text/html')
        type = self.Alternative.getContentType()
        transformtext = self.getRawAlternative()
        data = self.transformText(type, transformtext, 'alternative')
        self.setAlternativeView(data)
        #self.AlternativeView.setContentType(self, 'text/html')
        type = self.Handout.getContentType()
        transformtext = self.getRawHandout()
        data = self.transformText(type, transformtext, 'handout')
        self.setHandoutView(data)
        #self.HandoutView.setContentType(self, 'text/html')
        type = self.SlideReference.getContentType()
        transformtext = self.getRawSlideReference()
        data = self.transformText(type, transformtext, 'reference')
        self.setSlideReferenceView(data)
        #self.SlideReferenceView.setContentType(self, 'text/html')

    security.declareProtected(View, 'transformText')

    def transformText(self, type, text, origin):

        trans = getToolByName(self, 'portal_transforms')

        data = trans.convertTo('text/html', text, mimetype=type, usedby=self)
        objects = data.getSubObjects()
        #mobj = data.getMetadata()['fileName']
        #for d in mobj:
        #    mobj = 'bla'
        counter = 0
        for x in objects:
            if hasattr(self, x):
                self.manage_delObjects([x])
            if hasattr(self, origin + x):
                self.manage_delObjects([origin + x])
            self.manage_addImage(origin + x, objects[x])

            container = self[origin + x]
            counter = counter + 1
            #tempname = container.getTitle()
            #container.setTitle('bla')
            container.manage_permission(
                permissions.View,
                roles=["Anonymous", "Authenticated", "Manager"],
                acquire=False)
            container.manage_permission(
                'Delete objects',
                roles=["Anonymous", "Authenticated", "Manager"],
                acquire=False)

        transformedtext = data.getData()
        if (type == 'text/latex'):
            path = '/'.join(self.getPhysicalPath())
            transformedtext = transformedtext.replace('SRC="',
                                                      'SRC="' + path + '/')
        for x in objects:
            transformedtext = transformedtext.replace(x, origin + x)
        self.reindexObject()

        return transformedtext

    def isImageFormat(self):
        image_type = self.getSlideimageFormat()
        if (image_type == 'image'):
            return True
        else:
            return False

    def renderMainImage(self):
        # should add checkes for if it empy, try, except code as well...
        image_type = self.getSlideImageFormat()
        rendered_image = 'DELETE_IMAGE'
        text = self.getSlideImageText()
        im = self.getSlideImage()
        if (im and (image_type != 'image')):
            self.setSlideImage(rendered_image)
        if ((len(text) > 0)
                and ((image_type == 'image') or (image_type == 'none'))):
            self.setSlideImageText('')

        if (image_type == 'fig'):
            rendered_image = self.renderImage(text, 'fig2dev -L png', '')

        elif (image_type == 'gnuplot'):
            HEADER = 'set terminal png color\n'
            rendered_image = self.renderImage(text, 'gnuplot', HEADER)
        elif (image_type == 'r'):

            #HEADER = 'png(file="/dev/stdout")\r\n'
            HEADER = 'bitmap(file="/dev/stdout")\r\n'
            #rendered_image = self.renderImage(text, 'R --slave', HEADER)
            rendered_image = self.renderRQuestion(text, HEADER)

        else:
            ''' do nothing for the moement '''
        if (image_type != 'image'):
            if (rendered_image != 'FAILURE'):
                try:
                    self.setSlideImage(rendered_image)
                    return True
                except:
                    return False
            else:
                return False
        else:
            ''' Return true if image type is png, jpeg, gif - no rendering needed.'''
            return True

    def renderExplanationImage(self):
        # should add checkes for if it empy, try, except code as well...
        image_type = self.getExplanationImageFormat()
        text = self.getExplanationImageText()
        rendered_image = 'DELETE_IMAGE'
        im = self.getExplanationImage()
        if (im and (image_type != 'image')):
            self.setExplanationImage(rendered_image)
        if ((len(text) > 0)
                and ((image_type == 'image') or (image_type == 'none'))):
            self.setExplanationImageText('')

        if (image_type == 'fig'):
            rendered_image = self.renderImage(text, 'fig2dev -L png', '')
        elif (image_type == 'gnuplot'):
            HEADER = 'set terminal png color\n'
            rendered_image = self.renderImage(text, 'gnuplot', HEADER)
        elif (image_type == 'r'):
            #HEADER = 'postscript(file="/dev/stdout")\r\n'
            #HEADER = 'png(file="/dev/stdout")\r\n'
            HEADER = 'bitmap(file="/dev/stdout")\r\n'
            #rendered_image = self.renderImage(text, 'R --slave', HEADER)
            rendered_image = self.renderRQuestion(text, HEADER)

            #if (rendered_image != 'DELETE_IMAGE'):
            #    rendered_image = twutils.ps2png(rendered_image)
        else:
            ''' do nothing for the moement '''
        if (image_type != 'image'):
            if (rendered_image != 'FAILURE'):
                self.setExplanationImage(rendered_image)
                return True
            else:
                return False
        else:
            return True

    security.declarePublic("renderRQuestion")

    def renderRQuestion(self, questiontext, HEADER):
        "jaso"
        tmpout = tempfile.mkdtemp()
        png_fd, png_absname = tempfile.mkstemp(dir=tmpout, suffix='.png')
        render = False

        setdatafiles = False
        if ('read' or 'source' in questiontext):
            tmpout1 = tempfile.mkdtemp()
            setdatafiles = True
            parent = aq_parent(self)
            extradata = parent.getAllExtraFiles()
            for ext in extradata:
                extra = ext.getObject()
                filename = extra.getTitle()
                extraid = extra.getId()
                f = open(tmpout1 + '/' + extraid, 'w')
                text = str(extra.getField('file').get(extra).data)
                for ex in extradata:
                    extobj = ex.getObject()
                    extid = extobj.getId()
                    if (extid in text):
                        text = text.replace(extid, '/' + tmpout1 + '/' + extid)
                f.write(text)
                f.close()
                if (extraid in questiontext):
                    text = str(extra.getField('file').get(extra).data)
                    questiontext = questiontext.replace(
                        extraid, '/' + tmpout1 + '/' + extraid)

        try:
            stdin, stdout = os.popen2('R --slave')
            try:
                stdin.write('bitmap(file="' + png_absname + '")\r\n')
            except:
                return 'FAILURE'
            try:
                stdin.write(questiontext)
                stdin.write('\r\n')
                stdin.write('dev.off()')
                try:
                    stdin.flush()
                    try:
                        stdin.close()
                        try:
                            s = stdout.read(
                            )  #s should be of the form %s|%s|%s|%s
                            try:
                                stdout.flush()
                                render = True
                                try:
                                    stdout.close()
                                except:
                                    ''' bla bla'''
                            except:
                                ''' bla bla'''

                        except:
                            ''' bla bla'''

                    except:
                        '''bla bla'''
                except:
                    '''bla bla'''
            except:
                '''bla bla'''
        except:
            render = False

        # if exists png file then read data and set
        # else set png file as empty DELETE_IMAGE
        try:
            mainimagefile = open(png_absname, 'r')
        except:
            '''Could not open image file??'''
            return 'FAILURE'
        try:
            mainimage = mainimagefile.read()
        except:
            '''could not read from image file???'''
            return 'FAILURE'
        mainimagefile.close()
        #try:
        #    if (mainimage):
        #        self.setQuestionImage(mainimage)
        #    else:
        #        self.setQuestionImage('DELETE_IMAGE')

        #except:
        #    '''????'''

        #if (render is True):
        #    s = s.split("|")
        #else:
        #    s = questiontext.split("|")

        #remove temporary directories created by the use of tempfile
        # and close file
        os.close(png_fd)
        try:
            shutil.rmtree(tmpout, True)
            if (setdatafiles):
                shutil.rmtree(tmpout1, True)
        except OSError, (errno, strerror):
            print "tutorial pdf:(shutil.rmtree %s) OSError[%s]: %s" % \
                     (tmpout, errno, strerror)

        if (mainimage):
            return mainimage
        else:
            return 'DELETE_IMAGE'
    TextField('body',
              default_content_type='text/html',
              default_output_type='text/html',
              allowable_content_types=(
                  'text/structured',
                  'text/html',
                  'text/plain',
                  'text/plain-pre',
              ),
              widget=TextAreaWidget(
                  label="Body",
                  description='The main body of the article',
              )),
    ImageField('portrait',
               widget=ImageWidget(
                   label="Portrait",
                   description='Small portrait of article subject',
               )),
    LinkField('seealso1',
              widget=LinkWidget(
                  label="See also 1",
                  description='A link to go to',
              )),
    LinkField('seealso2',
              widget=LinkWidget(
                  label="See also 2",
                  description='Another link to go to',
              )),
))