source: trunk/ExerciseMaterial.py @ 2035

Revision 2035, 8.7 KB checked in by pjotr, 12 years ago (diff)

Small fixes

Line 
1# Copyright 2006 by the LeMill Team (see AUTHORS)
2#
3# This file is part of LeMill.
4#
5# LeMill is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# LeMill is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with LeMill; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1
18
19from AccessControl import ClassSecurityInfo, getSecurityManager
20from Products.Archetypes.public import *
21from Products.CMFCore.utils import getToolByName
22
23from config import PROJECTNAME, MODIFY_CONTENT, VIEW
24from FieldsWidgets import ChapterField, ChapterWidget, StringWidget
25from SharedMetadata import *
26from Material import Material
27from permissions import MODIFY_CONTENT
28from random import shuffle
29from Products.LeMill import LeMillMessageFactory as _
30
31import re
32
33schema = BaseSchema + Schema((
34   ChapterField('bodyText',
35        accessor="getBodyText",
36        edit_accessor = 'getRawBodyText',
37        mutator = "setBodyText",
38        index='ZCTextIndex:schema',
39        index_method = 'getOnlyText',
40        searchable = True,
41        deleteEmptyChapters = False,
42        allowable_content_types = ['text/html',],
43        allow_file_upload = False,
44        default_output_type = 'text/x-html-captioned',
45        default_content_type = 'text/html',
46        default=[('','guidelines'),],
47        widget=ExerciseWidget(label = "Body text",
48            label_msgid = "label_bodytext",
49            i18n_domain = "lemill",
50            ),
51    ),
52))
53
54schema = schema + tags + language_schema + group_sharing + subject_area_schema + target_group_schema + license_schema + coverImage + lemill_metadata_mods + no_description + author_schema + deletionReason + version_schema + translation_schema + ieee_lom_lre_ap + latest_edit_schema + score
55
56schema = schema.copy()
57schema.moveField('rights', pos='bottom')
58schema.moveField('language', after='bodyText')
59schema['title'].required = True
60
61fill_in_the_blanks=re.compile(r"""(?P<filler>({.*?})+)""",  re.IGNORECASE)
62
63class ExerciseMaterial(Material):
64    """Exercise page"""
65
66    schema = schema
67
68    meta_type = "ExerciseMaterial"
69    archetype_name = "ExerciseMaterial"
70
71    security = ClassSecurityInfo()
72    security.declareObjectPublic()
73
74    security.declarePrivate('manage_afterAdd')
75    def manage_afterAdd(self, item, container):
76        Material.manage_afterAdd(self, item, container)
77
78        if not hasattr(item.aq_base, 'left_slots'):
79            self._setProperty('left_slots', ['here/portlet_material_actions/macros/portlet',], 'lines')
80        else:
81            self._updateProperty('left_slots', ['here/portlet_material_actions/macros/portlet',])
82
83    def getOnlyText(self):
84        field=self.getField('bodyText')
85        values = field.get(self)
86        dump= '\n'.join([x[0] for x in values if not x[1]!='piece'])
87        return dump
88
89    def isCorrectAnswer(self, chapter, answer_index):
90        """ given a chapter having a multiple choice question, is this answer in correct answers? """
91        return answer_index < len(chapter[1])
92       
93
94    security.declareProtected(MODIFY_CONTENT,'delChapter')
95    def delChapter(self, REQUEST):
96        """ delete chapter """
97        field = self.getField('bodyText')
98        field.delChapter(self, int(REQUEST.get('delete')))
99        return REQUEST.RESPONSE.redirect(self.absolute_url()+'/edit')
100
101    def getAllAnswers(self, chapter):
102        """ Will return the list of the shuffled combined correct and incorrect answers """
103        # Chapter should have the structure: [question,correct_list,incorrect_list]
104        all_answers = chapter[1] + chapter[2]
105        extended_answers = []
106        for numerated_answer in enumerate(all_answers):
107            extended_answers.append(numerated_answer)
108        shuffle(extended_answers)
109        return extended_answers
110
111    def get_values_from_fitbs(self, chapter_index):
112        """ find words in {}:s and return them as dict """
113       
114        text=self.getBodyText()
115        text=text[chapter_index][0]
116        matches=fill_in_the_blanks.findall(text)
117        results={}
118        index=0
119        for m in matches:
120            answer=m[0]
121            answer=answer.strip(' {}')
122            answer=answer.split('}{')
123            results['exercise_%s_answer_%s' % (chapter_index, index)]=answer
124            index=index+1
125        return results
126           
127    def replace_blanks_with_input_tag(self, chapter_index, answers=True, readonly=True):
128        """ find words in { } and replace them with input boxes """
129        replacement="""<input type="text" value="%s"%s name="exercise_%s_answer_%s" id="exercise_%s_answer_%s" />"""
130        self.iterator=0
131       
132        def rep(match):
133            answer_index=self.iterator
134            if answers:
135                value=match.group('filler').strip(' {}')
136                value=value.replace('}{','/')
137            else:
138                value=""
139            self.iterator=self.iterator+1
140            return replacement % (value, readonly, chapter_index, answer_index, chapter_index, answer_index)
141
142        if readonly:
143            readonly=' readonly="1"'
144        else:
145            readonly=''           
146        text=self.getBodyText()
147        text=text[chapter_index][0]
148        text=fill_in_the_blanks.sub(rep, text)
149        del self.iterator
150        return text
151
152    def sendAnswers(self, REQUEST):
153        """ Send e-mail to a teacher """
154        putils = getToolByName(self,'plone_utils')
155        mhost = putils.getMailHost()
156        message = ''
157        students_name = ''
158        students_email = ''
159        teachers_email = ''
160        if REQUEST.has_key('your_name'):
161            students_name = REQUEST.get('your_name')
162        if REQUEST.has_key('students_email'):
163            students_email = REQUEST.get('students_email')
164        if REQUEST.has_key('teachers_email'):
165            teachers_email = REQUEST.get('teachers_email')
166        if not teachers_email or not students_email or not students_name:
167            msg = _(u"You have not provided enough information to send an e-mail.")
168            putils.addPortalMessage(msg)
169            return REQUEST.RESPONSE.redirect(self.absolute_url())
170        # Now we should compose the message body
171        exercise_body = self.getBodyText()
172        message += "This is an answer of %s to the exercise %s at %s\n\n\n" % (students_name, self.Title(), self.absolute_url())
173        # XXX Message body should be composed question by question
174        for i in range(1,len(exercise_body)):
175            if exercise_body[i][1] == 'multiple_choices':
176                answered_right = []
177                answered_wrong = []
178                question_text = exercise_body[i][0][0]
179                correct_answers = exercise_body[i][0][1]
180                all_answers = exercise_body[i][0][1] + exercise_body[i][0][2]
181                for a in all_answers:
182                    answer_value = REQUEST.get('bodyText_'+str(i)+'_'+str(a))
183                    if answer_value == 'checked' and a in correct_answers:
184                        answered_right.append(a)
185                    elif answer_value == 'checked' and a not in correct_answers:
186                        answered_wrong.append(a)
187                message += "\n\n\n%s\n\nAnswered right: %s out of %s.\nRight answers given: %s. Wrong answers given: %s." % (question_text, len(answered_right), len(all_answers), ','.join(answered_right), ','.join(answered_wrong))
188            elif exercise_body[i][1] == 'fill_in_the_blanks':
189                # XXX Do some stuff
190                print "Lalala"
191            elif exercise_body[i][1] == 'open_ended':
192                question_text = exercise_body[i][0]
193                students_answer = REQUEST.get('bodyText_'+str(i))
194                message += "\n\n\n%s\n\n%s" % (question_text, students_answer)
195        message += "\n\n\nBest regards,\nLeMill"
196       
197        message_from = "%s <%s>" % (students_name, students_email)
198        message_subject = "Answers to exercise %s by %s" % (self.Title(), students_name)
199        try:
200            mhost.send(message, mto=teachers_email, mfrom=message_from, subject=message_subject)
201            msg = _(u"The e-mail has been sent to a teacher.")
202            putils.addPortalMessage(msg)
203            return REQUEST.RESPONSE.redirect(self.absolute_url())
204        except:
205            msg = _(u"The e-mail could not be sent.")
206            putils.addPortalMessage(msg)
207            return REQUEST.RESPONSE.redirect(self.absolute_url())
208
209
210
211
212registerType(ExerciseMaterial, PROJECTNAME)
Note: See TracBrowser for help on using the repository browser.