MDL-9628 At the suggestion of Tim Hunt, interchanged the position of grade letter...
[moodle-pu.git] / mod / hotpot / lib.php
blob058565103e8c97a0dab0e8dea54ad8e88ec7ecc5
1 <?PHP // $Id$
3 //////////////////////////////////
4 /// CONFIGURATION settings
6 if (!isset($CFG->hotpot_showtimes)) {
7 set_config("hotpot_showtimes", 0);
9 if (!isset($CFG->hotpot_excelencodings)) {
10 set_config("hotpot_excelencodings", "");
13 //////////////////////////////////
14 /// CONSTANTS and GLOBAL VARIABLES
16 $CFG->hotpotroot = "$CFG->dirroot/mod/hotpot";
17 $CFG->hotpottemplate = "$CFG->hotpotroot/template";
18 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
19 $CFG->hotpotismobile = preg_match('/Alcatel|ATTWS|DoCoMo|Doris|Hutc3G|J-PHONE|Java|KDDI|KGT|LGE|MOT|Nokia|portalmmm|ReqwirelessWeb|SAGEM|SHARP|SIE-|SonyEricsson|Teleport|UP\.Browser|UPG1|Wapagsim/', $_SERVER['HTTP_USER_AGENT']);
20 } else {
21 $CFG->hotpotismobile = false;
24 define("HOTPOT_JS", "$CFG->wwwroot/mod/hotpot/hotpot-full.js");
26 define("HOTPOT_NO", "0");
27 define("HOTPOT_YES", "1");
29 define ("HOTPOT_TEXTSOURCE_QUIZ", "0");
30 define ("HOTPOT_TEXTSOURCE_FILENAME", "1");
31 define ("HOTPOT_TEXTSOURCE_FILEPATH", "2");
32 define ("HOTPOT_TEXTSOURCE_SPECIFIC", "3");
34 define("HOTPOT_LOCATION_COURSEFILES", "0");
35 define("HOTPOT_LOCATION_SITEFILES", "1");
37 $HOTPOT_LOCATION = array (
38 HOTPOT_LOCATION_COURSEFILES => get_string("coursefiles"),
39 HOTPOT_LOCATION_SITEFILES => get_string("sitefiles"),
42 define("HOTPOT_OUTPUTFORMAT_BEST", "1");
43 define("HOTPOT_OUTPUTFORMAT_V3", "10");
44 define("HOTPOT_OUTPUTFORMAT_V4", "11");
45 define("HOTPOT_OUTPUTFORMAT_V5", "12");
46 define("HOTPOT_OUTPUTFORMAT_V5_PLUS", "13");
47 define("HOTPOT_OUTPUTFORMAT_V6", "14");
48 define("HOTPOT_OUTPUTFORMAT_V6_PLUS", "15");
49 define("HOTPOT_OUTPUTFORMAT_FLASH", "20");
50 define("HOTPOT_OUTPUTFORMAT_MOBILE", "30");
52 $HOTPOT_OUTPUTFORMAT = array (
53 HOTPOT_OUTPUTFORMAT_BEST => get_string("outputformat_best", "hotpot"),
54 HOTPOT_OUTPUTFORMAT_V6_PLUS => get_string("outputformat_v6_plus", "hotpot"),
55 HOTPOT_OUTPUTFORMAT_V6 => get_string("outputformat_v6", "hotpot"),
56 HOTPOT_OUTPUTFORMAT_V5_PLUS => get_string("outputformat_v5_plus", "hotpot"),
57 HOTPOT_OUTPUTFORMAT_V5 => get_string("outputformat_v5", "hotpot"),
58 HOTPOT_OUTPUTFORMAT_V4 => get_string("outputformat_v4", "hotpot"),
59 HOTPOT_OUTPUTFORMAT_V3 => get_string("outputformat_v3", "hotpot"),
60 HOTPOT_OUTPUTFORMAT_FLASH => get_string("outputformat_flash", "hotpot"),
61 HOTPOT_OUTPUTFORMAT_MOBILE => get_string("outputformat_mobile", "hotpot"),
63 $HOTPOT_OUTPUTFORMAT_DIR = array (
64 HOTPOT_OUTPUTFORMAT_V6_PLUS => 'v6',
65 HOTPOT_OUTPUTFORMAT_V6 => 'v6',
66 HOTPOT_OUTPUTFORMAT_V5_PLUS => 'v5',
67 HOTPOT_OUTPUTFORMAT_V5 => 'v5',
68 HOTPOT_OUTPUTFORMAT_V4 => 'v4',
69 HOTPOT_OUTPUTFORMAT_V3 => 'v3',
70 HOTPOT_OUTPUTFORMAT_FLASH => 'flash',
71 HOTPOT_OUTPUTFORMAT_MOBILE => 'mobile',
73 foreach ($HOTPOT_OUTPUTFORMAT_DIR as $format=>$dir) {
74 if (is_file("$CFG->hotpottemplate/$dir.php") && is_dir("$CFG->hotpottemplate/$dir")) {
75 // do nothing ($format is available)
76 } else {
77 // $format is not available, so remove it
78 unset($HOTPOT_OUTPUTFORMAT[$format]);
79 unset($HOTPOT_OUTPUTFORMAT_DIR[$format]);
82 define("HOTPOT_NAVIGATION_BAR", "1");
83 define("HOTPOT_NAVIGATION_FRAME", "2");
84 define("HOTPOT_NAVIGATION_IFRAME", "3");
85 define("HOTPOT_NAVIGATION_BUTTONS", "4");
86 define("HOTPOT_NAVIGATION_GIVEUP", "5");
87 define("HOTPOT_NAVIGATION_NONE", "6");
89 $HOTPOT_NAVIGATION = array (
90 HOTPOT_NAVIGATION_BAR => get_string("navigation_bar", "hotpot"),
91 HOTPOT_NAVIGATION_FRAME => get_string("navigation_frame", "hotpot"),
92 HOTPOT_NAVIGATION_IFRAME => get_string("navigation_iframe", "hotpot"),
93 HOTPOT_NAVIGATION_BUTTONS => get_string("navigation_buttons", "hotpot"),
94 HOTPOT_NAVIGATION_GIVEUP => get_string("navigation_give_up", "hotpot"),
95 HOTPOT_NAVIGATION_NONE => get_string("navigation_none", "hotpot"),
98 define("HOTPOT_JCB", "1");
99 define("HOTPOT_JCLOZE", "2");
100 define("HOTPOT_JCROSS", "3");
101 define("HOTPOT_JMATCH", "4");
102 define("HOTPOT_JMIX", "5");
103 define("HOTPOT_JQUIZ", "6");
104 define("HOTPOT_TEXTOYS_RHUBARB", "7");
105 define("HOTPOT_TEXTOYS_SEQUITUR", "8");
107 $HOTPOT_QUIZTYPE = array(
108 HOTPOT_JCB => 'JCB',
109 HOTPOT_JCLOZE => 'JCloze',
110 HOTPOT_JCROSS => 'JCross',
111 HOTPOT_JMATCH => 'JMatch',
112 HOTPOT_JMIX => 'JMix',
113 HOTPOT_JQUIZ => 'JQuiz',
114 HOTPOT_TEXTOYS_RHUBARB => 'Rhubarb',
115 HOTPOT_TEXTOYS_SEQUITUR => 'Sequitur'
118 define("HOTPOT_JQUIZ_MULTICHOICE", "1");
119 define("HOTPOT_JQUIZ_SHORTANSWER", "2");
120 define("HOTPOT_JQUIZ_HYBRID", "3");
121 define("HOTPOT_JQUIZ_MULTISELECT", "4");
123 define("HOTPOT_GRADEMETHOD_HIGHEST", "1");
124 define("HOTPOT_GRADEMETHOD_AVERAGE", "2");
125 define("HOTPOT_GRADEMETHOD_FIRST", "3");
126 define("HOTPOT_GRADEMETHOD_LAST", "4");
128 $HOTPOT_GRADEMETHOD = array (
129 HOTPOT_GRADEMETHOD_HIGHEST => get_string("gradehighest", "quiz"),
130 HOTPOT_GRADEMETHOD_AVERAGE => get_string("gradeaverage", "quiz"),
131 HOTPOT_GRADEMETHOD_FIRST => get_string("attemptfirst", "quiz"),
132 HOTPOT_GRADEMETHOD_LAST => get_string("attemptlast", "quiz"),
135 define("HOTPOT_STATUS_INPROGRESS", "1");
136 define("HOTPOT_STATUS_TIMEDOUT", "2");
137 define("HOTPOT_STATUS_ABANDONED", "3");
138 define("HOTPOT_STATUS_COMPLETED", "4");
140 $HOTPOT_STATUS = array (
141 HOTPOT_STATUS_INPROGRESS => get_string("inprogress", "hotpot"),
142 HOTPOT_STATUS_TIMEDOUT => get_string("timedout", "hotpot"),
143 HOTPOT_STATUS_ABANDONED => get_string("abandoned", "hotpot"),
144 HOTPOT_STATUS_COMPLETED => get_string("completed", "hotpot"),
147 define("HOTPOT_FEEDBACK_NONE", "0");
148 define("HOTPOT_FEEDBACK_WEBPAGE", "1");
149 define("HOTPOT_FEEDBACK_FORMMAIL", "2");
150 define("HOTPOT_FEEDBACK_MOODLEFORUM", "3");
151 define("HOTPOT_FEEDBACK_MOODLEMESSAGING", "4");
153 $HOTPOT_FEEDBACK = array (
154 HOTPOT_FEEDBACK_NONE => get_string("feedbacknone", "hotpot"),
155 HOTPOT_FEEDBACK_WEBPAGE => get_string("feedbackwebpage", "hotpot"),
156 HOTPOT_FEEDBACK_FORMMAIL => get_string("feedbackformmail", "hotpot"),
157 HOTPOT_FEEDBACK_MOODLEFORUM => get_string("feedbackmoodleforum", "hotpot"),
158 HOTPOT_FEEDBACK_MOODLEMESSAGING => get_string("feedbackmoodlemessaging", "hotpot"),
160 if (empty($CFG->messaging)) { // Moodle 1.4 (and less)
161 unset($HOTPOT_FEEDBACK[HOTPOT_FEEDBACK_MOODLEMESSAGING]);
164 define("HOTPOT_DISPLAYNEXT_QUIZ", "0");
165 define("HOTPOT_DISPLAYNEXT_COURSE", "1");
166 define("HOTPOT_DISPLAYNEXT_INDEX", "2");
169 * If start and end date for the quiz are more than this many seconds apart
170 * they will be represented by two separate events in the calendar
172 define("HOTPOT_MAX_EVENT_LENGTH", "432000"); // 5 days maximum
174 //////////////////////////////////
175 /// CORE FUNCTIONS
178 // possible return values:
179 // false:
180 // display moderr.html (if exists) OR "Could not update" and return to couse view
181 // string:
182 // display as error message and return to course view
183 // true (or non-zero number):
184 // continue to $hotpot->redirect (if set) OR hotpot/view.php (to displsay quiz)
186 // $hotpot is an object containing the values of the form in mod.html
187 // i.e. all the fields in the 'hotpot' table, plus the following:
188 // $hotpot->course : an id in the 'course' table
189 // $hotpot->coursemodule : an id in the 'course_modules' table
190 // $hotpot->section : an id in the 'course_sections' table
191 // $hotpot->module : an id in the 'modules' table
192 // $hotpot->modulename : always 'hotpot'
193 // $hotpot->instance : an id in the 'hotpot' table
194 // $hotpot->mode : 'add' or 'update'
195 // $hotpot->sesskey : unique string required for Moodle's session management
197 function hotpot_add_instance(&$hotpot) {
198 if (hotpot_set_form_values($hotpot)) {
199 if ($result = insert_record('hotpot', $hotpot)) {
200 $hotpot->id = $result;
201 hotpot_update_events($hotpot);
203 } else {
204 $result= false;
206 return $result;
209 function hotpot_update_instance(&$hotpot) {
210 if (hotpot_set_form_values($hotpot)) {
211 $hotpot->id = $hotpot->instance;
212 if ($result = update_record('hotpot', $hotpot)) {
213 hotpot_update_events($hotpot);
215 } else {
216 $result= false;
218 return $result;
220 function hotpot_update_events($hotpot) {
222 // remove any previous calendar events for this hotpot
223 delete_records('event', 'modulename', 'hotpot', 'instance', $hotpot->id);
225 $event = new stdClass();
226 $event->description = addslashes($hotpot->summary);
227 $event->courseid = $hotpot->course;
228 $event->groupid = 0;
229 $event->userid = 0;
230 $event->modulename = 'hotpot';
231 $event->instance = $hotpot->id;
232 $event->timestart = $hotpot->timeopen;
233 if ($cm = get_coursemodule_from_id('hotpot', $hotpot->id)) {
234 $event->visible = hotpot_is_visible($cm);
235 } else {
236 $event->visible = 1;
239 if ($hotpot->timeclose && $hotpot->timeopen) {
240 // we have both a start and an end date
241 $event->eventtype = 'open';
242 $event->timeduration = ($hotpot->timeclose - $hotpot->timeopen);
244 if ($event->timeduration > HOTPOT_MAX_EVENT_LENGTH) { /// Long durations create two events
246 $event->name = addslashes($hotpot->name).' ('.get_string('hotpotopens', 'hotpot').')';
247 $event->timeduration = 0;
248 add_event($event);
250 $event->timestart = $hotpot->timeclose;
251 $event->eventtype = 'close';
252 $event->name = addslashes($hotpot->name).' ('.get_string('hotpotcloses', 'hotpot').')';
253 unset($event->id);
254 add_event($event);
255 } else { // single event with duration
256 $event->name = $hotpot->name;
257 add_event($event);
259 } elseif ($hotpot->timeopen) { // only an open date
260 $event->name = addslashes($hotpot->name).' ('.get_string('hotpotopens', 'hotpot').')';
261 $event->eventtype = 'open';
262 $event->timeduration = 0;
263 add_event($event);
264 } elseif ($hotpot->timeclose) { // only a closing date
265 $event->name = addslashes($hotpot->name).' ('.get_string('hotpotcloses', 'hotpot').')';
266 $event->timestart = $hotpot->timeclose;
267 $event->eventtype = 'close';
268 $event->timeduration = 0;
269 add_event($event);
273 function hotpot_set_form_values(&$hotpot) {
274 $ok = true;
275 $hotpot->errors = array(); // these will be reported by moderr.html
277 if (empty($hotpot->reference)) {
278 $ok = false;
279 $hotpot->errors['reference']= get_string('error_nofilename', 'hotpot');
282 if ($hotpot->studentfeedbackurl=='http://') {
283 $hotpot->studentfeedbackurl = '';
286 if (empty($hotpot->studentfeedbackurl)) {
287 switch ($hotpot->studentfeedback) {
288 case HOTPOT_FEEDBACK_WEBPAGE:
289 $ok = false;
290 $hotpot->errors['studentfeedbackurl']= get_string('error_nofeedbackurlwebpage', 'hotpot');
291 break;
292 case HOTPOT_FEEDBACK_FORMMAIL:
293 $ok = false;
294 $hotpot->errors['studentfeedbackurl']= get_string('error_nofeedbackurlformmail', 'hotpot');
295 break;
299 $time = time();
300 $hotpot->timecreated = $time;
301 $hotpot->timemodified = $time;
303 if (empty($hotpot->mode)) {
304 // moodle 1.9 (from mod_form.lib)
305 if ($hotpot->add) {
306 $hotpot->mode = 'add';
307 } else if ($hotpot->update) {
308 $hotpot->mode = 'update';
309 } else {
310 $hotpot->mode = '';
313 if ($hotpot->quizchain==HOTPOT_YES) {
314 switch ($hotpot->mode) {
315 case 'add':
316 $ok = hotpot_add_chain($hotpot);
317 break;
318 case 'update':
319 $ok = hotpot_update_chain($hotpot);
320 break;
322 } else { // $hotpot->quizchain==HOTPOT_NO
323 hotpot_set_name_summary_reference($hotpot);
326 switch ($hotpot->displaynext) {
327 // N.B. redirection only works for Moodle 1.5+
328 case HOTPOT_DISPLAYNEXT_COURSE:
329 $hotpot->redirect = true;
330 $hotpot->redirecturl = "view.php?id=$hotpot->course";
331 break;
332 case HOTPOT_DISPLAYNEXT_INDEX:
333 $hotpot->redirect = true;
334 $hotpot->redirecturl = "../mod/hotpot/index.php?id=$hotpot->course";
335 break;
336 default:
337 // use Moodle default action (i.e. go on to display the hotpot quiz)
340 // if ($ok && $hotpot->setdefaults) {
341 if ($ok) {
342 set_user_preference('hotpot_timeopen', $hotpot->timeopen);
343 set_user_preference('hotpot_timeclose', $hotpot->timeclose);
344 set_user_preference('hotpot_navigation', $hotpot->navigation);
345 set_user_preference('hotpot_outputformat', $hotpot->outputformat);
346 set_user_preference('hotpot_studentfeedback', $hotpot->studentfeedback);
347 set_user_preference('hotpot_studentfeedbackurl', $hotpot->studentfeedbackurl);
348 set_user_preference('hotpot_forceplugins', $hotpot->forceplugins);
349 set_user_preference('hotpot_shownextquiz', $hotpot->shownextquiz);
350 set_user_preference('hotpot_review', $hotpot->review);
351 set_user_preference('hotpot_grade', $hotpot->grade);
352 set_user_preference('hotpot_grademethod', $hotpot->grademethod);
353 set_user_preference('hotpot_attempts', $hotpot->attempts);
354 set_user_preference('hotpot_subnet', $hotpot->subnet);
355 set_user_preference('hotpot_displaynext', $hotpot->displaynext);
356 if ($hotpot->mode=='add') {
357 set_user_preference('hotpot_quizchain', $hotpot->quizchain);
358 set_user_preference('hotpot_namesource', $hotpot->namesource);
359 set_user_preference('hotpot_summarysource', $hotpot->summarysource);
362 return $ok;
364 function hotpot_get_chain(&$cm) {
365 // get details of course_modules in this section
366 $course_module_ids = get_field('course_sections', 'sequence', 'id', $cm->section);
367 if (empty($course_module_ids)) {
368 $hotpot_modules = array();
369 } else {
370 $hotpot_modules = get_records_select('course_modules', "id IN ($course_module_ids) AND module=$cm->module");
371 if (empty($hotpot_modules)) {
372 $hotpot_modules = array();
376 // get ids of hotpot modules in this section
377 $ids = array();
378 foreach ($hotpot_modules as $hotpot_module) {
379 $ids[] = $hotpot_module->instance;
382 // get details of hotpots in this section
383 if (empty($ids)) {
384 $hotpots = array();
385 } else {
386 $hotpots = get_records_list('hotpot', 'id', implode(',', $ids));
389 $found = false;
390 $chain = array();
392 // loop through course_modules in this section
393 $ids = explode(',', $course_module_ids);
394 foreach ($ids as $id) {
396 // check this course_module is a hotpot activity
397 if (isset($hotpot_modules[$id])) {
399 // store details of this course module and hotpot activity
400 $hotpot_id = $hotpot_modules[$id]->instance;
401 $chain[$id] = &$hotpot_modules[$id];
402 $chain[$id]->hotpot = &$hotpots[$hotpot_id];
404 // set $found, if this is the course module we're looking for
405 if (isset($cm->coursemodule)) {
406 if ($id==$cm->coursemodule) {
407 $found = true;
409 } else {
410 if ($id==$cm->id) {
411 $found = true;
415 // is this the end of a chain
416 if (empty($hotpots[$hotpot_id]->shownextquiz)) {
417 if ($found) {
418 break; // out of loop
419 } else {
420 // restart chain (target cm has not been found yet)
421 $chain = array();
425 } // end foreach $ids
427 return $found ? $chain : false;
429 function hotpot_is_visible(&$cm) {
430 if (!isset($cm->sectionvisible)) {
431 if ($section = get_record('course_sections', 'id', $cm->section)) {
432 $cm->sectionvisible = $section->visible;
433 } else {
434 error('Course module record contains invalid section');
438 if (empty($cm->sectionvisible)) {
439 $visible = HOTPOT_NO;
440 } else {
441 $visible = HOTPOT_YES;
442 if (empty($cm->visible)) {
443 if ($chain = hotpot_get_chain($cm)) {
444 $startofchain = array_shift($chain);
445 $visible = $startofchain->visible;
449 return $visible;
451 function hotpot_add_chain(&$hotpot) {
452 /// add a chain of hotpot actiivities
454 global $CFG, $course;
456 $ok = true;
457 $hotpot->names = array();
458 $hotpot->summaries = array();
459 $hotpot->references = array();
461 $xml_quiz = new hotpot_xml_quiz($hotpot, false, false, false, false, false);
463 if (isset($xml_quiz->error)) {
464 $hotpot->errors['reference'] = $xml_quiz->error;
465 $ok = false;
467 } else if (is_dir($xml_quiz->filepath)) {
469 // get list of hotpot files in this folder
470 if ($dh = @opendir($xml_quiz->filepath)) {
471 while ($file = @readdir($dh)) {
472 if (preg_match('/\.(jbc|jcl|jcw|jmt|jmx|jqz|htm|html)$/', $file)) {
473 $hotpot->references[] = "$xml_quiz->reference/$file";
476 closedir($dh);
478 // get titles
479 foreach ($hotpot->references as $i=>$reference) {
480 $filepath = $xml_quiz->fileroot.'/'.$reference;
481 hotpot_get_titles_and_next_ex($hotpot, $filepath);
482 $hotpot->names[$i] = $hotpot->exercisetitle;
483 $hotpot->summaries[$i] = $hotpot->exercisesubtitle;
486 } else {
487 $ok = false;
488 $hotpot->errors['reference'] = get_string('error_couldnotopenfolder', 'hotpot', $hotpot->reference);
491 } else if (is_file($xml_quiz->filepath)) {
493 $filerootlength = strlen($xml_quiz->fileroot) + 1;
495 while ($xml_quiz->filepath) {
496 hotpot_get_titles_and_next_ex($hotpot, $xml_quiz->filepath, true);
497 $hotpot->names[] = $hotpot->exercisetitle;
498 $hotpot->summaries[] = $hotpot->exercisesubtitle;
499 $hotpot->references[] = substr($xml_quiz->filepath, $filerootlength);
501 if ($hotpot->nextexercise) {
502 $filepath = $xml_quiz->fileroot.'/'.$xml_quiz->filesubdir.$hotpot->nextexercise;
504 // check file is not already in chain
505 $reference = substr($filepath, $filerootlength);
506 if (in_array($reference, $hotpot->references)) {
507 $filepath = '';
509 } else {
510 $filepath = '';
512 if ($filepath && file_exists($filepath) && is_file($filepath) && is_readable($filepath)) {
513 $xml_quiz->filepath = $filepath;
514 } else {
515 $xml_quiz->filepath = false; // finish while loop
517 } // end while
519 } else {
520 $ok = false;
521 $hotpot->errors['reference'] = get_string('error_notfileorfolder', 'hotpot', $hotpot->reference);
524 if (empty($hotpot->references) && empty($hotpot->errors['reference'])) {
525 $ok = false;
526 $hotpot->errors['reference'] = get_string('error_noquizzesfound', 'hotpot', $hotpot->reference);
529 if ($ok) {
530 $hotpot->visible = HOTPOT_YES;
532 if (trim($hotpot->name)=='') {
533 $hotpot->name = get_string("modulename", $hotpot->modulename);
535 $hotpot->specificname = $hotpot->name;
536 $hotpot->specificsummary = $hotpot->summary;
538 // add all except last activity in chain
540 $i_max = count($hotpot->references)-1;
541 for ($i=0; $i<$i_max; $i++) {
543 hotpot_set_name_summary_reference($hotpot, $i);
544 $hotpot->reference = addslashes($hotpot->reference);
546 if (!$hotpot->instance = insert_record("hotpot", $hotpot)) {
547 error("Could not add a new instance of $hotpot->modulename", "view.php?id=$hotpot->course");
550 // store (hotpot table) id of start of chain
551 if ($i==0) {
552 $hotpot->startofchain = $hotpot->instance;
555 if (isset($course->groupmode)) {
556 $hotpot->groupmode = $course->groupmode;
559 if (! $hotpot->coursemodule = add_course_module($hotpot)) {
560 error("Could not add a new course module");
562 if (! $sectionid = add_mod_to_section($hotpot) ) {
563 error("Could not add the new course module to that section");
566 if (! set_field("course_modules", "section", $sectionid, "id", $hotpot->coursemodule)) {
567 error("Could not update the course module with the correct section");
570 add_to_log($hotpot->course, "course", "add mod",
571 "../mod/$hotpot->modulename/view.php?id=$hotpot->coursemodule",
572 "$hotpot->modulename $hotpot->instance"
574 add_to_log($hotpot->course, $hotpot->modulename, "add",
575 "view.php?id=$hotpot->coursemodule",
576 "$hotpot->instance", $hotpot->coursemodule
579 // hide tail of chain
580 if ($hotpot->shownextquiz==HOTPOT_YES) {
581 $hotpot->visible = HOTPOT_NO;
583 } // end for ($hotpot->references)
585 // settings for final activity in chain
586 hotpot_set_name_summary_reference($hotpot, $i);
587 $hotpot->reference = addslashes($hotpot->references[$i]);
588 $hotpot->shownextquiz = HOTPOT_NO;
590 if (isset($hotpot->startofchain)) {
591 // redirection only works for Moodle 1.5+
592 $hotpot->redirect = true;
593 $hotpot->redirecturl = "$CFG->wwwroot/mod/hotpot/view.php?hp=$hotpot->startofchain";
595 } // end if $ok
597 return $ok;
599 function hotpot_set_name_summary_reference(&$hotpot, $chain_index=NULL) {
601 $xml_quiz = NULL;
603 $textfields = array('name', 'summary');
604 foreach ($textfields as $textfield) {
606 $textsource = $textfield.'source';
608 // are we adding a chain?
609 if (isset($chain_index)) {
611 switch ($hotpot->$textsource) {
612 case HOTPOT_TEXTSOURCE_QUIZ:
613 if ($textfield=='name') {
614 $hotpot->exercisetitle = $hotpot->names[$chain_index];
615 } else if ($textfield=='summary') {
616 $hotpot->exercisesubtitle = $hotpot->summaries[$chain_index];
618 break;
619 case HOTPOT_TEXTSOURCE_SPECIFIC:
620 $specifictext = 'specific'.$textfield;
621 if (empty($hotpot->$specifictext) && trim($hotpot->$specifictext)=='') {
622 $hotpot->$textfield = '';
623 } else {
624 $hotpot->$textfield = $hotpot->$specifictext.' ('.($chain_index+1).')';
626 break;
628 $hotpot->reference = $hotpot->references[$chain_index];
631 if ($hotpot->$textsource==HOTPOT_TEXTSOURCE_QUIZ) {
632 if (empty($xml_quiz) && !isset($chain_index)) {
633 $xml_quiz = new hotpot_xml_quiz($hotpot, false, false, false, false, false);
634 hotpot_get_titles_and_next_ex($hotpot, $xml_quiz->filepath);
636 if ($textfield=='name') {
637 $hotpot->$textfield = addslashes($hotpot->exercisetitle);
638 } else if ($textfield=='summary') {
639 $hotpot->$textfield = addslashes($hotpot->exercisesubtitle);
642 switch ($hotpot->$textsource) {
643 case HOTPOT_TEXTSOURCE_FILENAME:
644 $hotpot->$textfield = basename($hotpot->reference);
645 break;
646 case HOTPOT_TEXTSOURCE_FILEPATH:
647 $hotpot->$textfield = '';
648 // continue to next lines
649 default:
650 if (empty($hotpot->$textfield)) {
651 $hotpot->$textfield = str_replace('/', ' ', $hotpot->reference);
653 } // end switch
654 } // end foreach
656 function hotpot_get_titles_and_next_ex(&$hotpot, $filepath, $get_next=false) {
658 $hotpot->exercisetitle = '';
659 $hotpot->exercisesubtitle = '';
660 $hotpot->nextexercise = '';
662 // read the quiz file source
663 if ($source = file_get_contents($filepath)) {
665 $next = '';
666 $title = '';
667 $subtitle = '';
669 if (preg_match('|\.html?$|', $filepath)) {
670 // html file
671 if (preg_match('|<h2[^>]*class="ExerciseTitle"[^>]*>(.*?)</h2>|is', $source, $matches)) {
672 $title = trim(strip_tags($matches[1]));
674 if (empty($title)) {
675 if (preg_match('|<title[^>]*>(.*?)</title>|is', $source, $matches)) {
676 $title = trim(strip_tags($matches[1]));
679 if (preg_match('|<h3[^>]*class="ExerciseSubtitle"[^>]*>(.*?)</h3>|is', $source, $matches)) {
680 $subtitle = trim(strip_tags($matches[1]));
682 if ($get_next) {
683 if (preg_match('|<div[^>]*class="NavButtonBar"[^>]*>(.*?)</div>|is', $source, $matches)) {
684 $navbuttonbar = $matches[1];
685 if (preg_match_all('|<button[^>]*class="NavButton"[^>]*onclick="'."location='([^']*)'".'[^"]*"[^>]*>|is', $navbuttonbar, $matches)) {
686 $lastbutton = count($matches[0])-1;
687 $next = $matches[1][$lastbutton];
692 } else {
693 // xml file (...maybe)
694 $xml_tree = new hotpot_xml_tree($source);
695 $xml_tree->filetype = '';
697 $keys = array_keys($xml_tree->xml);
698 foreach ($keys as $key) {
699 if (preg_match('/^(hotpot|textoys)-(\w+)-file$/i', $key, $matches)) {
700 $xml_tree->filetype = 'xml';
701 $xml_tree->xml_root = "['$key']['#']";
702 $xml_tree->quiztype = strtolower($matches[2]);
703 break;
706 if ($xml_tree->filetype=='xml') {
708 $title = strip_tags($xml_tree->xml_value('data,title'));
709 $subtitle = $xml_tree->xml_value('hotpot-config-file,'.$xml_tree->quiztype.',exercise-subtitle');
711 if ($get_next) {
712 $include = $xml_tree->xml_value('hotpot-config-file,global,include-next-ex');
713 if (!empty($include)) {
714 $next = $xml_tree->xml_value("hotpot-config-file,$xml_tree->quiztype,next-ex-url");
715 if (is_array($next)) {
716 $next = $next[0]; // in case "next-ex-url" was repeated in the xml file
723 $hotpot->nextexercise = $next;
724 $hotpot->exercisetitle = (empty($title) || is_array($title)) ? basename($filepath) : $title;
725 $hotpot->exercisesubtitle = (empty($subtitle) || is_array($subtitle)) ? $hotpot->exercisetitle : $subtitle;
728 function hotpot_get_all_instances_in_course($modulename, $course) {
729 /// called from index.php
731 global $CFG;
732 $instances = array();
734 if (isset($CFG->release) && substr($CFG->release, 0, 3)>=1.2) {
735 $groupmode = 'cm.groupmode,';
736 } else {
737 $groupmode = '';
740 $query = "
741 SELECT
742 cm.id AS coursemodule,
743 cm.course AS course,
744 cm.module AS module,
745 cm.instance AS instance,
746 -- cm.section AS section,
747 cm.visible AS visible,
748 $groupmode
749 -- cs.section AS sectionnumber,
750 cs.section AS section,
751 cs.sequence AS sequence,
752 cs.visible AS sectionvisible,
753 thismodule.*
754 FROM
755 {$CFG->prefix}course_modules cm,
756 {$CFG->prefix}course_sections cs,
757 {$CFG->prefix}modules m,
758 {$CFG->prefix}$modulename thismodule
759 WHERE
760 m.name = '$modulename' AND
761 m.id = cm.module AND
762 cm.course = '$course->id' AND
763 cm.section = cs.id AND
764 cm.instance = thismodule.id
766 if ($rawmods = get_records_sql($query)) {
768 // cache $isteacher setting
770 $isteacher = has_capability('mod/hotpot:viewreport', get_context_instance(CONTEXT_MODULE, $course->id));
772 $explodesection = array();
773 $order = array();
775 foreach ($rawmods as $rawmod) {
777 if (empty($explodesection[$rawmod->section])) {
778 $explodesection[$rawmod->section] = true;
780 $coursemodules = explode(',', $rawmod->sequence);
781 foreach ($coursemodules as $i=>$coursemodule) {
782 $order[$coursemodule] = sprintf('%d.%04d', $rawmod->section, $i);
786 if ($isteacher) {
787 $visible = true;
788 } else if ($modulename=='hotpot') {
789 $visible = hotpot_is_visible($rawmod);
790 } else {
791 $visible = $rawmod->visible;
794 if ($visible) {
795 $instances[$order[$rawmod->coursemodule]] = $rawmod;
798 } // end foreach $modinfo
800 ksort($instances);
801 $instances = array_values($instances);
804 return $instances;
807 function hotpot_update_chain(&$hotpot) {
808 /// update a chain of hotpot actiivities
810 $ok = true;
811 if ($hotpot_modules = hotpot_get_chain($hotpot)) {
813 // skip updating of these fields
814 $skipfields = array('id', 'course', 'name', 'reference', 'summary', 'shownextquiz');
815 $fields = array();
817 foreach ($hotpot_modules as $hotpot_module) {
819 if ($hotpot->instance==$hotpot_module->id) {
820 // don't need to update this hotpot
822 } else {
823 // shortcut to hotpot record
824 $thishotpot = &$hotpot_module->hotpot;
826 // get a list of fields to update (first time only)
827 if (empty($fields)) {
828 $fields = array_keys(get_object_vars($thishotpot));
831 // assume update is NOT required
832 $require_update = false;
834 // update field values (except $skipfields)
835 foreach($fields as $field) {
836 if (in_array($field, $skipfields) || $thishotpot->$field==$hotpot->$field) {
837 // update not required for this field
838 } else {
839 $require_update = true;
840 $thishotpot->$field = $hotpot->$field;
844 // update $thishotpot, if required
845 if ($require_update && !update_record("hotpot", $thishotpot)) {
846 error("Could not update the $hotpot->modulename", "view.php?id=$hotpot->course");
849 } // end foreach $ids
851 return $ok;
853 function hotpot_delete_instance($id) {
854 /// Given an ID of an instance of this module,
855 /// this function will permanently delete the instance
856 /// and any data that depends on it.
858 $result = false;
859 if (delete_records("hotpot", "id", "$id")) {
860 $result = true;
861 delete_records("hotpot_questions", "hotpot", "$id");
862 if ($attempts = get_records_select("hotpot_attempts", "hotpot='$id'")) {
863 $ids = implode(',', array_keys($attempts));
864 delete_records_select("hotpot_attempts", "id IN ($ids)");
865 delete_records_select("hotpot_details", "attempt IN ($ids)");
866 delete_records_select("hotpot_responses", "attempt IN ($ids)");
868 // remove calendar events for this hotpot
869 delete_records('event', 'modulename', 'hotpot', 'instance', $id);
871 return $result;
873 function hotpot_delete_and_notify($table, $select, $strtable) {
874 $count = max(0, count_records_select($table, $select));
875 if ($count) {
876 delete_records_select($table, $select);
877 $count -= max(0, count_records_select($table, $select));
878 if ($count) {
879 notify(get_string('deleted')." $count x $strtable");
884 function hotpot_user_complete($course, $user, $mod, $hotpot) {
885 /// Print a detailed representation of what a user has done with
886 /// a given particular instance of this module, for user activity reports.
888 $report = hotpot_user_outline($course, $user, $mod, $hotpot);
889 if (empty($report)) {
890 print get_string("noactivity", "hotpot");
891 } else {
892 $date = userdate($report->time, get_string('strftimerecentfull'));
893 print $report->info.' '.get_string('mostrecently').': '.$date;
895 return true;
898 function hotpot_user_outline($course, $user, $mod, $hotpot) {
899 /// Return a small object with summary information about what a
900 /// user has done with a given particular instance of this module
901 /// Used for user activity reports.
902 /// $report->time = the time they did it
903 /// $report->info = a short text description
905 $report = NULL;
906 if ($records = get_records_select("hotpot_attempts", "hotpot='$hotpot->id' AND userid='$user->id'", "timestart ASC", "*")) {
907 $report = new stdClass();
908 $scores = array();
909 foreach ($records as $record){
910 if (empty($report->time)) {
911 $report->time = $record->timestart;
913 $scores[] = hotpot_format_score($record);
915 if (empty($scores)) {
916 $report->time = 0;
917 $report->info = get_string('noactivity', 'hotpot');
918 } else {
919 $report->info = get_string('score', 'quiz').': '.implode(', ', $scores);
922 return $report;
925 function hotpot_format_score($record, $undefined='&nbsp;') {
926 if (isset($record->score)) {
927 $score = $record->score;
928 } else {
929 $score = $undefined;
931 return $score;
934 function hotpot_format_status($record, $undefined='&nbsp;') {
935 global $HOTPOT_STATUS;
937 if (isset($record->status) || isset($HOTPOT_STATUS[$record->status])) {
938 $status = $HOTPOT_STATUS[$record->status];
939 } else {
940 $status = $undefined;
942 return $status;
945 function hotpot_print_recent_activity($course, $isteacher, $timestart) {
946 /// Given a course and a time, this module should find recent activity
947 /// that has occurred in hotpot activities and print it out.
948 /// Return true if there was output, or false is there was none.
950 global $CFG;
951 $result = false;
953 $records = get_records_sql("
954 SELECT
955 h.id AS id,
956 h.name AS name,
957 COUNT(*) AS count_attempts
958 FROM
959 {$CFG->prefix}hotpot h,
960 {$CFG->prefix}hotpot_attempts a
961 WHERE
962 h.course = $course->id
963 AND h.id = a.hotpot
964 AND a.id = a.clickreportid
965 AND a.starttime > $timestart
966 GROUP BY
967 h.id, h.name
969 // note that PostGreSQL requires h.name in the GROUP BY clause
971 if($records) {
972 $names = array();
973 foreach ($records as $id => $record){
974 if ($cm = get_coursemodule_from_instance('hotpot', $record->id, $course->id)) {
975 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
977 if (has_capability('mod/hotpot:viewreport', $context)) {
978 $href = "$CFG->wwwroot/mod/hotpot/view.php?hp=$id";
979 $name = '&nbsp;<a href="'.$href.'">'.$record->name.'</a>';
980 if ($record->count_attempts > 1) {
981 $name .= " ($record->count_attempts)";
983 $names[] = $name;
987 if (count($names) > 0) {
988 print_headline(get_string('modulenameplural', 'hotpot').':');
990 if ($CFG->version >= 2005050500) { // Moodle 1.5+
991 echo '<div class="head"><div class="name">'.implode('<br />', $names).'</div></div>';
992 } else { // Moodle 1.4.x (or less)
993 echo '<font size="1">'.implode('<br />', $names).'</font>';
995 $result = true;
998 return $result; // True if anything was printed, otherwise false
1001 function hotpot_get_recent_mod_activity(&$activities, &$index, $sincetime, $courseid, $cmid="", $userid="", $groupid="") {
1002 // Returns all quizzes since a given time.
1004 global $CFG;
1006 // If $cmid or $userid are specified, then this restricts the results
1007 $cm_select = empty($cmid) ? "" : " AND cm.id = '$cmid'";
1008 $user_select = empty($userid) ? "" : " AND u.id = '$userid'";
1010 $records = get_records_sql("
1011 SELECT
1012 a.*,
1013 h.name, h.course,
1014 cm.instance, cm.section,
1015 u.firstname, u.lastname, u.picture
1016 FROM
1017 {$CFG->prefix}hotpot_attempts a,
1018 {$CFG->prefix}hotpot h,
1019 {$CFG->prefix}course_modules cm,
1020 {$CFG->prefix}user u
1021 WHERE
1022 a.timefinish > '$sincetime'
1023 AND a.id = a.clickreportid
1024 AND a.userid = u.id $user_select
1025 AND a.hotpot = h.id $cm_select
1026 AND cm.instance = h.id
1027 AND cm.course = '$courseid'
1028 AND h.course = cm.course
1029 ORDER BY
1030 a.timefinish ASC
1033 if (!empty($records)) {
1034 foreach ($records as $record) {
1035 if (empty($groupid) || ismember($groupid, $record->userid)) {
1037 unset($activity);
1039 $activity->type = "hotpot";
1040 $activity->defaultindex = $index;
1041 $activity->instance = $record->hotpot;
1043 $activity->name = $record->name;
1044 $activity->section = $record->section;
1046 $activity->content->attemptid = $record->id;
1047 $activity->content->attempt = $record->attempt;
1048 $activity->content->score = $record->score;
1049 $activity->content->timestart = $record->timestart;
1050 $activity->content->timefinish = $record->timefinish;
1052 $activity->user->userid = $record->userid;
1053 $activity->user->fullname = fullname($record);
1054 $activity->user->picture = $record->picture;
1056 $activity->timestamp = $record->timefinish;
1058 $activities[] = $activity;
1060 $index++;
1062 } // end foreach
1066 function hotpot_print_recent_mod_activity($activity, $course, $detail=false) {
1067 /// Basically, this function prints the results of "hotpot_get_recent_activity"
1069 global $CFG, $THEME, $USER;
1071 print '<table border="0" cellpadding="3" cellspacing="0">';
1073 print '<tr><td bgcolor="'.$THEME->cellcontent2.'" class="forumpostpicture" width="35" valign="top">';
1074 print_user_picture($activity->user->userid, $course, $activity->user->picture);
1075 print '</td><td width="100%"><font size="2">';
1077 if ($detail) {
1078 // activity icon
1079 $src = "$CFG->modpixpath/$activity->type/icon.gif";
1080 print '<img src="'.$src.'" class="icon" alt="'.$activity->type.'" /> ';
1082 // link to activity
1083 $href = "$CFG->wwwroot/mod/hotpot/view.php?hp=$activity->instance";
1084 print '<a href="'.$href.'">'.$activity->name.'</a> - ';
1086 if (has_capability('mod/hotpot:viewreport',get_context_instance(CONTEXT_COURSE, $course))) {
1087 // score (with link to attempt details)
1088 $href = "$CFG->wwwroot/mod/hotpot/review.php?hp=$activity->instance&attempt=".$activity->content->attemptid;
1089 print '<a href="'.$href.'">('.hotpot_format_score($activity->content).')</a> ';
1091 // attempt number
1092 print get_string('attempt', 'quiz').' - '.$activity->content->attempt.'<br />';
1095 // link to user
1096 $href = "$CFG->wwwroot/user/view.php?id=$activity->user->userid&course=$course";
1097 print '<a href="'.$href.'">'.$activity->user->fullname.'</a> ';
1099 // time and date
1100 print ' - ' . userdate($activity->timestamp);
1102 // duration
1103 $duration = format_time($activity->content->timestart - $activity->content->timefinish);
1104 print " &nbsp; ($duration)";
1106 print "</font></td></tr>";
1107 print "</table>";
1110 function hotpot_cron () {
1111 /// Function to be run periodically according to the moodle cron
1112 /// This function searches for things that need to be done, such
1113 /// as sending out mail, toggling flags etc ...
1115 global $CFG;
1117 return true;
1120 function hotpot_grades($hotpotid) {
1121 /// Must return an array of grades for a given instance of this module,
1122 /// indexed by user. It also returns a maximum allowed grade.
1124 $hotpot = get_record('hotpot', 'id', $hotpotid);
1125 $return->grades = hotpot_get_grades($hotpot);
1126 $return->maxgrade = $hotpot->grade;
1128 return $return;
1130 function hotpot_get_grades($hotpot, $user_ids='') {
1131 global $CFG;
1133 $grades = array();
1135 $weighting = $hotpot->grade / 100;
1136 $precision = hotpot_get_precision($hotpot);
1138 // set the SQL string to determine the $grade
1139 $grade = "";
1140 switch ($hotpot->grademethod) {
1141 case HOTPOT_GRADEMETHOD_HIGHEST:
1142 $grade = "ROUND(MAX(score) * $weighting, $precision) AS grade";
1143 break;
1144 case HOTPOT_GRADEMETHOD_AVERAGE:
1145 // the 'AVG' function skips abandoned quizzes, so use SUM(score)/COUNT(id)
1146 $grade = "ROUND(SUM(score)/COUNT(id) * $weighting, $precision) AS grade";
1147 break;
1148 case HOTPOT_GRADEMETHOD_FIRST:
1149 $grade = "ROUND(score * $weighting, $precision)";
1150 $grade = sql_concat('timestart', "'_'", $grade);
1151 $grade = "MIN($grade) AS grade";
1152 break;
1153 case HOTPOT_GRADEMETHOD_LAST:
1154 $grade = "ROUND(score * $weighting, $precision)";
1155 $grade = sql_concat('timestart', "'_'", $grade);
1156 $grade = "MAX($grade) AS grade";
1157 break;
1160 if ($grade) {
1161 $userid_condition = empty($user_ids) ? '' : "AND userid IN ($user_ids) ";
1162 $grades = get_records_sql_menu("
1163 SELECT userid, $grade
1164 FROM {$CFG->prefix}hotpot_attempts
1165 WHERE timefinish>0 AND hotpot='$hotpot->id' $userid_condition
1166 GROUP BY userid
1168 if ($grades) {
1169 if ($hotpot->grademethod==HOTPOT_GRADEMETHOD_FIRST || $hotpot->grademethod==HOTPOT_GRADEMETHOD_LAST) {
1170 // remove left hand characters in $grade (up to and including the underscore)
1171 foreach ($grades as $userid=>$grade) {
1172 $grades[$userid] = substr($grades[$userid], strpos($grades[$userid], '_')+1);
1178 return $grades;
1180 function hotpot_get_precision(&$hotpot) {
1181 return ($hotpot->grademethod==HOTPOT_GRADEMETHOD_AVERAGE || $hotpot->grade<100) ? 1 : 0;
1184 function hotpot_get_participants($hotpotid) {
1185 //Must return an array of user ids who are participants
1186 //for a given instance of hotpot. Must include every user involved
1187 //in the instance, independient of his role (student, teacher, admin...)
1188 //See other modules as example.
1189 global $CFG;
1191 return get_records_sql("
1192 SELECT DISTINCT
1193 u.id, u.id
1194 FROM
1195 {$CFG->prefix}user u,
1196 {$CFG->prefix}hotpot_attempts a
1197 WHERE
1198 u.id = a.userid
1199 AND a.hotpot = '$hotpotid'
1203 function hotpot_scale_used ($hotpotid, $scaleid) {
1204 //This function returns if a scale is being used by one hotpot
1205 //it it has support for grading and scales. Commented code should be
1206 //modified if necessary. See forum, glossary or journal modules
1207 //as reference.
1209 $report = false;
1211 //$rec = get_record("hotpot","id","$hotpotid","scale","-$scaleid");
1213 //if (!empty($rec) && !empty($scaleid)) {
1214 // $report = true;
1217 return $report;
1220 //////////////////////////////////////////////////////////
1221 /// Any other hotpot functions go here.
1222 /// Each of them must have a name that starts with hotpot
1225 function hotpot_add_attempt($hotpotid) {
1226 global $db, $CFG, $USER;
1228 // get start time of this attempt
1229 $time = time();
1231 // set all previous "in progress" attempts at this quiz to "abandoned"
1232 if ($attempts = get_records_select('hotpot_attempts', "hotpot='$hotpotid' AND userid='$USER->id' AND status='".HOTPOT_STATUS_INPROGRESS."'")) {
1233 foreach ($attempts as $attempt) {
1234 if ($attempt->timefinish==0) {
1235 $attempt->timefinish = $time;
1237 if ($attempt->clickreportid==0) {
1238 $attempt->clickreportid = $attempt->id;
1240 $attempt->status = HOTPOT_STATUS_ABANDONED;
1241 update_record('hotpot_attempts', $attempt);
1245 // create and add new attempt record
1246 $attempt = new stdClass();
1247 $attempt->hotpot = $hotpotid;
1248 $attempt->userid = $USER->id;
1249 $attempt->attempt = hotpot_get_next_attempt($hotpotid);
1250 $attempt->timestart = $time;
1252 return insert_record("hotpot_attempts", $attempt);
1254 function hotpot_get_next_attempt($hotpotid) {
1255 global $USER;
1257 // get max attempt so far
1258 $i = count_records_select('hotpot_attempts', "hotpot='$hotpotid' AND userid='$USER->id'", 'MAX(attempt)');
1260 return empty($i) ? 1 : ($i+1);
1262 function hotpot_get_question_name($question) {
1263 $name = '';
1264 if (isset($question->text)) {
1265 $name = hotpot_strings($question->text);
1267 if (empty($name)) {
1268 $name = $question->name;
1270 return $name;
1272 function hotpot_strings($ids) {
1274 // array of ids of empty strings
1275 static $HOTPOT_EMPTYSTRINGS;
1277 if (!isset($HOTPOT_EMPTYSTRINGS)) { // first time only
1278 // get ids of empty strings
1279 $emptystrings = get_records_select('hotpot_strings', 'LENGTH(TRIM(string))=0');
1280 $HOTPOT_EMPTYSTRINGS = empty($emptystrings) ? array() : array_keys($emptystrings);
1283 $strings = array();
1284 if (!empty($ids)) {
1285 $ids = explode(',', $ids);
1286 foreach ($ids as $id) {
1287 if (!in_array($id, $HOTPOT_EMPTYSTRINGS)) {
1288 $strings[] = hotpot_string($id);
1292 return implode(',', $strings);
1294 function hotpot_string($id) {
1295 return get_field('hotpot_strings', 'string', 'id', $id);
1298 //////////////////////////////////////////////////////////////////////////////////////
1299 /// the class definitions to handle XML trees
1301 // get the standard XML parser supplied with Moodle
1302 require_once("$CFG->libdir/xmlize.php");
1304 // get the default class for hotpot quiz templates
1305 require_once("$CFG->hotpottemplate/default.php");
1307 class hotpot_xml_tree {
1308 function hotpot_xml_tree($str, $xml_root='') {
1309 if (empty($str)) {
1310 $this->xml = array();
1311 } else {
1312 if (empty($CFG->unicodedb)) {
1313 $str = utf8_encode($str);
1315 $this->xml = xmlize($str, 0);
1317 $this->xml_root = $xml_root;
1319 function xml_value($tags, $more_tags="[0]['#']") {
1321 $tags = empty($tags) ? '' : "['".str_replace(",", "'][0]['#']['", $tags)."']";
1322 eval('$value = &$this->xml'.$this->xml_root.$tags.$more_tags.';');
1324 if (is_string($value)) {
1325 if (empty($CFG->unicodedb)) {
1326 $value = utf8_decode($value);
1329 // decode angle brackets
1330 $value = strtr($value, array('&#x003C;'=>'<', '&#x003E;'=>'>', '&#x0026;'=>'&'));
1332 // remove white space between <table>, <ul|OL|DL> and <OBJECT|EMBED> parts
1333 // (so it doesn't get converted to <br />)
1334 $htmltags = '('
1335 . 'TABLE|/?CAPTION|/?COL|/?COLGROUP|/?TBODY|/?TFOOT|/?THEAD|/?TD|/?TH|/?TR'
1336 . '|OL|UL|/?LI'
1337 . '|DL|/?DT|/?DD'
1338 . '|EMBED|OBJECT|APPLET|/?PARAM'
1339 //. '|SELECT|/?OPTION'
1340 //. '|FIELDSET|/?LEGEND'
1341 //. '|FRAMESET|/?FRAME'
1342 . ')'
1345 $space = '(\s|(<br[^>]*>))+';
1346 $search = '#(<'.$htmltags.'[^>]*'.'>)'.$space.'(?='.'<)#is';
1347 $value = preg_replace($search, '\\1', $value);
1349 // replace remaining newlines with <br />
1350 $value = str_replace("\n", '<br />', $value);
1352 // encode unicode characters as HTML entities
1353 // (in particular, accented charaters that have not been encoded by HP)
1355 // unicode characters can be detected by checking the hex value of a character
1356 // 00 - 7F : ascii char (roman alphabet + punctuation)
1357 // 80 - BF : byte 2, 3 or 4 of a unicode char
1358 // C0 - DF : 1st byte of 2-byte char
1359 // E0 - EF : 1st byte of 3-byte char
1360 // F0 - FF : 1st byte of 4-byte char
1361 // if the string doesn't match the above, it might be
1362 // 80 - FF : single-byte, non-ascii char
1363 $search = '#('.'[\xc0-\xdf][\x80-\xbf]'.'|'.'[\xe0-\xef][\x80-\xbf]{2}'.'|'.'[\xf0-\xff][\x80-\xbf]{3}'.'|'.'[\x80-\xff]'.')#se';
1364 $value = preg_replace($search, "hotpot_utf8_to_html_entity('\\1')", $value);
1366 return $value;
1368 function xml_values($tags) {
1369 $i = 0;
1370 $values = array();
1371 while ($value = $this->xml_value($tags, "[$i]['#']")) {
1372 $values[$i++] = $value;
1374 return $values;
1376 function obj_value(&$obj, $name) {
1377 return is_object($obj) ? @$obj->$name : (is_array($obj) ? @$obj[$name] : NULL);
1379 function encode_cdata(&$str, $tag) {
1381 // conversion tables
1382 static $HTML_ENTITIES = array(
1383 '&apos;' => "'",
1384 '&quot;' => '"',
1385 '&lt;' => '<',
1386 '&gt;' => '>',
1387 '&amp;' => '&',
1389 static $ILLEGAL_STRINGS = array(
1390 "\r\n" => '&lt;br /&gt;',
1391 "\r" => '&lt;br /&gt;',
1392 "\n" => '&lt;br /&gt;',
1393 '[' => '&#91;',
1394 ']' => '&#93;'
1397 // extract the $tag from the $str(ing), if possible
1398 $pattern = '|(^.*<'.$tag.'[^>]*)(>.*<)(/'.$tag.'>.*$)|is';
1399 if (preg_match($pattern, $str, $matches)) {
1401 // encode problematic CDATA chars and strings
1402 $matches[2] = strtr($matches[2], $ILLEGAL_STRINGS);
1404 // if there are any ampersands in "open text"
1405 // surround them by CDATA start and end markers
1406 // (and convert HTML entities to plain text)
1407 $search = '/>([^<]*&[^<]*)</e';
1408 $replace = '"><![CDATA[".strtr("$1", $HTML_ENTITIES)."]]><"';
1409 $matches[2] = preg_replace($search, $replace, $matches[2]);
1411 $str = $matches[1].$matches[2].$matches[3];
1416 class hotpot_xml_quiz extends hotpot_xml_tree {
1418 // constructor function
1419 function hotpot_xml_quiz(&$obj, $read_file=true, $parse_xml=true, $convert_urls=true, $report_errors=true, $create_html=true) {
1420 // obj can be the $_GET array or a form object/array
1422 global $CFG, $HOTPOT_OUTPUTFORMAT, $HOTPOT_OUTPUTFORMAT_DIR;
1424 // check xmlize functions are available
1425 if (! function_exists("xmlize")) {
1426 error('xmlize functions are not available');
1429 $this->read_file = $read_file;
1430 $this->parse_xml = $parse_xml;
1431 $this->convert_urls = $convert_urls;
1432 $this->report_errors = $report_errors;
1433 $this->create_html = $create_html;
1435 // extract fields from $obj
1436 // course : the course id
1437 // reference : the filename within the files folder
1438 // location : "site" files folder or "course" files folder
1439 // navigation : type of navigation required in quiz
1440 // forceplugins : force Moodle compatible media players
1441 $this->course = $this->obj_value($obj, 'course');
1442 $this->reference = $this->obj_value($obj, 'reference');
1443 $this->location = $this->obj_value($obj, 'location');
1444 $this->navigation = $this->obj_value($obj, 'navigation');
1445 $this->forceplugins = $this->obj_value($obj, 'forceplugins');
1447 // can't continue if there is no course or reference
1448 if (empty($this->course) || empty($this->reference)) {
1449 $this->error = get_string('error_nocourseorfilename', 'hotpot');
1450 if ($this->report_errors) {
1451 error($this->error);
1453 return;
1456 $this->course_homeurl = "$CFG->wwwroot/course/view.php?id=$this->course";
1458 // set filedir, filename and filepath
1459 switch ($this->location) {
1460 case HOTPOT_LOCATION_SITEFILES:
1461 $site = get_site();
1462 $this->filedir = $site->id;
1463 break;
1465 case HOTPOT_LOCATION_COURSEFILES:
1466 default:
1467 $this->filedir = $this->course;
1468 break;
1470 $this->filesubdir = dirname($this->reference);
1471 if ($this->filesubdir=='.') {
1472 $this->filesubdir = '';
1474 if ($this->filesubdir) {
1475 $this->filesubdir .= '/';
1477 $this->filename = basename($this->reference);
1478 $this->fileroot = "$CFG->dataroot/$this->filedir";
1479 $this->filepath = "$this->fileroot/$this->reference";
1481 // read the file, if required
1482 if ($this->read_file) {
1484 if (!file_exists($this->filepath) || !is_readable($this->filepath)) {
1485 $this->error = get_string('error_couldnotopensourcefile', 'hotpot', $this->filepath);
1486 if ($this->report_errors) {
1487 error($this->error, $this->course_homeurl);
1489 return;
1492 // read in the XML source
1493 $this->source = file_get_contents($this->filepath);
1495 // convert relative URLs to absolute URLs
1496 if ($this->convert_urls) {
1497 $this->hotpot_convert_relative_urls($this->source);
1500 $this->html = '';
1501 $this->quiztype = '';
1502 $this->outputformat = 0;
1504 // is this an html file?
1505 if (preg_match('|\.html?$|', $this->filename)) {
1507 $this->filetype = 'html';
1508 $this->html = &$this->source;
1510 // relative URLs in stylesheets
1511 $search = '|'.'(<style[^>]*>)'.'(.*?)'.'(</style>)'.'|ise';
1512 $replace = "stripslashes('\\1').hotpot_convert_stylesheets_urls('".$this->get_baseurl()."','".$this->reference."','\\2'.'\\3')";
1513 $this->source = preg_replace($search, $replace, $this->source);
1515 // relative URLs in "PreloadImages(...);"
1516 $search = '|'.'(?<='.'PreloadImages'.'\('.')'."([^)]+?)".'(?='.'\);'.')'.'|se';
1517 $replace = "hotpot_convert_preloadimages_urls('".$this->get_baseurl()."','".$this->reference."','\\1')";
1518 $this->source = preg_replace($search, $replace, $this->source);
1520 // relative URLs in <button class="NavButton" ... onclick="location='...'">
1521 $search = '|'.'(?<='.'onclick="'."location='".')'."([^']*)".'(?='."'; return false;".'")'.'|ise';
1522 $replace = "hotpot_convert_navbutton_url('".$this->get_baseurl()."','".$this->reference."','\\1','".$this->course."')";
1523 $this->source = preg_replace($search, $replace, $this->source);
1525 // relative URLs in <a ... onclick="window.open('...')...">...</a>
1526 $search = '|'.'(?<='.'onclick="'."window.open\\('".')'."([^']*)".'(?='."'\\);return false;".'")'.'|ise';
1527 $replace = "hotpot_convert_url('".$this->get_baseurl()."','".$this->reference."','\\1')";
1528 $this->source = preg_replace($search, $replace, $this->source);
1530 } else {
1532 // relative URLs in <a ... onclick="window.open('...')...">...</a>
1533 $search = '|'.'(?<='.'onclick=&quot;'."window.open\\(&apos;".')'."(.*?)".'(?='."&apos;\\);return false;".'&quot;)'.'|ise';
1534 $replace = "hotpot_convert_url('".$this->get_baseurl()."','".$this->reference."','\\1')";
1535 $this->source = preg_replace($search, $replace, $this->source);
1537 if ($this->parse_xml) {
1539 $this->filetype = 'xml';
1541 // encode "gap fill" text in JCloze exercise
1542 $this->encode_cdata($this->source, 'gap-fill');
1544 // convert source to xml tree
1545 $this->hotpot_xml_tree($this->source);
1547 $keys = array_keys($this->xml);
1548 foreach ($keys as $key) {
1549 if (preg_match('/^(hotpot|textoys)-(\w+)-file$/i', $key, $matches)) {
1550 $this->quiztype = strtolower($matches[2]);
1551 $this->xml_root = "['$key']['#']";
1552 break;
1557 if ($this->create_html) {
1559 // set the real output format from the requested output format
1560 $this->real_outputformat = $this->obj_value($obj, 'outputformat');
1561 $this->draganddrop = '';
1562 if (
1563 empty($this->real_outputformat) ||
1564 $this->real_outputformat==HOTPOT_OUTPUTFORMAT_BEST ||
1565 empty($HOTPOT_OUTPUTFORMAT_DIR[$this->real_outputformat])
1567 if ($CFG->hotpotismobile && isset($HOTPOT_OUTPUTFORMAT_DIR[HOTPOT_OUTPUTFORMAT_MOBILE])) {
1568 $this->real_outputformat = HOTPOT_OUTPUTFORMAT_MOBILE;
1569 } else { // PC
1570 if ($this->quiztype=='jmatch' || $this->quiztype=='jmix') {
1571 $this->real_outputformat = HOTPOT_OUTPUTFORMAT_V6_PLUS;
1572 } else {
1573 $this->real_outputformat = HOTPOT_OUTPUTFORMAT_V6;
1578 if ($this->real_outputformat==HOTPOT_OUTPUTFORMAT_V6_PLUS) {
1579 if ($this->quiztype=='jmatch' || $this->quiztype=='jmix') {
1580 $this->draganddrop = 'd'; // prefix for templates (can also be "f" ?)
1582 $this->real_outputformat = HOTPOT_OUTPUTFORMAT_V6;
1585 // set path(s) to template
1586 $this->template_dir = $HOTPOT_OUTPUTFORMAT_DIR[$this->real_outputformat];
1587 $this->template_dirpath = $CFG->hotpottemplate.'/'.$this->template_dir;
1588 $this->template_filepath = $CFG->hotpottemplate.'/'.$this->template_dir.'.php';
1590 // check template class exists
1591 if (!file_exists($this->template_filepath) || !is_readable($this->template_filepath)) {
1592 $this->error = get_string('error_couldnotopentemplate', 'hotpot', $this->template_dir);
1593 if ($this->report_errors) {
1594 error($this->error, $this->course_homeurl);
1596 return;
1599 // get default and output-specfic template classes
1600 include($this->template_filepath);
1602 // create html (using the template for the specified output format)
1603 $this->template = new hotpot_xml_quiz_template($this);
1604 $this->html = &$this->template->html;
1606 } // end $this->create_html
1607 } // end if html/xml file
1608 } // end if $this->read_file
1609 } // end constructor function
1611 function hotpot_convert_relative_urls(&$str) {
1612 $tagopen = '(?:(<)|(&lt;)|(&amp;#x003C;))'; // left angle bracket
1613 $tagclose = '(?(2)>|(?(3)&gt;|(?(4)&amp;#x003E;)))'; // right angle bracket (to match left angle bracket)
1615 $space = '\s+'; // at least one space
1616 $anychar = '(?:[^>]*?)'; // any character
1618 $quoteopen = '("|&quot;|&amp;quot;)'; // open quote
1619 $quoteclose = '\\5'; // close quote (to match open quote)
1621 $replace = "hotpot_convert_relative_url('".$this->get_baseurl()."', '".$this->reference."', '\\1', '\\6', '\\7')";
1623 $tags = array('script'=>'src', 'link'=>'href', 'a'=>'href','img'=>'src','param'=>'value', 'object'=>'data', 'embed'=>'src');
1624 foreach ($tags as $tag=>$attribute) {
1625 if ($tag=='param') {
1626 $url = '\S+?\.\S+?'; // must include a filename and have no spaces
1627 } else {
1628 $url = '.*?';
1630 $search = "%($tagopen$tag$space$anychar$attribute=$quoteopen)($url)($quoteclose$anychar$tagclose)%ise";
1631 $str = preg_replace($search, $replace, $str);
1635 function get_baseurl() {
1636 // set the url base (first time only)
1637 if (!isset($this->baseurl)) {
1638 global $CFG;
1639 if ($CFG->slasharguments) {
1640 $this->baseurl = "$CFG->wwwroot/file.php/$this->filedir/";
1641 } else {
1642 $this->baseurl = "$CFG->wwwroot/file.php?file=/$this->filedir/";
1645 return $this->baseurl;
1649 // insert forms and messages
1651 function remove_nav_buttons() {
1652 $search = '#<!-- Begin(Top|Bottom)NavButtons -->(.*?)<!-- End(Top|Bottom)NavButtons -->#s';
1653 $this->html = preg_replace($search, '', $this->html);
1655 function insert_script($src=HOTPOT_JS) {
1656 $script = '<script src="'.$src.'" type="text/javascript"></script>'."\n";
1657 $this->html = preg_replace('|</head>|i', $script.'</head>', $this->html, 1);
1659 function insert_submission_form($attemptid, $startblock, $endblock, $keep_contents=false) {
1660 $form_name = 'store';
1661 $form_fields = ''
1662 . '<input type="hidden" name="attemptid" value="'.$attemptid.'" />'
1663 . '<input type="hidden" name="starttime" value="" />'
1664 . '<input type="hidden" name="endtime" value="" />'
1665 . '<input type="hidden" name="mark" value="" />'
1666 . '<input type="hidden" name="detail" value="" />'
1667 . '<input type="hidden" name="status" value="" />'
1669 $this->insert_form($startblock, $endblock, $form_name, $form_fields, $keep_contents);
1671 function insert_giveup_form($attemptid, $startblock, $endblock, $keep_contents=false) {
1672 $form_name = ''; // no <form> tag will be generated
1673 $form_fields = ''
1674 . '<button onclick="Finish('.HOTPOT_STATUS_ABANDONED.')" class="FuncButton" '
1675 . 'onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" '
1676 . 'onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" '
1677 . 'onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)">'
1678 . get_string('giveup', 'hotpot').'</button>'
1680 $this->insert_form($startblock, $endblock, $form_name, $form_fields, $keep_contents, true);
1682 function insert_form($startblock, $endblock, $form_name, $form_fields, $keep_contents, $center=false) {
1683 global $CFG;
1684 $search = '#('.preg_quote($startblock).')(.*?)('.preg_quote($endblock).')#s';
1685 $replace = $form_fields;
1686 if ($keep_contents) {
1687 $replace .= '\\2';
1689 if ($form_name) {
1690 $replace = '<form action="'.$CFG->wwwroot.'/mod/hotpot/attempt.php" method="post" name="'.$form_name.'"'.$CFG->frametarget.'>'.$replace.'</form>';
1692 if ($center) {
1693 $replace = '<div style="margin-left:auto; margin-right:auto; text-align: center;">'.$replace.'</div>';
1695 $replace = '\\1'.$replace.'\\3';
1696 $this->html = preg_replace($search, $replace, $this->html, 1);
1698 function insert_message($start_str, $message, $color='red', $align='center') {
1699 $message = '<p align="'.$align.'" style="text-align:'.$align.'"><b><font color="'.$color.'">'.$message."</font></b></p>\n";
1700 $this->html = preg_replace('|'.preg_quote($start_str).'|', $start_str.$message, $this->html, 1);
1703 function adjust_media_urls() {
1705 if ($this->forceplugins) {
1707 // make sure the Moodle media plugin is available
1708 global $CFG;
1709 include_once "$CFG->dirroot/filter/mediaplugin/filter.php";
1711 // exclude swf files from the filter
1712 //$CFG->filter_mediaplugin_ignore_swf = true;
1714 $space = '\s(?:.+\s)?';
1715 $quote = '["'."']?"; // single, double, or no quote
1717 // patterns to media files types and paths
1718 $filetype = "avi|mpeg|mpg|mp3|mov|wmv";
1719 $filepath = ".*?\.($filetype)";
1721 $tagopen = '(?:(<)|(\\\\u003C))'; // left angle-bracket (uses two parenthese)
1722 $tagclose = '(?(1)>|(?(2)\\\\u003E))'; // right angle-bracket (to match the left one)
1723 $tagreopen = '(?(1)<|(?(2)\\\\u003C))'; // another left angle-bracket (to match the first one)
1725 // pattern to match <PARAM> tags which contain the file path
1726 // wmp : url
1727 // quicktime : src
1728 // realplayer : src
1729 // flash : movie (doesn't need replacing)
1730 $param_url = "/{$tagopen}param{$space}name=$quote(?:movie|src|url)$quote{$space}value=$quote($filepath)$quote.*?$tagclose/is";
1732 // pattern to match <a> tags which link to multimedia files
1733 $link_url = "/{$tagopen}a{$space}href=$quote($filepath)$quote.*?$tagclose.*?$tagreopen\/A$tagclose/is";
1735 // extract <object> tags
1736 preg_match_all("/{$tagopen}object\s.*?{$tagclose}(.*?){$tagreopen}\/object{$tagclose}/is", $this->html, $objects);
1738 $i_max = count($objects[0]);
1739 for ($i=0; $i<$i_max; $i++) {
1741 // extract URL from <PARAM> or <A>
1742 $url = '';
1743 if (preg_match($param_url, $objects[3][$i], $matches) || preg_match($link_url, $objects[3][$i], $matches)) {
1744 $url = $matches[3];
1747 if ($url) {
1748 // strip inner tags (e.g. <embed>)
1749 $txt = preg_replace("/$tagopen.*?$tagclose/", '', $objects[3][$i]);
1751 // if url is in the query string, remove the leading characters
1752 $url = preg_replace('/^[^?]*\?([^=]+=[^&]*&)*[^=]+=([^&]*)$/', '$2', $url, 1);
1753 $link = '<a href="'.$url.'">'.$txt.'</a>';
1755 $new_object = mediaplugin_filter($this->filedir, $link);
1756 $new_object = str_replace($link, '', $new_object);
1757 $new_object = str_replace('&amp;', '&', $new_object);
1759 $this->html = str_replace($objects[0][$i], $new_object, $this->html);
1765 } // end class
1767 function hotpot_convert_stylesheets_urls($baseurl, $reference, $css, $stripslashes=true) {
1768 if ($stripslashes) {
1769 $css = stripslashes($css);
1771 $search = '|'.'(?<='.'url'.'\('.')'."(.+?)".'(?='.'\)'.')'.'|ise';
1772 $replace = "hotpot_convert_url('".$baseurl."','".$reference."','\\1')";
1773 return preg_replace($search, $replace, $css);
1775 function hotpot_convert_preloadimages_urls($baseurl, $reference, $urls, $stripslashes=true) {
1776 if ($stripslashes) {
1777 $urls = stripslashes($urls);
1779 $search = '|(?<=["'."'])([^,'".'"]*?)(?=["'."'])|ise";
1780 $replace = "hotpot_convert_url('".$baseurl."','".$reference."','\\1')";
1781 return preg_replace($search, $replace, $urls);
1783 function hotpot_convert_navbutton_url($baseurl, $reference, $url, $course, $stripslashes=true) {
1784 global $CFG;
1786 if ($stripslashes) {
1787 $url = stripslashes($url);
1789 $url = hotpot_convert_url($baseurl, $reference, $url, false);
1791 // is this a $url for another hotpot in this course ?
1792 if (preg_match("|^$baseurl(.*)$|", $url, $matches)) {
1793 if ($records = get_records_select('hotpot', "course='$course' AND reference='".$matches[1]."'")) {
1794 $ids = array_keys($records);
1795 $url = "$CFG->wwwroot/mod/hotpot/view.php?hp=".$ids[0];
1799 return $url;
1802 function hotpot_convert_relative_url($baseurl, $reference, $opentag, $url, $closetag, $stripslashes=true) {
1803 if ($stripslashes) {
1804 $opentag = stripslashes($opentag);
1805 $url = stripslashes($url);
1806 $closetag = stripslashes($closetag);
1809 // catch <PARAM name="FlashVars" value="TheSound=soundfile.mp3">
1810 // ampersands can appear as "&", "&amp;" or "&amp;#x0026;amp;"
1811 if (preg_match('|^'.'\w+=[^&]+'.'('.'&((amp;#x0026;)?amp;)?'.'\w+=[^&]+)*'.'$|', $url)) {
1812 $query = $url;
1813 $url = '';
1814 $fragment = '';
1816 // parse the $url into $matches
1817 // [1] path
1818 // [2] query string, if any
1819 // [3] anchor fragment, if any
1820 } else if (preg_match('|^'.'([^?]*)'.'((?:\\?[^#]*)?)'.'((?:#.*)?)'.'$|', $url, $matches)) {
1821 $url = $matches[1];
1822 $query = $matches[2];
1823 $fragment = $matches[3];
1825 // these appears to be no query or fragment in this url
1826 } else {
1827 $query = '';
1828 $fragment = '';
1831 if ($url) {
1832 $url = hotpot_convert_url($baseurl, $reference, $url, false);
1835 if ($query) {
1836 $search = '#'.'(file|src|thesound)='."([^&]+)".'#ise';
1837 $replace = "'\\1='.hotpot_convert_url('".$baseurl."','".$reference."','\\2')";
1838 $query = preg_replace($search, $replace, $query);
1841 $url = $opentag.$url.$query.$fragment.$closetag;
1843 return $url;
1846 function hotpot_convert_url($baseurl, $reference, $url, $stripslashes=true) {
1847 // maintain a cache of converted urls
1848 static $HOTPOT_RELATIVE_URLS = array();
1850 if ($stripslashes) {
1851 $url = stripslashes($url);
1854 // is this an absolute url? (or javascript pseudo url)
1855 if (preg_match('%^(http://|/|javascript:)%i', $url)) {
1856 // do nothing
1858 // has this relative url already been converted?
1859 } else if (isset($HOTPOT_RELATIVE_URLS[$url])) {
1860 $url = $HOTPOT_RELATIVE_URLS[$url];
1862 } else {
1863 $relativeurl = $url;
1865 // get the subdirectory, $dir, of the quiz $reference
1866 $dir = dirname($reference);
1868 // allow for leading "./" and "../"
1869 while (preg_match('|^(\.{1,2})/(.*)$|', $url, $matches)) {
1870 if ($matches[1]=='..') {
1871 $dir = dirname($dir);
1873 $url = $matches[2];
1876 // add subdirectory, $dir, to $baseurl, if necessary
1877 if ($dir && $dir<>'.') {
1878 $baseurl .= "$dir/";
1881 // prefix $url with $baseurl
1882 $url = "$baseurl$url";
1884 // add url to cache
1885 $HOTPOT_RELATIVE_URLS[$relativeurl] = $url;
1887 return $url;
1890 // ===================================================
1891 // function for adding attempt questions and responses
1892 // ===================================================
1894 function hotpot_add_attempt_details(&$attempt) {
1896 // encode ampersands so that HTML entities are preserved in the XML parser
1897 // N.B. ampersands inside <![CDATA[ ]]> blocks do NOT need to be encoded
1899 $old = &$attempt->details; // shortcut to "old" details
1900 $new = '';
1901 $str_start = 0;
1902 while (($cdata_start = strpos($old, '<![CDATA[', $str_start)) && ($cdata_end = strpos($old, ']]>', $cdata_start))) {
1903 $cdata_end += 3;
1904 $new .= str_replace('&', '&amp;', substr($old, $str_start, $cdata_start-$str_start)).substr($old, $cdata_start, $cdata_end-$cdata_start);
1905 $str_start = $cdata_end;
1907 $new .= str_replace('&', '&amp;', substr($old, $str_start));
1908 unset($old);
1910 // parse the attempt details as xml
1911 $details = new hotpot_xml_tree($new, "['hpjsresult']['#']");
1913 $num = -1;
1914 $q_num = -1;
1915 $question = NULL;
1916 $reponse = NULL;
1918 $i = 0;
1919 $tags = 'fields,field';
1921 while (($field="[$i]['#']") && $details->xml_value($tags, $field)) {
1923 $name = $details->xml_value($tags, $field."['fieldname'][0]['#']");
1924 $data = $details->xml_value($tags, $field."['fielddata'][0]['#']");
1926 // parse the field name into $matches
1927 // [1] quiz type
1928 // [2] attempt detail name
1929 if (preg_match('/^(\w+?)_(\w+)$/', $name, $matches)) {
1930 $quiztype = strtolower($matches[1]);
1931 $name = strtolower($matches[2]);
1933 // parse the attempt detail $name into $matches
1934 // [1] question number
1935 // [2] question detail name
1936 if (preg_match('/^q(\d+)_(\w+)$/', $name, $matches)) {
1937 $num = $matches[1];
1938 $name = strtolower($matches[2]);
1939 $data = addslashes($data);
1941 // adjust JCross question numbers
1942 if (preg_match('/^(across|down)(.*)$/', $name, $matches)) {
1943 $num .= '_'.$matches[1]; // e.g. 01_across, 02_down
1944 $name = $matches[2];
1945 if (substr($name, 0, 1)=='_') {
1946 $name = substr($name, 1); // remove leading '_'
1950 // is this a new question (or the first one)?
1951 if ($q_num<>$num) {
1953 // add previous question and response, if any
1954 hotpot_add_response($attempt, $question, $response);
1956 // initialize question object
1957 $question = NULL;
1958 $question->name = '';
1959 $question->text = '';
1960 $question->hotpot = $attempt->hotpot;
1962 // initialize response object
1963 $response = NULL;
1964 $response->attempt = $attempt->id;
1966 // update question number
1967 $q_num = $num;
1970 // adjust field name and value, and set question type
1971 // (may not be necessary one day)
1972 hotpot_adjust_response_field($quiztype, $question, $num, $name, $data);
1974 // add $data to the question/response details
1975 switch ($name) {
1976 case 'name':
1977 case 'type':
1978 $question->$name = $data;
1979 break;
1980 case 'text':
1981 $question->$name = hotpot_string_id($data);
1982 break;
1984 case 'correct':
1985 case 'ignored':
1986 case 'wrong':
1987 $response->$name = hotpot_string_ids($data);
1988 break;
1990 case 'score':
1991 case 'weighting':
1992 case 'hints':
1993 case 'clues':
1994 case 'checks':
1995 $response->$name = intval($data);
1996 break;
1999 } else { // attempt details
2001 // adjust field name and value
2002 hotpot_adjust_response_field($quiztype, $question, $num='', $name, $data);
2004 // add $data to the attempt details
2005 if ($name=='penalties') {
2006 $attempt->$name = intval($data);
2011 $i++;
2012 } // end while
2014 // add the final question and response, if any
2015 hotpot_add_response($attempt, $question, $response);
2017 function hotpot_add_response(&$attempt, &$question, &$response) {
2018 global $db, $next_url;
2020 $loopcount = 1;
2022 $looping = isset($question) && isset($question->name) && isset($response);
2023 while ($looping) {
2025 if ($loopcount==1) {
2026 $questionname = $question->name;
2029 $question->md5key = md5($question->name);
2030 if (!$question->id = get_field('hotpot_questions', 'id', 'hotpot', $attempt->hotpot, 'md5key', $question->md5key, 'name', $question->name)) {
2031 // add question record
2032 if (!$question->id = insert_record('hotpot_questions', $question)) {
2033 error("Could not add question record (attempt_id=$attempt->id): ".$db->ErrorMsg(), $next_url);
2037 if (record_exists('hotpot_responses', 'attempt', $attempt->id, 'question', $question->id)) {
2038 // there is already a response to this question for this attempt
2039 // probably because this quiz has two questions with the same text
2040 // e.g. Which one of these answers is correct?
2042 // To workaround this, we create new question names
2043 // e.g. Which one of these answers is correct? (2)
2044 // until we get a question name for which there is no response yet on this attempt
2046 $loopcount++;
2047 $question->name = "$questionname ($loopcount)";
2049 // This method fails to correctly identify questions in
2050 // quizzes which allow questions to be shuffled or omitted.
2051 // As yet, there is no workaround for such cases.
2053 } else {
2054 $response->question = $question->id;
2056 // add response record
2057 if(!$response->id = insert_record('hotpot_responses', $response)) {
2058 error("Could not add response record (attempt_id=$attempt->id, question_id=$question->id): ".$db->ErrorMsg(), $next_url);
2061 // we can stop looping now
2062 $looping = false;
2064 } // end while
2066 function hotpot_adjust_response_field($quiztype, &$question, &$num, &$name, &$data) {
2067 switch ($quiztype) {
2068 case 'jbc':
2069 $question->type = HOTPOT_JCB;
2070 switch ($name) {
2071 case 'right':
2072 $name = 'correct';
2073 break;
2075 break;
2076 case 'jcloze':
2077 $question->type = HOTPOT_JCLOZE;
2078 if (is_numeric($num)) {
2079 $question->name = $num;
2081 switch ($name) {
2082 case 'penalties':
2083 if (is_numeric($num)) {
2084 $name = 'checks';
2085 if (is_numeric($data)) {
2086 $data++;
2089 break;
2090 case 'clue_shown':
2091 $name = 'clues';
2092 $data = ($data=='YES' ? 1 : 0);
2093 break;
2094 case 'clue_text':
2095 $name = 'text';
2096 break;
2098 break;
2099 case 'jcross':
2100 $question->type = HOTPOT_JCROSS;
2101 $question->name = $num;
2102 switch ($name) {
2103 case '': // HotPot v2.0.x
2104 $name = 'correct';
2105 break;
2106 case 'clue':
2107 $name = 'text';
2108 break;
2110 break;
2111 case 'jmatch':
2112 $question->type = HOTPOT_JMATCH;
2113 switch ($name) {
2114 case 'attempts':
2115 $name = 'penalties';
2116 if (is_numeric($data) && $data>0) {
2117 $data--;
2119 break;
2120 case 'lhs':
2121 $name = 'name';
2122 break;
2123 case 'rhs':
2124 $name = 'correct';
2125 break;
2127 break;
2128 case 'jmix':
2129 $question->type = HOTPOT_JMIX;
2130 $question->name = $num;
2131 switch ($name) {
2132 // keep these in for "restore" of courses
2133 // which were backed up with HotPot v2.0.x
2134 case 'wrongguesses':
2135 $name = 'checks';
2136 if (is_numeric($data)) {
2137 $data++;
2139 break;
2140 case 'right':
2141 $name = 'correct';
2142 break;
2144 break;
2145 break;
2146 case 'jquiz':
2147 switch ($name) {
2148 case 'type':
2149 $data = HOTPOT_JQUIZ;
2150 switch ($data) {
2151 case 'multiple-choice':
2152 $data .= '.'.HOTPOT_JQUIZ_MULTICHOICE;
2153 break;
2154 case 'short-answer':
2155 $data .= '.'.HOTPOT_JQUIZ_SHORTANSWER;
2156 break;
2157 case 'hybrid':
2158 $data .= '.'.HOTPOT_JQUIZ_HYBRID;
2159 break;
2160 case 'multi-select':
2161 $data .= '.'.HOTPOT_JQUIZ_MULTISELECT;
2162 case 'n/a':
2163 default:
2164 // do nothing more
2165 break;
2167 break;
2168 case 'question':
2169 $name = 'name';
2170 break;
2172 break;
2174 case 'rhubarb':
2175 $question->type = HOTPOT_TEXTOYS_RHUBARB;
2176 if (empty($question->name)) {
2177 $question->name = $num;
2179 break;
2181 case 'sequitur':
2182 $question->type = HOTPOT_TEXTOYS_SEQUITUR;
2183 break;
2186 function hotpot_string_ids($field_value) {
2187 $ids = array();
2188 $strings = explode(',', $field_value);
2189 foreach($strings as $str) {
2190 if ($id = hotpot_string_id($str)) {
2191 $ids[] = $id;
2194 return implode(',', $ids);
2196 function hotpot_string_id($str) {
2197 $id = '';
2198 if (isset($str) && $str<>'') {
2200 // get the id from the table if it is already there
2201 $md5key = md5($str);
2202 if (!$id = get_field('hotpot_strings', 'id', 'md5key', $md5key, 'string', $str)) {
2204 // create a string record
2205 $record = new stdClass();
2206 $record->string = $str;
2207 $record->md5key = $md5key;
2209 // try and add the new string record
2210 if (!$id = insert_record('hotpot_strings', $record)) {
2211 global $db;
2212 error("Could not add string record for '".htmlspecialchars($str)."': ".$db->ErrorMsg());
2216 return $id;
2219 function hotpot_get_view_actions() {
2220 return array('view','view all','report');
2223 function hotpot_get_post_actions() {
2224 return array('attempt','review','submit');
2227 if (!function_exists('file_get_contents')) {
2228 // add this function for php version<4.3
2229 function file_get_contents($filepath) {
2230 $contents = file($filepath);
2231 if (is_array($contents)) {
2232 $contents = implode('', $contents);
2234 return $contents;
2237 if (!function_exists('html_entity_decode')) {
2238 // add this function for php version<4.3
2239 function html_entity_decode($str) {
2240 $t = get_html_translation_table(HTML_ENTITIES);
2241 $t = array_flip($t);
2242 return strtr($str, $t);
2247 // required for Moodle 1.x
2248 if (!isset($CFG->pixpath)) {
2249 $CFG->pixpath = "$CFG->wwwroot/pix";
2252 if (!function_exists('fullname')) {
2253 // add this function for Moodle 1.x
2254 function fullname($user) {
2255 return "$user->firstname $user->lastname";
2258 if (!function_exists('get_user_preferences')) {
2259 // add this function for Moodle 1.x
2260 function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
2261 return $default;
2264 if (!function_exists('set_user_preference')) {
2265 // add this function for Moodle 1.x
2266 function set_user_preference($name, $value, $otheruser=NULL) {
2267 return false;
2270 if (!function_exists('get_coursemodule_from_id')) {
2271 // add this function for Moodle < 1.5.4
2272 function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
2273 global $CFG;
2274 return get_record_sql("
2275 SELECT
2276 cm.*, m.name, md.name as modname
2277 FROM
2278 {$CFG->prefix}course_modules cm,
2279 {$CFG->prefix}modules md,
2280 {$CFG->prefix}$modulename m
2281 WHERE
2282 ".($courseid ? "cm.course = '$courseid' AND " : '')."
2283 cm.id = '$cmid' AND
2284 cm.instance = m.id AND
2285 md.name = '$modulename' AND
2286 md.id = cm.module
2290 if (!function_exists('get_coursemodule_from_instance')) {
2291 // add this function for Moodle < 1.5.4
2292 function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
2293 global $CFG;
2294 return get_record_sql("
2295 SELECT
2296 cm.*, m.name, md.name as modname
2297 FROM
2298 {$CFG->prefix}course_modules cm,
2299 {$CFG->prefix}modules md,
2300 {$CFG->prefix}$modulename m
2301 WHERE
2302 ".($courseid ? "cm.course = '$courseid' AND" : '')."
2303 cm.instance = m.id AND
2304 md.name = '$modulename' AND
2305 md.id = cm.module AND
2306 m.id = '$instance'
2310 function hotpot_utf8_to_html_entity($char) {
2311 // http://www.zend.com/codex.php?id=835&single=1
2313 // array used to figure what number to decrement from character order value
2314 // according to number of characters used to map unicode to ascii by utf-8
2315 static $HOTPOT_UTF8_DECREMENT = array(
2316 1=>0, 2=>192, 3=>224, 4=>240
2319 // the number of bits to shift each character by
2320 static $HOTPOT_UTF8_SHIFT = array(
2321 1=>array(0=>0),
2322 2=>array(0=>6, 1=>0),
2323 3=>array(0=>12, 1=>6, 2=>0),
2324 4=>array(0=>18, 1=>12, 2=>6, 3=>0)
2327 $dec = 0;
2328 $len = strlen($char);
2329 for ($pos=0; $pos<$len; $pos++) {
2330 $ord = ord ($char{$pos});
2331 $ord -= ($pos ? 128 : $HOTPOT_UTF8_DECREMENT[$len]);
2332 $dec += ($ord << $HOTPOT_UTF8_SHIFT[$len][$pos]);
2334 return '&#x'.sprintf('%04X', $dec).';';
2337 function hotpot_print_show_links($course, $location, $reference, $actions='', $spacer=' &nbsp; ', $new_window=false, $return=false) {
2338 global $CFG;
2339 if (is_string($actions)) {
2340 if (empty($actions)) {
2341 $actions = 'showxmlsource,showxmltree,showhtmlsource';
2343 $actions = explode(',', $actions);
2345 $strenterafilename = get_string('enterafilename', 'hotpot');
2346 $html = <<<END_OF_SCRIPT
2347 <script type="text/javascript">
2348 //<![CDATA[
2349 function setLink(lnk) {
2350 var form = null;
2351 if (document.forms['mform1']) {
2352 var form = document.forms['mform1'];
2353 } else if (document.forms['form']) {
2354 var form = document.forms['form'];
2356 return setLinkAttribute(lnk, 'reference', form) && setLinkAttribute(lnk, 'location', form);
2358 function setLinkAttribute(lnk, name, form) {
2359 // set link attribute value using
2360 // f(orm) name and e(lement) name
2362 var r = true; // result
2364 var obj = (form) ? form.elements[name] : null;
2365 if (obj) {
2366 r = false;
2367 var v = getObjValue(obj);
2368 if (v=='') {
2369 alert('$strenterafilename');
2370 } else {
2371 var s = lnk.href;
2372 var i = s.indexOf('?');
2373 if (i>=0) {
2374 i = s.indexOf(name+'=', i+1);
2375 if (i>=0) {
2376 i += name.length+1;
2377 var ii = s.indexOf('&', i);
2378 if (ii<0) {
2379 ii = s.length;
2381 lnk.href = s.substring(0, i) + v + s.substring(ii);
2382 r = true;
2387 return r;
2389 function getObjValue(obj) {
2390 var v = ''; // the value
2391 var t = (obj && obj.type) ? obj.type : "";
2392 if (t=="text" || t=="textarea" || t=="hidden") {
2393 v = obj.value;
2394 } else if (t=="select-one" || t=="select-multiple") {
2395 var l = obj.options.length;
2396 for (var i=0; i<l; i++) {
2397 if (obj.options[i].selected) {
2398 v += (v=="" ? "" : ",") + obj.options[i].value;
2402 return v;
2404 function getDir(s) {
2405 if (s.charAt(0)!='/') {
2406 s = '/' + s;
2408 var i = s.lastIndexOf('/');
2409 return s.substring(0, i);
2411 //]]>
2412 </script>
2413 END_OF_SCRIPT;
2415 foreach ($actions as $action) {
2416 $html .= $spacer
2417 . '<a href="'
2418 . $CFG->wwwroot.'/mod/hotpot/show.php'
2419 . '?course='.$course.'&location='.$location.'&reference='.urlencode($reference).'&action='.$action
2420 . '"'
2421 . ' onclick="return setLink(this);"'
2422 . ($new_window ? ' target="_blank"' : '')
2423 . '>'.get_string($action, 'hotpot').'</a>'
2426 $html = '<span class="helplink">'.$html.'</span>';
2427 if ($return) {
2428 return $html;
2429 } else {
2430 print $html;