source: trunk/ExerciseMaterial.py @ 2083

Revision 2083, 12.7 KB checked in by tarmo, 12 years ago (diff)

Closes #1558. If captcha is not enabled, then nobody can pass
the captcha humanity test. So for exercises to work (as in sending
email) captcha must be enabled.

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, to_unicode
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 x[1] not in ['piece', 'multiple_choices']])
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+=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 replace_blanks_with_your_answers(self, text, your_answerdict, i):
153        """ find braces {text} and add own answers before them in brackets [mytext]{text} """
154        self.iterator=0
155       
156        def rep(match):
157            value=match.group('filler')           
158            your_answer=your_answerdict.get('exercise_%s_answer_%s' % (i, self.iterator), '')
159            self.iterator+=1
160            return '[%s]%s' % (your_answer, value)
161        text=fill_in_the_blanks.sub(rep, text)
162        del self.iterator
163        return text
164
165
166
167    def sendAnswers(self, REQUEST):
168        """ Send e-mail to a teacher """
169        putils = getToolByName(self,'plone_utils')
170        letool = getToolByName(self,'lemill_tool')
171        mhost = putils.getMailHost()
172        mbody = u''
173        students_name = REQUEST.get('your_name','')
174        students_email = REQUEST.get('students_email','')
175        teachers_email = REQUEST.get('teachers_email','')
176
177        if not students_email or (teachers_email and not students_name):
178            msg = _(u"You have not provided enough information to send an e-mail.")
179            putils.addPortalMessage(msg, type='warn')
180            return REQUEST.RESPONSE.redirect(self.absolute_url())
181
182        if not self.lemill_tool.validateCaptcha(REQUEST.get('captcha')):
183            msg = _(u"Invalid answer for humanity test.")
184            putils.addPortalMessage(msg, type='warn')
185            return REQUEST.RESPONSE.redirect(self.absolute_url())
186       
187        exercise_body = self.getBodyText()
188
189
190        # Now we should compose the message body       
191        if teachers_email:
192            mbody += _(u"""
193Hello,
194
195%(name)s has completed the LeMill exercise '%(exercise_title)s' at %(exercise_url)s.
196""") % {'name':to_unicode(students_name), 'exercise_title':to_unicode(self.Title()), 'exercise_url':to_unicode(self.absolute_url())}
197        else:
198            mbody += _(u"""
199Hello %(name)s,
200
201You have completed the LeMill exercise '%(exercise_title)s' at %(exercise_url)s.
202""") % {'name':to_unicode(students_name), 'exercise_title':to_unicode(self.Title()), 'exercise_url':to_unicode(self.absolute_url())}
203
204        mbody += _(u"If you are surprised by getting this e-mail, you can simply ignore and delete it as someone may have accidentally inserted your address as a recipient.")
205        # Message body is composed chapter by chapter
206        i=0
207        for (chapter_text, chapter_type) in exercise_body:
208            if chapter_type=='multiple_choices':
209                answered_right = 0
210                answered_wrong = 0
211                question = chapter_text[0]
212                correct_answers = chapter_text[1]
213                answers_total = correct_answers+chapter_text[2]
214                my_answers=[]
215                # Correct answers have small index number
216                for a in range(len(correct_answers)):
217                    answer_value = REQUEST.get('exercise_%s_checkbox_%s' % (i,a),'')
218                    if answer_value:
219                        my_answers.append(answers_total[a])
220                        answered_right+=1
221                    else:
222                        answered_wrong+=1
223                # These are all wrong answers
224                for a in range(len(correct_answers),len(answers_total)):
225                    answer_value = REQUEST.get('exercise_%s_checkbox_%s' % (i,a),'')
226                    if answer_value:
227                        my_answers.append(answers_total[a])
228                        answered_wrong+=1
229                    else:
230                        answered_right+=1
231                percentage=int((float(answered_right)/(answered_wrong+answered_right))*100)
232                mbody += _(u"""
233
234Your answer to question '%(question)s' was:
235%(my_answers)s
236The correct answer is:
237%(correct_answers)s
238You got %(percentage)s%% correct!
239""") % {'question':to_unicode(question), 'my_answers':to_unicode(', '.join(my_answers)), 'correct_answers':to_unicode(', '.join(correct_answers)), 'percentage':percentage}
240
241            elif chapter_type == 'fill_in_the_blanks':
242                correct_answer_dict=self.get_values_from_fitbs(i)
243                correct_answers_n=0
244                my_answer_dict={}
245                all_answers_n=len(correct_answer_dict.keys())
246                for it in range(all_answers_n):
247                    my_answer=REQUEST.get('exercise_%s_answer_%s' % (i,it),'')
248                    correct_answer=[to_unicode(c.strip()) for c in correct_answer_dict['exercise_%s_answer_%s' % (i,it)]]
249                    if to_unicode(my_answer.strip()) in correct_answer:
250                        correct_answers_n+=1
251                    my_answer_dict['exercise_%s_answer_%s' % (i,it)]=my_answer
252                exercise_text=self.replace_blanks_with_your_answers(chapter_text, my_answer_dict, i)
253                exercise_text=letool.html_to_text(exercise_text)
254                mbody += _(u"""
255Answer entered by student is in the square brackets. The correct answer is in the logical brackets.
256In the following fill-in-the-blanks exercise your answers and correct answers were:
257%(exercise_text)s
258
259You got %(correct_answers_n)s/%(all_answers_n)s correct!
260""") % {'exercise_text':to_unicode(exercise_text), 'correct_answers_n':correct_answers_n, 'all_answers_n':all_answers_n}           
261
262            elif chapter_type == 'open_ended':
263                students_answer = REQUEST.get('exercise_%s_answer' % i, '')
264                mbody += _(u"""
265Your answer to question '%(question)s' was:
266%(answer)s
267
268Your teacher will give you feedback on your answer.
269""") % {'question':to_unicode(chapter_text), 'answer':to_unicode(students_answer)}
270            i+=1 # <--- remember to increase index
271           
272        mbody += _(u"\n\nBest regards, LeMill")
273        mbody = mbody.encode('utf-8')
274
275        if teachers_email:
276            message_from = "%s <%s>" % (students_name, students_email)
277            message_subject = "LeMill exercise '%s' by %s" % (self.Title(),students_name)
278            try:
279                mhost.secureSend(mbody, mto=teachers_email, mfrom=message_from, subject=message_subject, mcc=students_email, charset='utf-8')
280                msg = _(u"The e-mail has been sent to you and a teacher.")
281                putils.addPortalMessage(msg)
282                return REQUEST.RESPONSE.redirect(self.absolute_url())
283            except:
284                msg = _(u"The e-mail could not be sent.")
285                putils.addPortalMessage(msg, type='warn')
286                return REQUEST.RESPONSE.redirect(self.absolute_url())
287        else:
288            message_from = "%s <%s>" % ('LeMill', students_email)
289            message_subject = "LeMill exercise '%s' feedback" % (self.Title())
290            try:
291                mhost.secureSend(mbody, mto=students_email, mfrom=message_from, subject=message_subject, charset='utf-8')
292                msg = _(u"The e-mail has been sent to you.")
293                putils.addPortalMessage(msg)
294                return REQUEST.RESPONSE.redirect(self.absolute_url())
295            except:
296                msg = _(u"The e-mail could not be sent.")
297                putils.addPortalMessage(msg, type='warn')
298                return REQUEST.RESPONSE.redirect(self.absolute_url())
299
300
301registerType(ExerciseMaterial, PROJECTNAME)
Note: See TracBrowser for help on using the repository browser.