Example #1
1
function survey_print_multi($question)
{
    global $USER, $db, $qnum, $checklist;
    $stripreferthat = get_string("ipreferthat", "survey");
    $strifoundthat = get_string("ifoundthat", "survey");
    $strdefault = get_string('default');
    $strresponses = get_string('responses', 'survey');
    print_heading($question->text, null, 3, 'questiontext');
    echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\">";
    $options = explode(",", $question->options);
    $numoptions = count($options);
    $oneanswer = $question->type == 1 || $question->type == 2 ? true : false;
    if ($question->type == 2) {
        $P = "P";
    } else {
        $P = "";
    }
    echo "<tr class=\"smalltext\"><th scope=\"row\">{$strresponses}</th>";
    while (list($key, $val) = each($options)) {
        echo "<th scope=\"col\" class=\"hresponse\">{$val}</th>\n";
    }
    echo "<th>&nbsp;</th></tr>\n";
    if ($oneanswer) {
        echo "<tr><th scope=\"col\" colspan=\"6\">{$question->intro}</th></tr>\n";
    } else {
        echo "<tr><th scope=\"col\" colspan=\"7\">{$question->intro}</th></tr>\n";
    }
    $subquestions = get_records_list("survey_questions", "id", $question->multi);
    foreach ($subquestions as $q) {
        $qnum++;
        $rowclass = survey_question_rowclass($qnum);
        if ($q->text) {
            $q->text = get_string($q->text, "survey");
        }
        echo "<tr class=\"{$rowclass} rblock\">";
        if ($oneanswer) {
            echo "<th scope=\"row\" class=\"optioncell\">";
            echo "<b class=\"qnumtopcell\">{$qnum}</b> &nbsp; ";
            echo $q->text . "</th>\n";
            for ($i = 1; $i <= $numoptions; $i++) {
                $hiddentext = get_accesshide($options[$i - 1]);
                $id = "q{$P}" . $q->id . "_{$i}";
                echo "<td><label for=\"{$id}\"><input type=\"radio\" name=\"q{$P}{$q->id}\" id=\"{$id}\" value=\"{$i}\" />{$hiddentext}</label></td>";
            }
            $default = get_accesshide($strdefault, 'label', '', "for=\"q{$P}{$q->id}\"");
            echo "<td class=\"whitecell\"><input type=\"radio\" name=\"q{$P}{$q->id}\" id=\"q{$P}" . $q->id . "_D\" value=\"0\" checked=\"checked\" />{$default}</td>";
            $checklist["q{$P}{$q->id}"] = $numoptions;
        } else {
            // yu : fix for MDL-7501, possibly need to use user flag as this is quite ugly.
            echo "<th scope=\"row\" class=\"optioncell\">";
            echo "<b class=\"qnumtopcell\">{$qnum}</b> &nbsp; ";
            $qnum++;
            echo "<span class=\"preferthat smalltext\">{$stripreferthat}</span> &nbsp; ";
            echo "<span class=\"option\">{$q->text}</span></th>\n";
            for ($i = 1; $i <= $numoptions; $i++) {
                $hiddentext = get_accesshide($options[$i - 1]);
                $id = "qP" . $q->id . "_{$i}";
                echo "<td><label for=\"{$id}\"><input type=\"radio\" name=\"qP{$q->id}\" id=\"{$id}\" value=\"{$i}\" />{$hiddentext}</label></td>";
            }
            $default = get_accesshide($strdefault, 'label', '', "for=\"qP{$q->id}\"");
            echo "<td><input type=\"radio\" name=\"qP{$q->id}\" id=\"qP{$q->id}\" value=\"0\" checked=\"checked\" />{$default}</td>";
            echo "</tr>";
            echo "<tr class=\"{$rowclass} rblock\">";
            echo "<th scope=\"row\" class=\"optioncell\">";
            echo "<b class=\"qnumtopcell\">{$qnum}</b> &nbsp; ";
            echo "<span class=\"foundthat smalltext\">{$strifoundthat}</span> &nbsp; ";
            echo "<span class=\"option\">{$q->text}</span></th>\n";
            for ($i = 1; $i <= $numoptions; $i++) {
                $hiddentext = get_accesshide($options[$i - 1]);
                $id = "q" . $q->id . "_{$i}";
                echo "<td><label for=\"{$id}\"><input type=\"radio\" name=\"q{$q->id}\" id=\"{$id}\" value=\"{$i}\" />{$hiddentext}</label></td>";
            }
            $default = get_accesshide($strdefault, 'label', '', "for=\"q{$q->id}\"");
            echo "<td class=\"buttoncell\"><input type=\"radio\" name=\"q{$q->id}\" id=\"q{$q->id}\" value=\"0\" checked=\"checked\" />{$default}</td>";
            $checklist["qP{$q->id}"] = $numoptions;
            $checklist["q{$q->id}"] = $numoptions;
        }
        echo "</tr>\n";
    }
    echo "</table>";
}
Example #2
0
/**
 * External function for retrieving module data.
 *
 * Using external method so we can cache results
 * to improve performance for all page_module
 * instances.
 *
 * @param int $cmid Course Module ID
 * @return array
 **/
function block_page_module_init($cmid)
{
    global $COURSE, $CFG, $PAGE, $BLOCK_PAGE_MODULE;
    static $page = false, $baseurl = '';
    if (!$page) {
        if (!empty($PAGE) and get_class($PAGE) == 'format_page') {
            $page = $PAGE->get_formatpage();
        } else {
            require_once $CFG->dirroot . '/course/format/page/lib.php';
            if (!($page = page_get_current_page())) {
                $page = new stdClass();
                $page->id = 0;
            }
        }
        if ($COURSE->id == SITEID) {
            $baseurl = "{$CFG->wwwroot}/index.php?id={$COURSE->id}&amp;page={$page->id}";
        } else {
            $baseurl = "{$CFG->wwwroot}/course/view.php?id={$COURSE->id}&amp;page={$page->id}";
        }
        if (!empty($page->id)) {
            // Since we know what page will be printed, lets
            // get all of our records in bulk and cache the results
            if ($cms = get_records_sql("SELECT c.*\n                                           FROM {$CFG->prefix}course_modules c,\n                                                {$CFG->prefix}format_page p,\n                                                {$CFG->prefix}format_page_items i\n                                          WHERE i.cmid = c.id\n                                            AND p.id = i.pageid\n                                            AND p.id = {$page->id}")) {
                // Save for later
                $BLOCK_PAGE_MODULE['cms'] = $cms;
                if ($modules = get_records('modules')) {
                    // Save for later
                    $BLOCK_PAGE_MODULE['modules'] = $modules;
                    $mods = array();
                    foreach ($cms as $cm) {
                        $mods[$modules[$cm->module]->name][] = $cm->instance;
                    }
                    $instances = array();
                    foreach ($mods as $modname => $instanceids) {
                        if ($records = get_records_list($modname, 'id', implode(',', $instanceids))) {
                            $instances[$modname] = $records;
                        }
                    }
                    // Save for later
                    $BLOCK_PAGE_MODULE['instances'] = $instances;
                }
            }
        } else {
            // OK, we cannot do anything cool, make sure we dont break rest of the script
            $BLOCK_PAGE_MODULE = array('cms' => array(), 'modules' => array(), 'instances' => array());
        }
    }
    if (!($cm = block_page_module_get_cm($cmid, $page->id))) {
        return false;
    }
    if (!($module = block_page_module_get_module($cm->module))) {
        return false;
    }
    if (!($moduleinstance = block_page_module_get_instance($module->name, $cm->instance))) {
        return false;
    }
    return array($cm, $module, $moduleinstance, $COURSE, $page, $baseurl);
}
Example #3
0
 function get_question_options(&$question)
 {
     global $QTYPES;
     // Get relevant data indexed by positionkey from the multianswers table
     if (!($sequence = get_field('question_multianswer', 'sequence', 'question', $question->id))) {
         notify('Error: Cloze question ' . $question->id . ' is missing question options!');
         return false;
     }
     $wrappedquestions = get_records_list('question', 'id', $sequence, 'id ASC');
     // We want an array with question ids as index and the positions as values
     $sequence = array_flip(explode(',', $sequence));
     array_walk($sequence, create_function('&$val', '$val++;'));
     foreach ($wrappedquestions as $wrapped) {
         if (!$QTYPES[$wrapped->qtype]->get_question_options($wrapped)) {
             notify("Unable to get options for questiontype {$wrapped->qtype} (id={$wrapped->id})");
         }
         // for wrapped questions the maxgrade is always equal to the defaultgrade,
         // there is no entry in the question_instances table for them
         $wrapped->maxgrade = $wrapped->defaultgrade;
         $question->options->questions[$sequence[$wrapped->id]] = clone $wrapped;
         // ??? Why do we need a clone here?
     }
     return true;
 }
Example #4
0
 /**
  * Decode links in question type specific tables.
  * @return bool success or failure.
  */
 function decode_content_links_caller($questionids, $restore, &$i)
 {
     $status = true;
     // Decode links in the question_multichoice table.
     if ($multichoices = get_records_list('question_multichoice', 'question', implode(',', $questionids), '', 'id, correctfeedback, partiallycorrectfeedback, incorrectfeedback')) {
         foreach ($multichoices as $multichoice) {
             $correctfeedback = restore_decode_content_links_worker($multichoice->correctfeedback, $restore);
             $partiallycorrectfeedback = restore_decode_content_links_worker($multichoice->partiallycorrectfeedback, $restore);
             $incorrectfeedback = restore_decode_content_links_worker($multichoice->incorrectfeedback, $restore);
             if ($correctfeedback != $multichoice->correctfeedback || $partiallycorrectfeedback != $multichoice->partiallycorrectfeedback || $incorrectfeedback != $multichoice->incorrectfeedback) {
                 $subquestion->correctfeedback = addslashes($correctfeedback);
                 $subquestion->partiallycorrectfeedback = addslashes($partiallycorrectfeedback);
                 $subquestion->incorrectfeedback = addslashes($incorrectfeedback);
                 if (!update_record('question_multichoice', $multichoice)) {
                     $status = false;
                 }
             }
             // Do some output.
             if (++$i % 5 == 0 && !defined('RESTORE_SILENTLY')) {
                 echo ".";
                 if ($i % 100 == 0) {
                     echo "<br />";
                 }
                 backup_flush(300);
             }
         }
     }
     return $status;
 }
Example #5
0
 function get_content()
 {
     global $USER, $CFG;
     if ($this->content !== NULL) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->text = '';
     $this->content->footer = '';
     if (empty($this->instance)) {
         return $this->content;
     }
     if ($this->instance->pagetype == 'course-view') {
         // We need to see if we are monitoring a quiz
         $quizid = empty($this->config->quizid) ? 0 : $this->config->quizid;
         $courseid = $this->instance->pageid;
     } else {
         // Assuming we are displayed in the quiz view page
         $quizid = $this->instance->pageid;
         // A trick to take advantage of instance config and save queries
         if (empty($this->config->courseid)) {
             $modrecord = get_record('modules', 'name', 'quiz');
             $cmrecord = get_record('course_modules', 'module', $modrecord->id, 'instance', $quizid);
             $this->config->courseid = intval($cmrecord->course);
             $this->instance_config_commit();
         }
         $courseid = $this->config->courseid;
     }
     $context = get_context_instance(CONTEXT_COURSE, $courseid);
     if (empty($quizid)) {
         $this->content->text = get_string('error_emptyquizid', 'block_quiz_results');
         return $this->content;
     }
     // Get the quiz record
     $quiz = get_record('quiz', 'id', $quizid);
     if (empty($quiz)) {
         $this->content->text = get_string('error_emptyquizrecord', 'block_quiz_results');
         return $this->content;
     }
     // Get the grades for this quiz
     $grades = get_records('quiz_grades', 'quiz', $quizid, 'grade, timemodified DESC');
     if (empty($grades)) {
         // No grades, sorry
         // The block will hide itself in this case
         return $this->content;
     }
     if (empty($this->config->showbest) && empty($this->config->showworst)) {
         $this->content->text = get_string('configuredtoshownothing', 'block_quiz_results');
         return $this->content;
     }
     $groupmode = NOGROUPS;
     $best = array();
     $worst = array();
     $nameformat = intval(empty($this->config->nameformat) ? B_QUIZRESULTS_NAME_FORMAT_FULL : $this->config->nameformat);
     // If the block is configured to operate in group mode, or if the name display format
     // is other than "fullname", then we need to retrieve the full course record
     if (!empty($this->config->usegroups) || $nameformat != B_QUIZRESULTS_NAME_FORMAT_FULL) {
         $course = get_record_select('course', 'id = ' . $courseid, 'groupmode, groupmodeforce, student');
     }
     if (!empty($this->config->usegroups)) {
         // The block was configured to operate in group mode
         if ($course->groupmodeforce) {
             $groupmode = $course->groupmode;
         } else {
             $module = get_record_sql('SELECT cm.groupmode FROM ' . $CFG->prefix . 'modules m LEFT JOIN ' . $CFG->prefix . 'course_modules cm ON m.id = cm.module WHERE m.name = \'quiz\' AND cm.instance = ' . $quizid);
             $groupmode = $module->groupmode;
         }
         // The actual groupmode for the quiz is now known to be $groupmode
     }
     if (has_capability('moodle/site:accessallgroups', $context) && $groupmode == SEPARATEGROUPS) {
         // We 'll make an exception in this case
         $groupmode = VISIBLEGROUPS;
     }
     switch ($groupmode) {
         case VISIBLEGROUPS:
             // Display group-mode results
             $groups = groups_get_all_groups($courseid);
             if (empty($groups)) {
                 // No groups exist, sorry
                 $this->content->text = get_string('error_nogroupsexist', 'block_quiz_results');
                 return $this->content;
             }
             // Find out all the userids which have a submitted grade
             $userids = array();
             foreach ($grades as $grade) {
                 $userids[] = $grade->userid;
             }
             // Now find which groups these users belong in
             $groupofuser = get_records_sql('SELECT m.userid, m.groupid, g.name FROM ' . $CFG->prefix . 'groups g LEFT JOIN ' . $CFG->prefix . 'groups_members m ON g.id = m.groupid ' . 'WHERE g.courseid = ' . $courseid . ' AND m.userid IN (' . implode(',', $userids) . ')');
             $groupgrades = array();
             // OK... now, iterate the grades again and sum them up for each group
             foreach ($grades as $grade) {
                 if (isset($groupofuser[$grade->userid])) {
                     // Count this result only if the user is in a group
                     $groupid = $groupofuser[$grade->userid]->groupid;
                     if (!isset($groupgrades[$groupid])) {
                         $groupgrades[$groupid] = array('sum' => (double) $grade->grade, 'number' => 1, 'group' => $groupofuser[$grade->userid]->name);
                     } else {
                         $groupgrades[$groupid]['sum'] += $grade->grade;
                         ++$groupgrades[$groupid]['number'];
                     }
                 }
             }
             foreach ($groupgrades as $groupid => $groupgrade) {
                 $groupgrades[$groupid]['average'] = $groupgrades[$groupid]['sum'] / $groupgrades[$groupid]['number'];
             }
             // Sort groupgrades according to average grade, ascending
             uasort($groupgrades, create_function('$a, $b', 'if($a["average"] == $b["average"]) return 0; return ($a["average"] > $b["average"] ? 1 : -1);'));
             // How many groups do we have with graded member submissions to show?
             $numbest = empty($this->config->showbest) ? 0 : min($this->config->showbest, count($groupgrades));
             $numworst = empty($this->config->showworst) ? 0 : min($this->config->showworst, count($groupgrades) - $numbest);
             // Collect all the group results we are going to use in $best and $worst
             $remaining = $numbest;
             $groupgrade = end($groupgrades);
             while ($remaining--) {
                 $best[key($groupgrades)] = $groupgrade['average'];
                 $groupgrade = prev($groupgrades);
             }
             $remaining = $numworst;
             $groupgrade = reset($groupgrades);
             while ($remaining--) {
                 $worst[key($groupgrades)] = $groupgrade['average'];
                 $groupgrade = next($groupgrades);
             }
             // Ready for output!
             $gradeformat = intval(empty($this->config->gradeformat) ? B_QUIZRESULTS_GRADE_FORMAT_PCT : $this->config->gradeformat);
             if ($this->instance->pagetype != 'mod-quiz-view') {
                 // Don't show header and link to the quiz if we ARE at the quiz...
                 $this->content->text .= '<h1><a href="' . $CFG->wwwroot . '/mod/quiz/view.php?q=' . $quizid . '">' . $quiz->name . '</a></h1>';
             }
             if ($nameformat = B_QUIZRESULTS_NAME_FORMAT_FULL) {
                 if (has_capability('moodle/course:managegroups', $context)) {
                     $grouplink = $CFG->wwwroot . '/group/overview.php?courseid=' . $courseid . '&amp;id=';
                 } else {
                     if (has_capability('moodle/course:viewparticipants', $context)) {
                         $grouplink = $CFG->wwwroot . '/user/index.php?id=' . $courseid . '&amp;group=';
                     } else {
                         $grouplink = '';
                     }
                 }
             }
             $rank = 0;
             if (!empty($best)) {
                 $this->content->text .= '<table class="grades"><caption>';
                 $this->content->text .= $numbest == 1 ? get_string('bestgroupgrade', 'block_quiz_results') : get_string('bestgroupgrades', 'block_quiz_results', $numbest);
                 $this->content->text .= '</caption><colgroup class="number" /><colgroup class="name" /><colgroup class="grade" /><tbody>';
                 foreach ($best as $groupid => $averagegrade) {
                     switch ($nameformat) {
                         case B_QUIZRESULTS_NAME_FORMAT_ANON:
                         case B_QUIZRESULTS_NAME_FORMAT_ID:
                             $thisname = get_string('group');
                             break;
                         default:
                         case B_QUIZRESULTS_NAME_FORMAT_FULL:
                             if ($grouplink) {
                                 $thisname = '<a href="' . $grouplink . $groupid . '">' . $groupgrades[$groupid]['group'] . '</a>';
                             } else {
                                 $thisname = $groupgrades[$groupid]['group'];
                             }
                             break;
                     }
                     $this->content->text .= '<tr><td>' . ++$rank . '.</td><td>' . $thisname . '</td><td>';
                     switch ($gradeformat) {
                         case B_QUIZRESULTS_GRADE_FORMAT_FRA:
                             $this->content->text .= format_float($averagegrade, $quiz->decimalpoints) . '/' . $quiz->grade;
                             break;
                         case B_QUIZRESULTS_GRADE_FORMAT_ABS:
                             $this->content->text .= format_float($averagegrade, $quiz->decimalpoints);
                             break;
                         default:
                         case B_QUIZRESULTS_GRADE_FORMAT_PCT:
                             $this->content->text .= round((double) $averagegrade / (double) $quiz->grade * 100) . '%';
                             break;
                     }
                     $this->content->text .= '</td></tr>';
                 }
                 $this->content->text .= '</tbody></table>';
             }
             $rank = 0;
             if (!empty($worst)) {
                 $worst = array_reverse($worst, true);
                 $this->content->text .= '<table class="grades"><caption>';
                 $this->content->text .= $numworst == 1 ? get_string('worstgroupgrade', 'block_quiz_results') : get_string('worstgroupgrades', 'block_quiz_results', $numworst);
                 $this->content->text .= '</caption><colgroup class="number" /><colgroup class="name" /><colgroup class="grade" /><tbody>';
                 foreach ($worst as $groupid => $averagegrade) {
                     switch ($nameformat) {
                         case B_QUIZRESULTS_NAME_FORMAT_ANON:
                         case B_QUIZRESULTS_NAME_FORMAT_ID:
                             $thisname = get_string('group');
                             break;
                         default:
                         case B_QUIZRESULTS_NAME_FORMAT_FULL:
                             $thisname = '<a href="' . $CFG->wwwroot . '/course/group.php?group=' . $groupid . '&amp;id=' . $courseid . '">' . $groupgrades[$groupid]['group'] . '</a>';
                             break;
                     }
                     $this->content->text .= '<tr><td>' . ++$rank . '.</td><td>' . $thisname . '</td><td>';
                     switch ($gradeformat) {
                         case B_QUIZRESULTS_GRADE_FORMAT_FRA:
                             $this->content->text .= format_float($averagegrade, $quiz->decimalpoints) . '/' . $quiz->grade;
                             break;
                         case B_QUIZRESULTS_GRADE_FORMAT_ABS:
                             $this->content->text .= format_float($averagegrade, $quiz->decimalpoints);
                             break;
                         default:
                         case B_QUIZRESULTS_GRADE_FORMAT_PCT:
                             $this->content->text .= round((double) $averagegrade / (double) $quiz->grade * 100) . '%';
                             break;
                     }
                     $this->content->text .= '</td></tr>';
                 }
                 $this->content->text .= '</tbody></table>';
             }
             break;
         case SEPARATEGROUPS:
             // This is going to be just like no-groups mode, only we 'll filter
             // out the grades from people not in our group.
             if (empty($USER) || empty($USER->id)) {
                 // Not logged in, so show nothing
                 return $this->content;
             }
             $mygroups = groups_get_all_groups($courseid, $USER->id);
             if (empty($mygroups)) {
                 // Not member of a group, show nothing
                 return $this->content;
             }
             $mygroupsusers = get_records_list('groups_members', 'groupid', implode(',', array_keys($mygroups)), '', 'userid, id');
             // There should be at least one user there, ourselves. So no more tests.
             // Just filter out the grades belonging to other users, and proceed as if there were no groups
             $strallowedusers = implode(',', array_keys($mygroupsusers));
             $grades = array_filter($grades, create_function('$el', '$allowed = explode(",", "' . $strallowedusers . '"); return in_array($el->userid, $allowed);'));
             // NO break; HERE, JUST GO AHEAD
         // NO break; HERE, JUST GO AHEAD
         default:
         case NOGROUPS:
             // Single user mode
             $numbest = empty($this->config->showbest) ? 0 : min($this->config->showbest, count($grades));
             $numworst = empty($this->config->showworst) ? 0 : min($this->config->showworst, count($grades) - $numbest);
             // Collect all the usernames we are going to need
             $remaining = $numbest;
             $grade = end($grades);
             while ($remaining--) {
                 $best[$grade->userid] = $grade->id;
                 $grade = prev($grades);
             }
             $remaining = $numworst;
             $grade = reset($grades);
             while ($remaining--) {
                 $worst[$grade->userid] = $grade->id;
                 $grade = next($grades);
             }
             if (empty($best) && empty($worst)) {
                 // Nothing to show, for some reason...
                 return $this->content;
             }
             // Now grab all the users from the database
             $userids = array_merge(array_keys($best), array_keys($worst));
             $users = get_records_list('user', 'id', implode(',', $userids), '', 'id, firstname, lastname, idnumber');
             // Ready for output!
             $gradeformat = intval(empty($this->config->gradeformat) ? B_QUIZRESULTS_GRADE_FORMAT_PCT : $this->config->gradeformat);
             if ($this->instance->pagetype != 'mod-quiz-view') {
                 // Don't show header and link to the quiz if we ARE at the quiz...
                 $this->content->text .= '<h1><a href="' . $CFG->wwwroot . '/mod/quiz/view.php?q=' . $quizid . '">' . $quiz->name . '</a></h1>';
             }
             $rank = 0;
             if (!empty($best)) {
                 $this->content->text .= '<table class="grades"><caption>';
                 $this->content->text .= $numbest == 1 ? get_string('bestgrade', 'block_quiz_results') : get_string('bestgrades', 'block_quiz_results', $numbest);
                 $this->content->text .= '</caption><colgroup class="number" /><colgroup class="name" /><colgroup class="grade" /><tbody>';
                 foreach ($best as $userid => $gradeid) {
                     switch ($nameformat) {
                         case B_QUIZRESULTS_NAME_FORMAT_ID:
                             $thisname = $course->student . ' ' . intval($users[$userid]->idnumber);
                             break;
                         case B_QUIZRESULTS_NAME_FORMAT_ANON:
                             $thisname = $course->student;
                             break;
                         default:
                         case B_QUIZRESULTS_NAME_FORMAT_FULL:
                             $thisname = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $userid . '&amp;course=' . $courseid . '">' . fullname($users[$userid]) . '</a>';
                             break;
                     }
                     $this->content->text .= '<tr><td>' . ++$rank . '.</td><td>' . $thisname . '</td><td>';
                     switch ($gradeformat) {
                         case B_QUIZRESULTS_GRADE_FORMAT_FRA:
                             $this->content->text .= format_float($grades[$gradeid]->grade, $quiz->decimalpoints) . '/' . $quiz->grade;
                             break;
                         case B_QUIZRESULTS_GRADE_FORMAT_ABS:
                             $this->content->text .= format_float($grades[$gradeid]->grade, $quiz->decimalpoints);
                             break;
                         default:
                         case B_QUIZRESULTS_GRADE_FORMAT_PCT:
                             if ($quiz->grade) {
                                 $this->content->text .= round((double) $grades[$gradeid]->grade / (double) $quiz->grade * 100) . '%';
                             } else {
                                 $this->content->text .= '--%';
                             }
                             break;
                     }
                     $this->content->text .= '</td></tr>';
                 }
                 $this->content->text .= '</tbody></table>';
             }
             $rank = 0;
             if (!empty($worst)) {
                 $worst = array_reverse($worst, true);
                 $this->content->text .= '<table class="grades"><caption>';
                 $this->content->text .= $numworst == 1 ? get_string('worstgrade', 'block_quiz_results') : get_string('worstgrades', 'block_quiz_results', $numworst);
                 $this->content->text .= '</caption><colgroup class="number" /><colgroup class="name" /><colgroup class="grade" /><tbody>';
                 foreach ($worst as $userid => $gradeid) {
                     switch ($nameformat) {
                         case B_QUIZRESULTS_NAME_FORMAT_ID:
                             $thisname = $course->student . ' ' . intval($users[$userid]->idnumber);
                             break;
                         case B_QUIZRESULTS_NAME_FORMAT_ANON:
                             $thisname = $course->student;
                             break;
                         default:
                         case B_QUIZRESULTS_NAME_FORMAT_FULL:
                             $thisname = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $userid . '&amp;course=' . $courseid . '">' . fullname($users[$userid]) . '</a>';
                             break;
                     }
                     $this->content->text .= '<tr><td>' . ++$rank . '.</td><td>' . $thisname . '</td><td>';
                     switch ($gradeformat) {
                         case B_QUIZRESULTS_GRADE_FORMAT_FRA:
                             $this->content->text .= format_float($grades[$gradeid]->grade, $quiz->decimalpoints) . '/' . $quiz->grade;
                             break;
                         case B_QUIZRESULTS_GRADE_FORMAT_ABS:
                             $this->content->text .= format_float($grades[$gradeid]->grade, $quiz->decimalpoints);
                             break;
                         default:
                         case B_QUIZRESULTS_GRADE_FORMAT_PCT:
                             $this->content->text .= round((double) $grades[$gradeid]->grade / (double) $quiz->grade * 100) . '%';
                             break;
                     }
                     $this->content->text .= '</td></tr>';
                 }
                 $this->content->text .= '</tbody></table>';
             }
             break;
     }
     return $this->content;
 }
 /**
  * Builds and return the HTML rows of the table (grades headed by student).
  * @return string HTML
  */
 function get_studentshtml()
 {
     global $CFG, $USER;
     $studentshtml = '';
     $strfeedback = $this->get_lang_string("feedback");
     $strgrade = $this->get_lang_string('grade');
     /*
            if ($showquickfeedback ) {
                $gradetabindex += $numusers * 4;
            } else {
                $gradetabindex += $numusers * 2;
            }
     *
     */
     $gradetabindex = 1;
     $numusers = count($this->users);
     $showuserimage = $this->get_pref('showuserimage');
     $showuseridnumber = $this->get_pref('showuseridnumber');
     $showquickfeedback = $this->get_pref('showquickfeedback');
     $accuratetotals = get_user_preferences('grade_report_accuratepointtotals') == null ? 1 : 0;
     // turn off fixed students column no matter what for this report
     $fixedstudents = 0;
     //$this->is_fixed_students();
     $quickgrading = $this->get_pref('quickgrading');
     // Preload scale objects for items with a scaleid
     $scales_list = '';
     $tabindices = array();
     foreach ($this->gtree->items as $item) {
         if (!empty($item->scaleid)) {
             $scales_list .= "{$item->scaleid},";
         }
         if ($item->type == 'item') {
             $tabindices[$item->id]['grade'] = $gradetabindex;
             if ($showquickfeedback) {
                 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
                 $gradetabindex += $numusers * 2;
             } else {
                 $gradetabindex += $numusers;
             }
         }
     }
     $scales_array = array();
     if (!empty($scales_list)) {
         $scales_list = substr($scales_list, 0, -1);
         $scales_array = get_records_list('scale', 'id', $scales_list);
     }
     $row_classes = array(' even ', ' odd ');
     foreach ($this->users as $userid => $user) {
         if ($this->canviewhidden) {
             $altered = array();
             $unknown = array();
         } else {
             $hiding_affected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->items);
             $altered = $hiding_affected['altered'];
             $unknown = $hiding_affected['unknown'];
             unset($hiding_affected);
         }
         $columncount = 0;
         if ($fixedstudents) {
             $studentshtml .= '<tr class="r' . $this->rowcount++ . $row_classes[$this->rowcount % 2] . '">';
         } else {
             // Student name and link
             $user_pic = null;
             if ($showuserimage) {
                 $user_pic = '<div class="userpic">' . print_user_picture($user, $this->courseid, null, 0, true) . '</div>';
             }
             //we're either going to add a th or a colspan to keep things aligned
             // REMOVING $colspan AS ANYTHING
             $userreportcell = '';
             $userreportcellcolspan = '';
             if (has_capability('gradereport/' . $CFG->grade_profilereport . ':view', $this->context)) {
                 $a->user = fullname($user);
                 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
                 $userreportcell = '<td class="tduser"><a href="' . $CFG->wwwroot . '/grade/report/' . $CFG->grade_profilereport . '/index.php?id=' . $this->courseid . '&amp;userid=' . $user->id . '" target="_blank">' . '<img class="userreport" src="' . $CFG->pixpath . '/t/grades.gif" alt="' . $strgradesforuser . '" style="align:center" title="' . $strgradesforuser . '" /></a></td>';
                 //                    $userreportcell = '<a href="'.$CFG->wwwroot.'/grade/report/'.$CFG->grade_profilereport.'/index.php?id='.$this->courseid.'&amp;userid='.$user->id.'" target="_blank">'
                 //                                    .'<img class="userreport" src="'.$CFG->pixpath.'/t/grades.gif" alt="'.$strgradesforuser.'" style="align:center" title="'.$strgradesforuser.'" /></a>';
             } else {
                 $userreportcell = '<td class="userreport"></td>';
             }
             $studentshtml .= '<tr class="r' . $this->rowcount++ . $row_classes[$this->rowcount % 2] . '">' . '<th class="c' . $columncount++ . ' user">' . $user_pic . '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&amp;course=' . $this->course->id . '">' . $user->firstname . '<br /><span class="lastname">' . $user->lastname . "</a></span></th>{$userreportcell}";
             //                              .fullname($user)."</a></th>$userreportcell";
             if ($showuseridnumber) {
                 $studentshtml .= '<th class="c' . $columncount++ . ' useridnumber" onclick="set_row(this.parentNode.rowIndex);">' . $user->idnumber . '</th>';
             }
         }
         // each loop does an item, entire cycle does a user's row
         foreach ($this->gtree->items as $itemid => $unused) {
             $item =& $this->gtree->items[$itemid];
             $grade = $this->grades[$userid][$item->id];
             // Get the decimal points preference for this item
             $decimalpoints = $item->get_decimals();
             if (in_array($itemid, $unknown)) {
                 $gradeval = null;
             } else {
                 if (array_key_exists($itemid, $altered)) {
                     $gradeval = $altered[$itemid];
                 } else {
                     $gradeval = $grade->finalgrade;
                 }
             }
             // MDL-11274
             // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
             if (!$this->canviewhidden and $grade->is_hidden()) {
                 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
                     // the problem here is that we do not have the time when grade value was modified, 'timemodified' is general modification date for grade_grades records
                     $studentshtml .= '<td class="cell c' . $columncount++ . '"><span class="datesubmitted">' . userdate($grade->get_datesubmitted(), get_string('strftimedatetimeshort')) . '</span></td>';
                 } else {
                     $studentshtml .= '<td class="cell c' . $columncount++ . '">-</td>';
                 }
                 continue;
             }
             // emulate grade element
             $eid = $this->gtree->get_grade_eid($grade);
             $element = array('eid' => $eid, 'object' => $grade, 'type' => 'grade');
             $cellclasses = 'grade cell c' . $columncount++;
             if ($item->is_category_item()) {
                 $cellclasses .= ' cat';
             }
             if ($item->is_course_item()) {
                 $cellclasses .= ' course';
             }
             if ($grade->is_overridden()) {
                 $cellclasses .= ' overridden';
             }
             if ($grade->is_excluded()) {
                 $cellclasses .= ' excluded';
             }
             /*  ELLIMINATE ALT TEXT WITH DIV SECTIONS
                             $grade_title = '<div class="fullname">'.fullname($user).'</div>';
                             $grade_title .= '<div class="itemname">'.$item->get_name(true).'</div>';
             
                             if (!empty($grade->feedback) && !$USER->gradeediting[$this->courseid]) {
                                 $grade_title .= '<div class="feedback">'
                                              .wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >') . '</div>';
                             } else {
             
                             }
             */
             $grade_title = '';
             $studentshtml .= '<td class="' . $cellclasses . '" title="' . s($grade_title) . '">';
             if ($grade->is_excluded()) {
                 $studentshtml .= '<span class="excludedfloater">' . get_string('excluded', 'grades') . '</span> ';
             }
             // Do not show any icons if no grade (no record in DB to match)
             if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
                 $studentshtml .= $this->get_icons($element);
             }
             $hidden = '';
             if ($grade->is_hidden()) {
                 $hidden = ' hidden ';
             }
             $gradepass = '******';
             if ($grade->is_passed($item)) {
                 $gradepass = '******';
             } elseif (is_null($grade->is_passed($item))) {
                 $gradepass = '';
             }
             // if in editting mode, we need to print either a text box
             // or a drop down (for scales)
             // grades in item of type grade category or course are not directly editable
             if ($item->needsupdate) {
                 $studentshtml .= '<span class="gradingerror' . $hidden . '">' . get_string('error') . '</span>';
             } else {
                 if ($USER->gradeediting[$this->courseid]) {
                     if ($item->scaleid && !empty($scales_array[$item->scaleid])) {
                         $scale = $scales_array[$item->scaleid];
                         $gradeval = (int) $gradeval;
                         // scales use only integers
                         $scales = explode(",", $scale->scale);
                         // reindex because scale is off 1
                         // MDL-12104 some previous scales might have taken up part of the array
                         // so this needs to be reset
                         $scaleopt = array();
                         $i = 0;
                         foreach ($scales as $scaleoption) {
                             $i++;
                             $scaleopt[$i] = $scaleoption;
                         }
                         if ($quickgrading and $grade->is_editable()) {
                             $oldval = empty($gradeval) ? -1 : $gradeval;
                             if (empty($item->outcomeid)) {
                                 $nogradestr = $this->get_lang_string('nograde');
                             } else {
                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
                             }
                             $studentshtml .= '<input type="hidden" name="oldgrade_' . $userid . '_' . $item->id . '" value="' . $oldval . '"/>';
                             $studentshtml .= choose_from_menu($scaleopt, 'grade_' . $userid . '_' . $item->id, $gradeval, $nogradestr, '', '-1', true, false, $tabindices[$item->id]['grade']);
                         } elseif (!empty($scale)) {
                             $scales = explode(",", $scale->scale);
                             // invalid grade if gradeval < 1
                             if ($gradeval < 1) {
                                 $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">-</span>';
                             } else {
                                 $gradeval = $grade->grade_item->bounded_grade($gradeval);
                                 //just in case somebody changes scale
                                 $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . $scales[$gradeval - 1] . '</span>';
                             }
                         } else {
                             // no such scale, throw error?
                         }
                     } else {
                         if ($item->gradetype != GRADE_TYPE_TEXT) {
                             // Value type
                             // We always want to display the correct (first) displaytype when editing
                             // regardless of grade_report_gradeeditalways
                             $gradedisplaytype = (int) substr((string) $item->get_displaytype(), 0, 1);
                             // if we have an accumulated total points that's not accurately reflected in the db, then we want to display the ACCURATE number
                             // we only need to take the extra calculation into account if points display since percent and letter are accurate by their nature
                             // If the settings don't call for ACCURATE point totals ($this->accuratetotals) then there will be no earned_total value
                             if ($gradedisplaytype == GRADE_DISPLAY_TYPE_REAL && isset($this->grades[$userid][$grade->itemid]->cat_item)) {
                                 $items = $this->gtree->items;
                                 $grade_values = $this->grades[$userid][$grade->itemid]->cat_item;
                                 $grade_maxes = $this->grades[$userid][$grade->itemid]->cat_max;
                                 $this_cat = $this->gtree->items[$grade->itemid]->get_item_category();
                                 limit_item($this_cat, $items, $grade_values, $grade_maxes);
                                 $gradeval = array_sum($grade_values);
                                 $item->grademax = array_sum($grade_maxes);
                             }
                             $value = grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null);
                             if (!$grade->is_hidden() && $gradeval != null && $this->accuratetotals) {
                                 $this->grades[$userid][$this->gtree->parents[$grade->itemid]->id]->cat_item[$grade->itemid] = $gradeval;
                                 $this->grades[$userid][$this->gtree->parents[$grade->itemid]->id]->cat_max[$grade->itemid] = $grade->rawgrademax;
                             }
                             if ($quickgrading and $grade->is_editable()) {
                                 if (!$item->is_course_item() and !$item->is_category_item()) {
                                     $studentshtml .= '<input type="hidden" name="oldgrade_' . $userid . '_' . $item->id . '" value="' . $value . '" />';
                                     $studentshtml .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade'] . '" type="text" title="' . $strgrade . '" class ="gradevalue' . $hidden . $gradepass . '" rel="' . $item->id . '" name="grade_' . $userid . '_' . $item->id . '" value="' . $value . '" />';
                                 } else {
                                     $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . $value . '</span>';
                                 }
                             } else {
                                 $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . format_float($gradeval, $decimalpoints) . '</span>';
                             }
                         }
                     }
                     // If quickfeedback is on, print an input element
                     if ($showquickfeedback and $grade->is_editable()) {
                         if (!$item->is_course_item() and !$item->is_category_item()) {
                             $studentshtml .= '<input type="hidden" name="oldfeedback_' . $userid . '_' . $item->id . '" value="' . s($grade->feedback) . '" />';
                             $studentshtml .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'] . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_' . $userid . '_' . $item->id . '" value="' . s($grade->feedback) . '" />';
                         }
                     }
                 } else {
                     // Not editing
                     if ($this->accuratetotals) {
                         $gradedisplaytype = (int) substr((string) $item->get_displaytype(), 0, 1);
                     } else {
                         $gradedisplaytype = $item->get_displaytype();
                     }
                     // if we have an accumulated total points that's not accurately reflected in the db, then we want to display the ACCURATE number
                     // we only need to take the extra calculation into account if points display since percent and letter are accurate by their nature
                     // If the settings don't call for ACCURATE point totals ($this->accuratetotals) then there will be no earned_total value
                     if ($gradedisplaytype == GRADE_DISPLAY_TYPE_REAL && isset($this->grades[$userid][$grade->itemid]->cat_item)) {
                         $items = $this->gtree->items;
                         $grade_values = $this->grades[$userid][$grade->itemid]->cat_item;
                         $grade_maxes = $this->grades[$userid][$grade->itemid]->cat_max;
                         $this_cat = $this->gtree->items[$grade->itemid]->get_item_category();
                         limit_item($this_cat, $items, $grade_values, $grade_maxes);
                         $gradeval = array_sum($grade_values);
                         $item->grademax = array_sum($grade_maxes);
                     }
                     // is calculating accurate totals store the earned_total for this item to its parent, if there is one
                     if (!$grade->is_hidden() && $gradeval != null && $this->accuratetotals && isset($this->gtree->parents[$grade->itemid]->id)) {
                         $this->grades[$userid][$this->gtree->parents[$grade->itemid]->id]->cat_item[$grade->itemid] = $gradeval;
                         $this->grades[$userid][$this->gtree->parents[$grade->itemid]->id]->cat_max[$grade->itemid] = $grade->rawgrademax;
                     }
                     // If feedback present, surround grade with feedback tooltip: Open span here
                     if ($item->needsupdate) {
                         $studentshtml .= '<span class="gradingerror' . $hidden . $gradepass . '">' . get_string('error') . '</span>';
                     } else {
                         $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null) . '</span>';
                     }
                 }
             }
             if (!empty($this->gradeserror[$item->id][$userid])) {
                 $studentshtml .= $this->gradeserror[$item->id][$userid];
             }
             $studentshtml .= '</td>' . "\n";
         }
         $studentshtml .= '</tr>';
     }
     return $studentshtml;
 }
Example #7
0
             notify("An error occurred while saving your notes.  Sorry.");
         } else {
             notify(get_string("savednotes", "survey"));
         }
     } else {
         if (!survey_add_analysis($survey->id, $user->id, $notes)) {
             notify("An error occurred while saving your notes.  Sorry.");
         } else {
             notify(get_string("savednotes", "survey"));
         }
     }
 }
 echo "<p <p class=\"centerpara\">";
 print_user_picture($user->id, $course->id, $user->picture, true);
 echo "</p>";
 $questions = get_records_list("survey_questions", "id", $survey->questions);
 $questionorder = explode(",", $survey->questions);
 if ($showscales) {
     // Print overall summary
     echo "<p <p class=\"centerpara\">>";
     survey_print_graph("id={$id}&amp;sid={$student}&amp;type=student.png");
     echo "</p>";
     // Print scales
     foreach ($questionorder as $key => $val) {
         $question = $questions[$val];
         if ($question->type < 0) {
             // We have some virtual scales.  Just show them.
             $virtualscales = true;
             break;
         }
     }
 /**
  * When called on a loaded scale object (with a valid id) and given a float grade between
  * the grademin and grademax, this method returns the scale item that falls closest to the
  * float given (which is usually an average of several grades on a scale). If the float falls
  * below 1 but above 0, it will be rounded up to 1.
  * @param float $grade
  * @return string
  */
 function get_nearest_item($grade)
 {
     // Obtain nearest scale item from average
     $scales_array = get_records_list('scale', 'id', $this->id);
     $scale = $scales_array[$this->id];
     $scales = explode(",", $scale->scale);
     // this could be a 0 when summed and rounded, e.g, 1, no grade, no grade, no grade
     if ($grade < 1) {
         $grade = 1;
     }
     return $scales[$grade - 1];
 }
Example #9
0
File: lib.php Project: r007/PMoodle
/** 
 * Get the name of a tag
 * 
 * @param mixed $tagids the id of the tag, or an array of ids
 * @return mixed string name of one tag, or id-indexed array of strings
 */
function tag_get_name($tagids)
{
    $return_a_string = false;
    if (!is_array($tagids)) {
        $return_a_string = true;
        $tagids = array($tagids);
    }
    $tag_names = array();
    foreach (get_records_list('tag', 'id', implode(',', $tagids)) as $tag) {
        $tag_names[$tag->id] = $tag->name;
    }
    if ($return_a_string) {
        return array_pop($tag_names);
    }
    return $tag_names;
}
Example #10
0
 /**
  * Builds and return the HTML rows of the table (grades headed by student).
  * @return string HTML
  */
 function get_studentshtml()
 {
     global $CFG, $USER;
     $studentshtml = '';
     $strfeedback = $this->get_lang_string("feedback");
     $strgrade = $this->get_lang_string('grade');
     $gradetabindex = 1;
     $numusers = count($this->users);
     $showuserimage = $this->get_pref('showuserimage');
     $showuseridnumber = $this->get_pref('showuseridnumber');
     $fixedstudents = $this->is_fixed_students();
     // Preload scale objects for items with a scaleid
     $scales_list = '';
     $tabindices = array();
     foreach ($this->gtree->items as $item) {
         if (!empty($item->scaleid)) {
             $scales_list .= "{$item->scaleid},";
         }
         $tabindices[$item->id]['grade'] = $gradetabindex;
         $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
         $gradetabindex += $numusers * 2;
     }
     $scales_array = array();
     if (!empty($scales_list)) {
         $scales_list = substr($scales_list, 0, -1);
         $scales_array = get_records_list('scale', 'id', $scales_list);
     }
     $row_classes = array(' even ', ' odd ');
     $row_classes = array(' even ', ' odd ');
     foreach ($this->users as $userid => $user) {
         if ($this->canviewhidden) {
             $altered = array();
             $unknown = array();
         } else {
             $hiding_affected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->items);
             $altered = $hiding_affected['altered'];
             $unknown = $hiding_affected['unknown'];
             unset($hiding_affected);
         }
         $columncount = 0;
         if ($fixedstudents) {
             $studentshtml .= '<tr class="r' . $this->rowcount++ . $row_classes[$this->rowcount % 2] . '">';
         } else {
             // Student name and link
             $user_pic = null;
             if ($showuserimage) {
                 $user_pic = '<div class="userpic">' . print_user_picture($user, $this->courseid, null, 0, true) . '</div>';
             }
             $studentshtml .= '<tr class="r' . $this->rowcount++ . $row_classes[$this->rowcount % 2] . '">' . '<th class="c' . $columncount++ . ' user" scope="row" onclick="set_row(this.parentNode.rowIndex);">' . $user_pic . '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&amp;course=' . $this->course->id . '">' . fullname($user) . '</a></th>';
             if ($showuseridnumber) {
                 $studentshtml .= '<th class="c' . $columncount++ . ' useridnumber" onclick="set_row(this.parentNode.rowIndex);">' . $user->idnumber . '</th>';
             }
         }
         foreach ($this->gtree->items as $itemid => $unused) {
             $item =& $this->gtree->items[$itemid];
             $grade = $this->grades[$userid][$item->id];
             // Get the decimal points preference for this item
             $decimalpoints = $item->get_decimals();
             if (in_array($itemid, $unknown)) {
                 $gradeval = null;
             } else {
                 if (array_key_exists($itemid, $altered)) {
                     $gradeval = $altered[$itemid];
                 } else {
                     $gradeval = $grade->finalgrade;
                 }
             }
             // MDL-11274
             // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
             if (!$this->canviewhidden and $grade->is_hidden()) {
                 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
                     // the problem here is that we do not have the time when grade value was modified, 'timemodified' is general modification date for grade_grades records
                     $studentshtml .= '<td class="cell c' . $columncount++ . '"><span class="datesubmitted">' . userdate($grade->get_datesubmitted(), get_string('strftimedatetimeshort')) . '</span></td>';
                 } else {
                     $studentshtml .= '<td class="cell c' . $columncount++ . '">-</td>';
                 }
                 continue;
             }
             // emulate grade element
             $eid = $this->gtree->get_grade_eid($grade);
             $element = array('eid' => $eid, 'object' => $grade, 'type' => 'grade');
             $cellclasses = 'grade cell c' . $columncount++;
             if ($item->is_category_item()) {
                 $cellclasses .= ' cat';
             }
             if ($item->is_course_item()) {
                 $cellclasses .= ' course';
             }
             if ($grade->is_overridden()) {
                 $cellclasses .= ' overridden';
             }
             if ($grade->is_excluded()) {
                 // $cellclasses .= ' excluded';
             }
             $grade_title = '<div class="fullname">' . fullname($user) . '</div>';
             $grade_title .= '<div class="itemname">' . $item->get_name(true) . '</div>';
             if (!empty($grade->feedback) && !$USER->gradeediting[$this->courseid]) {
                 $grade_title .= '<div class="feedback">' . wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >') . '</div>';
             } else {
             }
             $studentshtml .= '<td class="' . $cellclasses . '" title="' . s($grade_title) . '">';
             if ($grade->is_excluded()) {
                 $studentshtml .= '<span class="excludedfloater">' . get_string('excluded', 'grades') . '</span> ';
             }
             // Do not show any icons if no grade (no record in DB to match)
             if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
                 $studentshtml .= $this->get_icons($element);
             }
             $hidden = '';
             if ($grade->is_hidden()) {
                 $hidden = ' hidden ';
             }
             $gradepass = '******';
             if ($grade->is_passed($item)) {
                 $gradepass = '******';
             } elseif (is_null($grade->is_passed($item))) {
                 $gradepass = '';
             }
             // if in editting mode, we need to print either a text box
             // or a drop down (for scales)
             // grades in item of type grade category or course are not directly editable
             if ($item->needsupdate) {
                 $studentshtml .= '<span class="gradingerror' . $hidden . '">' . get_string('error') . '</span>';
             } else {
                 if ($USER->gradeediting[$this->courseid]) {
                     if ($item->scaleid && !empty($scales_array[$item->scaleid])) {
                         $scale = $scales_array[$item->scaleid];
                         $gradeval = (int) $gradeval;
                         // scales use only integers
                         $scales = explode(",", $scale->scale);
                         // reindex because scale is off 1
                         // MDL-12104 some previous scales might have taken up part of the array
                         // so this needs to be reset
                         $scaleopt = array();
                         $i = 0;
                         foreach ($scales as $scaleoption) {
                             $i++;
                             $scaleopt[$i] = $scaleoption;
                         }
                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
                             $oldval = empty($gradeval) ? -1 : $gradeval;
                             if (empty($item->outcomeid)) {
                                 $nogradestr = $this->get_lang_string('nograde');
                             } else {
                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
                             }
                             $studentshtml .= '<input type="hidden" name="oldgrade_' . $userid . '_' . $item->id . '" value="' . $oldval . '"/>';
                             $studentshtml .= choose_from_menu($scaleopt, 'grade_' . $userid . '_' . $item->id, $gradeval, $nogradestr, '', '-1', true, false, $tabindices[$item->id]['grade']);
                         } elseif (!empty($scale)) {
                             $scales = explode(",", $scale->scale);
                             // invalid grade if gradeval < 1
                             if ($gradeval < 1) {
                                 $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">-</span>';
                             } else {
                                 $gradeval = $grade->grade_item->bounded_grade($gradeval);
                                 //just in case somebody changes scale
                                 $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . $scales[$gradeval - 1] . '</span>';
                             }
                         } else {
                             // no such scale, throw error?
                         }
                     } else {
                         if ($item->gradetype != GRADE_TYPE_TEXT) {
                             // Value type
                             if ($this->get_pref('quickgrading') and $grade->is_editable()) {
                                 $value = format_float($gradeval, $decimalpoints);
                                 $studentshtml .= '<input type="hidden" name="oldgrade_' . $userid . '_' . $item->id . '" value="' . $value . '" />';
                                 $studentshtml .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade'] . '" type="text" title="' . $strgrade . '" name="grade_' . $userid . '_' . $item->id . '" value="' . $value . '" />';
                             } else {
                                 $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . format_float($gradeval, $decimalpoints) . '</span>';
                             }
                         }
                     }
                     // If quickfeedback is on, print an input element
                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
                         $studentshtml .= '<input type="hidden" name="oldfeedback_' . $userid . '_' . $item->id . '" value="' . s($grade->feedback) . '" />';
                         $studentshtml .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'] . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_' . $userid . '_' . $item->id . '" value="' . s($grade->feedback) . '" />';
                     }
                 } else {
                     // Not editing
                     $gradedisplaytype = $item->get_displaytype();
                     // If feedback present, surround grade with feedback tooltip: Open span here
                     if ($item->needsupdate) {
                         $studentshtml .= '<span class="gradingerror' . $hidden . $gradepass . '">' . get_string('error') . '</span>';
                     } else {
                         $studentshtml .= '<span class="gradevalue' . $hidden . $gradepass . '">' . grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null) . '</span>';
                     }
                 }
             }
             if (!empty($this->gradeserror[$item->id][$userid])) {
                 $studentshtml .= $this->gradeserror[$item->id][$userid];
             }
             $studentshtml .= '</td>' . "\n";
         }
         $studentshtml .= '</tr>';
     }
     return $studentshtml;
 }
Example #11
0
 public function getForumsForHierarchy($parentDataItemId)
 {
     global $CFG;
     global $SynchContentHierarchy;
     // Have the modules been loaded for the parent section? if not load them
     if (!$SynchContentHierarchy->hasModulesLoaded($parentDataItemId)) {
         $this->getAndAppendModulesToSection($parentDataItemId);
     }
     $parentId = SynchContentHierarchy::getIdFromDataItemId($parentDataItemId);
     $sectionId = $parentId;
     $forumIds = $this->getInstanceIdsFromModulesByModuleType($parentDataItemId, '1010000006');
     if (!is_array($forumIds)) {
         return null;
     }
     $records = get_records_list("forum", "id", implode(',', $forumIds), null, "id, course, type, name, intro");
     if (!$records || !count($records)) {
         return null;
     }
     $contentItems = array();
     $contentItem = null;
     $record = null;
     foreach ($records as $record) {
         $contentItem = new SynchContentItem(array('id' => $record->id, 'name' => $record->name, 'description' => $record->intro));
         $contentItems[$record->id] = $contentItem;
     }
     return $contentItems;
 }
Example #12
0
    if ($question->multi) {
        $addlist = $question->multi;
    } else {
        $addlist = $qid;
    }
    if ($virtualscales && $question->type < 0) {
        // only use them
        $fullorderlist .= $addlist;
    } else {
        if (!$virtualscales && $question->type >= 0) {
            // ignore them
            $fullorderlist .= $addlist;
        }
    }
}
$fullquestions = get_records_list("survey_questions", "id", $fullorderlist);
//  Question type of multi-questions overrides the type of single questions
foreach ($order as $key => $qid) {
    $question = $questions[$qid];
    if ($question->multi) {
        $subs = explode(",", $question->multi);
        while (list($skey, $sqid) = each($subs)) {
            $fullquestions["{$sqid}"]->type = $question->type;
        }
    }
}
$order = explode(",", $fullorderlist);
$questions = $fullquestions;
//  Translate all the question texts
foreach ($questions as $key => $question) {
    $questions[$key]->text = get_string($question->text, "survey");
Example #13
0
function quiz_upgrade($oldversion)
{
    // This function does anything necessary to upgrade
    // older versions to match current functionality
    global $CFG, $db;
    $success = true;
    include_once "{$CFG->dirroot}/mod/quiz/locallib.php";
    if ($success && $oldversion < 2003010100) {
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz ADD review integer DEFAULT '0' NOT NULL AFTER `grademethod` ");
    }
    if ($success && $oldversion < 2003010301) {
        $success = $success && table_column("quiz_truefalse", "true", "trueanswer", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
        $success = $success && table_column("quiz_truefalse", "false", "falseanswer", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
        $success = $success && table_column("quiz_questions", "type", "qtype", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "");
    }
    if ($success && $oldversion < 2003022303) {
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_randommatch (\n                                  id SERIAL PRIMARY KEY,\n                                  question integer NOT NULL default '0',\n                                  choose integer NOT NULL default '4'\n                              );");
    }
    if ($success && $oldversion < 2003030303) {
        $success = $success && table_column("quiz_questions", "", "defaultgrade", "INTEGER", "6", "UNSIGNED", "1", "NOT NULL", "image");
    }
    if ($success && $oldversion < 2003033100) {
        $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch RENAME prefix_quiz_randomsamatch ");
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_match_sub (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 questiontext text NOT NULL default '',\n                                 answertext varchar(255) NOT NULL default ''\n                              );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_match_sub_question_idx ON prefix_quiz_match_sub (question);");
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_multichoice (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 layout integer NOT NULL default '0',\n                                 answers varchar(255) NOT NULL default '',\n                                 single integer NOT NULL default '0'\n                               );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_multichoice_question_idx ON prefix_quiz_multichoice (question);");
    }
    if ($success && $oldversion < 2003040901) {
        $success = $success && table_column("quiz", "", "shufflequestions", "INTEGER", "5", "UNSIGNED", "0", "NOT NULL", "review");
        $success = $success && table_column("quiz", "", "shuffleanswers", "INTEGER", "4", "UNSIGNED", "0", "NOT NULL", "shufflequestions");
    }
    if ($success && $oldversion < 2003042702) {
        $success = $success && modify_database("", "CREATE TABLE prefix_quiz_match (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 subquestions varchar(255) NOT NULL default ''\n                               );");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_match_question_idx ON prefix_quiz_match (question);");
    }
    if ($success && $oldversion < 2003071001) {
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_numerical (\n                               id SERIAL PRIMARY KEY,\n                               question integer NOT NULL default '0',\n                               answer integer NOT NULL default '0',\n                               min varchar(255) NOT NULL default '',\n                               max varchar(255) NOT NULL default ''\n                               ); ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_numerical_answer_idx ON prefix_quiz_numerical (answer);");
    }
    if ($success && $oldversion < 2003072400) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'review', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2003082300) {
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_multianswers (\n                               id SERIAL PRIMARY KEY,\n                               question integer NOT NULL default '0',\n                               answers varchar(255) NOT NULL default '',\n                               positionkey varchar(255) NOT NULL default '',\n                               answertype integer NOT NULL default '0',\n                               norm integer NOT NULL default '1'\n                              ); ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_multianswers_question_idx ON prefix_quiz_multianswers (question);");
        $success = $success && table_column("quiz", "", "attemptonlast", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "attempts");
        $success = $success && table_column("quiz_questions", "", "stamp", "varchar", "255", "", "qtype");
    }
    if ($success && $oldversion < 2003082301) {
        $success = $success && table_column("quiz_questions", "", "version", "integer", "10", "", "1", "not null", "stamp");
        if ($questions = get_records("quiz_questions")) {
            foreach ($questions as $question) {
                $stamp = make_unique_id_code();
                if (!($success = $success && set_field("quiz_questions", "stamp", $stamp, "id", $question->id))) {
                    notify("Error while adding stamp to question id = {$question->id}");
                    break;
                }
            }
        }
    }
    if ($success && $oldversion < 2003082700) {
        table_column("quiz_categories", "", "stamp", "varchar", "255", "", "", "not null");
        if ($categories = get_records("quiz_categories")) {
            foreach ($categories as $category) {
                $stamp = make_unique_id_code();
                if (!($success = $success && set_field("quiz_categories", "stamp", $stamp, "id", $category->id))) {
                    notify("Error while adding stamp to category id = {$category->id}");
                    break;
                }
            }
        }
    }
    if ($success && $oldversion < 2003111100) {
        $duplicates = get_records_sql("SELECT stamp as id,count(*) as cuenta\n                                       FROM {$CFG->prefix}quiz_questions\n                                       GROUP BY stamp\n                                       HAVING count(*)>1");
        if ($duplicates) {
            notify("You have some quiz questions with duplicate stamps IDs.  Cleaning these up.");
            foreach ($duplicates as $duplicate) {
                $questions = get_records("quiz_questions", "stamp", $duplicate->id);
                $add = 1;
                foreach ($questions as $question) {
                    echo "Changing question id {$question->id} stamp to " . $duplicate->id . $add . "<br />";
                    $success = $success && set_field("quiz_questions", "stamp", $duplicate->id . $add, "id", $question->id);
                    $add++;
                }
            }
        } else {
            notify("Checked your quiz questions for stamp duplication errors, but no problems were found.", "green");
        }
    }
    if ($success && $oldversion < 2004021300) {
        $success = $success && table_column("quiz_questions", "", "questiontextformat", "integer", "2", "", "0", "not null", "questiontext");
    }
    if ($success && $oldversion < 2004021900) {
        $success = $success && modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'add', 'quiz', 'name');");
        $success = $success && modify_database("", "INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'update', 'quiz', 'name');");
    }
    if ($success && $oldversion < 2004051700) {
        include_once "{$CFG->dirroot}/mod/quiz/lib.php";
        $success = $success && quiz_refresh_events();
    }
    if ($success && $oldversion < 2004060200) {
        $success = $success && table_column("quiz", "", "timelimit", "integer", "", "", "0", "NOT NULL", "");
    }
    if ($success && $oldversion < 2004070700) {
        $success = $success && table_column("quiz", "", "password", "varchar", "255", "", "", "not null", "");
        $success = $success && table_column("quiz", "", "subnet", "varchar", "255", "", "", "not null", "");
    }
    if ($success && $oldversion < 2004073001) {
        // Six new tables:
        $success = $success && modify_database("", "BEGIN;");
        // One table for handling units for numerical questions
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_numerical_units (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               multiplier decimal(40,20) NOT NULL default '1.00000000000000000000',\n                               unit varchar(50) NOT NULL default ''\n                );");
        // Four tables for handling distribution and storage of
        // individual data for dataset dependent question types
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_attemptonlast_datasets (\n                               id SERIAL8 PRIMARY KEY,\n                               category INT8  NOT NULL default '0',\n                               userid INT8  NOT NULL default '0',\n                               datasetnumber INT8  NOT NULL default '0',\n                               CONSTRAINT prefix_quiz_attemptonlast_datasets_category_userid UNIQUE (category,userid)\n            ) ;");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_dataset_definitions (\n                               id SERIAL8 PRIMARY KEY,\n                               category INT8  NOT NULL default '0',\n                               name varchar(255) NOT NULL default '',\n                               type INT8 NOT NULL default '0',\n                               options varchar(255) NOT NULL default '',\n                               itemcount INT8  NOT NULL default '0'\n            ) ; ");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_dataset_items (\n                               id SERIAL8 PRIMARY KEY,\n                               definition INT8  NOT NULL default '0',\n                               number INT8  NOT NULL default '0',\n                               value varchar(255) NOT NULL default ''\n                             ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_dataset_items_definition_idx ON prefix_quiz_dataset_items (definition);");
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_question_datasets (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               datasetdefinition INT8  NOT NULL default '0'\n            ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_question_datasets_question_datasetdefinition_idx ON prefix_quiz_question_datasets (question,datasetdefinition);");
        // One table for new question type calculated
        //  - the first dataset dependent question type
        $success = $success && modify_database("", " CREATE TABLE prefix_quiz_calculated (\n                               id SERIAL8 PRIMARY KEY,\n                               question INT8  NOT NULL default '0',\n                               answer INT8  NOT NULL default '0',\n                               tolerance varchar(20) NOT NULL default '0.0',\n                               tolerancetype INT8 NOT NULL default '1',\n                               correctanswerlength INT8 NOT NULL default '2'\n                ) ; ");
        $success = $success && modify_database("", "CREATE INDEX prefix_quiz_calculated_question_idx ON  prefix_quiz_calculated (question);");
        $success = $success && modify_database("", "COMMIT;");
    }
    if ($success && $oldversion < 2004111400) {
        $success = $success && table_column("quiz_responses", "answer", "answer", "text", "", "", "", "not null");
    }
    if ($success && $oldversion < 2004111700) {
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_course_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_answers_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_attempts_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_attempts_userid_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_calculated_answer_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_categories_course_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_dataset_definitions_category_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_grades_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_grades_userid_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_numerical_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_numerical_units_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_question_grades_quiz_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_question_grades_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_questions_category_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_randomsamatch_question_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_responses_attempt_idx;", false);
        $success = $success && execute_sql("DROP INDEX {$CFG->prefix}quiz_responses_question_idx;", false);
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_course_idx ON prefix_quiz (course);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_answers_question_idx ON prefix_quiz_answers (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_attempts_quiz_idx ON prefix_quiz_attempts (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_attempts_userid_idx ON prefix_quiz_attempts (userid);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_calculated_answer_idx ON prefix_quiz_calculated (answer);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_categories_course_idx ON prefix_quiz_categories (course);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_dataset_definitions_category_idx ON prefix_quiz_dataset_definitions (category);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_grades_quiz_idx ON prefix_quiz_grades (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_grades_userid_idx ON prefix_quiz_grades (userid);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_numerical_question_idx ON prefix_quiz_numerical (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_numerical_units_question_idx ON prefix_quiz_numerical_units (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_grades_quiz_idx ON prefix_quiz_question_grades (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_grades_question_idx ON prefix_quiz_question_grades (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_questions_category_idx ON prefix_quiz_questions (category);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_randomsamatch_question_idx ON prefix_quiz_randomsamatch (question);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_responses_attempt_idx ON prefix_quiz_responses (attempt);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_responses_question_idx ON prefix_quiz_responses (question);');
    }
    if ($success && $oldversion < 2004112300) {
        //try and clean up an old mistake - try and bring us up to what is in postgres7.sql today.
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_attemptonlast_datasets_category_userid;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_category_userid_unique;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attemptonlast_datasets ADD CONSTRAINT prefix_quiz_category_userid_unique UNIQUE (category,userid);');
    }
    if ($success && $oldversion < 2004120501) {
        $success = $success && table_column("quiz_calculated", "", "correctanswerformat", "integer", "10", "", "0", "not null", "correctanswerlength");
    }
    if ($success && $oldversion < 2004121400) {
        // New field to determine popup window behaviour
        $success = $success && table_column("quiz", "", "popup", "integer", "4", "", "0", "not null", "subnet");
    }
    if ($success && $oldversion < 2005010201) {
        $success = $success && table_column('quiz_categories', '', 'parent');
        $success = $success && table_column('quiz_categories', '', 'sortorder', 'integer', '10', '', '999');
    }
    if ($success && $oldversion < 2005010300) {
        $success = $success && table_column("quiz", "", "questionsperpage", "integer", "10", "", "0", "not null", "review");
    }
    if ($success && $oldversion < 2005012700) {
        $success = $success && table_column('quiz_grades', 'grade', 'grade', 'real', 2, '');
    }
    if ($success && $oldversion < 2005021400) {
        $success = $success && table_column("quiz", "", "decimalpoints", "integer", "4", "", "2", "not null", "grademethod");
    }
    if ($success && $oldversion < 2005022800) {
        $success = $success && table_column('quiz_questions', '', 'hidden', 'integer', '1', 'unsigned', '0', 'not null', 'version');
        $success = $success && table_column('quiz_responses', '', 'originalquestion', 'integer', '10', 'unsigned', '0', 'not null', 'question');
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_question_version (\n                              id SERIAL PRIMARY KEY,\n                              quiz integer NOT NULL default '0',\n                              oldquestion integer NOT NULL default '0',\n                              newquestion integer NOT NULL default '0',\n                              userid integer NOT NULL default '0',\n                              timestamp integer NOT NULL default '0');");
    }
    if ($success && $oldversion < 2005032000) {
        $success = $success && execute_sql(" INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('quiz', 'editquestions', 'quiz', 'name') ");
    }
    if ($success && $oldversion < 2005032300) {
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_version RENAME TO prefix_quiz_question_versions;');
    }
    if ($success && $oldversion < 2005041200) {
        // replace wiki-like with markdown
        include_once "{$CFG->dirroot}/lib/wiki_to_markdown.php";
        $wtm = new WikiToMarkdown();
        $sql = "select course from {$CFG->prefix}quiz_categories, {$CFG->prefix}quiz_questions ";
        $sql .= "where {$CFG->prefix}quiz_category.id = {$CFG->prefix}quiz_questions.category ";
        $sql .= "and {$CFG->prefix}quiz_questions.id = ";
        $wtm->update('quiz_questions', 'questiontext', 'questiontextformat', $sql);
    }
    if ($success && $oldversion < 2005041300) {
        $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET hidden = '1' WHERE qtype ='" . RANDOM . "';");
    }
    if ($success && $oldversion < 2005042002) {
        $success = $success && table_column('quiz_answers', 'answer', 'answer', 'text', '', '', '', 'not null', '');
    }
    if ($success && $oldversion < 2005042400) {
        begin_sql();
        // Changes to quiz table
        // The bits of the optionflags field will hold various option flags
        $success = $success && table_column('quiz', '', 'optionflags', 'integer', '10', 'unsigned', '0', 'not null', 'timeclose');
        // The penalty scheme
        $success = $success && table_column('quiz', '', 'penaltyscheme', 'integer', '4', 'unsigned', '0', 'not null', 'optionflags');
        // The review options are now all stored in the bits of the review field
        $success = $success && table_column('quiz', 'review', 'review', 'integer', 10, 'unsigned', 0, 'not null', '');
        /// Changes to quiz_attempts table
        // The preview flag marks teacher previews
        $success = $success && table_column('quiz_attempts', '', 'preview', 'tinyint', '2', 'unsigned', '0', 'not null', 'timemodified');
        // The layout is the list of questions with inserted page breaks.
        $success = $success && table_column('quiz_attempts', '', 'layout', 'text', '', '', '', 'not null', 'timemodified');
        // For old quiz attempts we will set this to the repaginated question list from $quiz->questions
        /// The following updates of field values require a loop through all quizzes
        // This is because earlier versions of mysql don't allow joins in UPDATE
        if ($quizzes = get_records('quiz')) {
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            foreach ($quizzes as $quiz) {
                // repaginate
                $quiz->questions = $quiz->questionsperpage ? quiz_repaginate($quiz->questions, $quiz->questionsperpage) : $quiz->questions;
                if ($quiz->questionsperpage) {
                    $quiz->questions = quiz_repaginate($quiz->questions, $quiz->questionsperpage);
                    $success = $success && set_field('quiz', 'questions', $quiz->questions, 'id', $quiz->id);
                }
                set_field('quiz_attempts', 'layout', $quiz->questions, 'quiz', $quiz->id);
                // set preview flag
                if ($teachers = get_course_teachers($quiz->course)) {
                    $teacherids = implode(',', array_keys($teachers));
                    $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET preview = 1 WHERE userid IN ({$teacherids})");
                }
                // set review flags in quiz table
                $review = QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_RESPONSES + QUIZ_REVIEW_SCORES;
                if ($quiz->feedback) {
                    $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_FEEDBACK;
                }
                if ($quiz->correctanswers) {
                    $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_ANSWERS;
                }
                if ($quiz->review & 1) {
                    $review += QUIZ_REVIEW_CLOSED;
                }
                if ($quiz->review & 2) {
                    $review += QUIZ_REVIEW_OPEN;
                }
                $success = $success && set_field('quiz', 'review', $review, 'id', $quiz->id);
            }
            $db->debug = $olddebug;
        }
        // We can now drop the fields whose data has been moved to the review field
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz DROP COLUMN feedback");
        $success = $success && execute_sql(" ALTER TABLE {$CFG->prefix}quiz DROP COLUMN correctanswers");
        /// Renaming tables
        // rename the quiz_question_grades table to quiz_question_instances
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades RENAME TO prefix_quiz_question_instances;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_grades_id_seq RENAME TO prefix_quiz_question_instances_id_seq;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_question_instances ALTER COLUMN id SET DEFAULT nextval(\'prefix_quiz_question_instances_id_seq\');');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_question_grades_quiz_idx');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_question_grades_question_idx;');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_instances_quiz_idx ON prefix_quiz_question_instances (quiz);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_question_instances_question_idx ON prefix_quiz_question_instances (question);');
        // rename the quiz_responses table quiz_states
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses RENAME TO prefix_quiz_states;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_responses_id_seq RENAME TO prefix_quiz_states_id_seq;');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_states ALTER COLUMN id SET DEFAULT nextval(\'prefix_quiz_states_id_seq\');');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_responses_attempt_idx;');
        $success = $success && modify_database('', 'DROP INDEX prefix_quiz_responses_question_idx;');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_states_attempt_idx ON prefix_quiz_states (attempt);');
        $success = $success && modify_database('', 'CREATE INDEX prefix_quiz_states_question_idx ON prefix_quiz_states (question);');
        /// add columns to quiz_states table
        // The sequence number of the state.
        $success = $success && table_column('quiz_states', '', 'seq_number', 'integer', '6', 'unsigned', '0', 'not null', 'originalquestion');
        // For existing states we leave this at 0 because in the old quiz code there was only one response allowed
        // The time the state was created.
        $success = $success && table_column('quiz_states', '', 'timestamp', 'integer', '10', 'unsigned', '0', 'not null', 'answer');
        // For existing states we will below set this to the timemodified field of the attempt
        // The type of event that led to the creation of the state
        $success = $success && table_column('quiz_states', '', 'event', 'integer', '4', 'unsigned', '0', 'not null', 'timestamp');
        // The raw grade
        $success = $success && table_column('quiz_states', '', 'raw_grade', 'varchar', '10', '', '', 'not null', 'grade');
        // For existing states (no penalties) this is equal to the grade
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_states SET raw_grade = grade");
        // The penalty that the response attracted
        $success = $success && table_column('quiz_states', '', 'penalty', 'varchar', '10', '', '0.0', 'not null', 'raw_grade');
        // For existing states this can stay at 0 because penalties did not exist previously.
        /// New table for pointers to newest and newest graded states
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_newest_states (\n                               id SERIAL PRIMARY KEY,\n                               attemptid integer NOT NULL default '0',\n                               questionid integer NOT NULL default '0',\n                               newest integer NOT NULL default '0',\n                               newgraded integer NOT NULL default '0',\n                               sumpenalty varchar(10) NOT NULL default '0.0'\n                             );");
        $success = $success && modify_database('CREATE UNIQUE INDEX prefix_quiz_newest_states_attempt_idx ON prefix_quiz_newest_states (attemptid,questionid);');
        /// Now upgrade some fields in states and newest_states tables where necessary
        // to save time on large sites only do this for attempts that have not yet been finished.
        if ($attempts = get_records_select('quiz_attempts', 'timefinish = 0')) {
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            foreach ($attempts as $attempt) {
                quiz_upgrade_states($attempt);
            }
            $db->debug = $olddebug;
        }
        /// Entries for the log_display table
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'preview', 'quiz', 'name');");
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'start attempt', 'quiz', 'name');");
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'close attempt', 'quiz', 'name');");
        /// update the default settings in $CFG
        $review = QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_RESPONSES + QUIZ_REVIEW_SCORES;
        if (!empty($CFG->quiz_feedback)) {
            $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_FEEDBACK;
        }
        if (!empty($CFG->quiz_correctanswers)) {
            $review += QUIZ_REVIEW_IMMEDIATELY & QUIZ_REVIEW_ANSWERS;
        }
        if (isset($CFG->quiz_review) and $CFG->quiz_review & 1) {
            $review += QUIZ_REVIEW_CLOSED;
        }
        if (isset($CFG->quiz_review) and $CFG->quiz_review & 2) {
            $review += QUIZ_REVIEW_OPEN;
        }
        $success = $success && set_config('quiz_review', $review);
        /// Use tolerance instead of min and max in numerical question type
        $success = $success && table_column('quiz_numerical', '', 'tolerance', 'varchar', '255', '', '0.0', 'not null', 'question');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_numerical SET tolerance = (max::text::real-min::text::real)/2");
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN min');
        // Replaced by tolerance
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN max');
        // Replaced by tolerance
        /// Tables for Remote Questions
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp (\n                                 id SERIAL PRIMARY KEY,\n                                 question integer NOT NULL default '0',\n                                 type integer NOT NULL default '0',\n                                 source text NOT NULL,\n                                 format varchar(255) NOT NULL default '',\n                                 flags integer NOT NULL default '0',\n                                 maxscore integer NOT NULL default '1'\n                               );");
        $success = $success && modify_database('', "CREATE INDEX prefix_quiz_rqp_question_idx ON prefix_quiz_rqp (question);");
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp_states (\n                                 id SERIAL PRIMARY KEY,\n                                 stateid integer NOT NULL default '0',\n                                 responses text NOT NULL,\n                                 persistent_data text NOT NULL,\n                                 template_vars text NOT NULL\n                               );");
        $success = $success && modify_database('', "CREATE TABLE prefix_quiz_rqp_types (\n                                id SERIAL PRIMARY KEY,\n                                name varchar(255) NOT NULL default '',\n                                rendering_server varchar(255) NOT NULL default '',\n                                cloning_server varchar(255) NOT NULL default '',\n                                flags integer NOT NULL default '0'\n                              );");
        $success = $success && modify_database('', "CREATE UNIQUE INDEX prefix_quiz_rqp_types_name_uk ON prefix_quiz_rqp_types (name);");
        if ($success) {
            $success = $success && commit_sql();
        } else {
            rollback_sql();
        }
    }
    if ($success && $oldversion < 2005042900 && false) {
        // We don't want this to be executed any more!!!
        begin_sql();
        $success = $success && table_column('quiz_multianswers', '', 'sequence', 'varchar', '255', '', '', 'not null', 'question');
        $success = $success && table_column('quiz_numerical', '', 'answers', 'varchar', '255', '', '', 'not null', 'answer');
        $success = $success && modify_database('', 'UPDATE prefix_quiz_numerical SET answers = answer');
        $success = $success && table_column('quiz_questions', '', 'parent', 'integer', '10', 'unsigned', '0', 'not null', 'category');
        $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET parent = id WHERE qtype ='" . RANDOM . "';");
        // convert multianswer questions to the new model
        if ($multianswers = get_records_sql("SELECT m.id, q.category, q.id AS parent,\n                                        q.name, q.questiontextformat, m.norm AS\n                                        defaultgrade, m.answertype AS qtype,\n                                        q.version, q.hidden, m.answers,\n                                        m.positionkey\n                                        FROM {$CFG->prefix}quiz_questions q,\n                                             {$CFG->prefix}quiz_multianswers m\n                                        WHERE q.qtype = '" . MULTIANSWER . "'\n                                        AND   q.id = m.question\n                                        ORDER BY q.id ASC, m.positionkey ASC")) {
            $multianswers = array_values($multianswers);
            $n = count($multianswers);
            $parent = $multianswers[0]->parent;
            $sequence = array();
            // turn reporting off temporarily to avoid one line output per set_field
            $olddebug = $db->debug;
            $db->debug = false;
            for ($i = 0; $i < $n; $i++) {
                $answers = $multianswers[$i]->answers;
                unset($multianswers[$i]->answers);
                $pos = $multianswers[$i]->positionkey;
                unset($multianswers[$i]->positionkey);
                // create questions for all the multianswer victims
                unset($multianswers[$i]->id);
                $multianswers[$i]->length = 0;
                $multianswers[$i]->questiontext = '';
                $multianswers[$i]->stamp = make_unique_id_code();
                $id = insert_record('quiz_questions', $multianswers[$i]);
                $success = $success && $id;
                $sequence[$pos] = $id;
                // update the answers table to point to these new questions
                $success = $success && modify_database('', "UPDATE prefix_quiz_answers SET question = '{$id}' WHERE id IN ({$answers});");
                // update the questiontype tables to point to these new questions
                if (SHORTANSWER == $multianswers[$i]->qtype) {
                    $success = $success && modify_database('', "UPDATE prefix_quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}';");
                } else {
                    if (NUMERICAL == $multianswers[$i]->qtype) {
                        if (strpos($answers, ',')) {
                            $numerical = get_records_list('quiz_numerical', 'answer', $answers);
                            // Get the biggest tolerance value
                            $tolerance = 0;
                            foreach ($numerical as $num) {
                                $tolerance = $tolerance < $num->tolerance ? $num->tolerance : $tolerance;
                            }
                            $success = $success && delete_records_select('quiz_numerical', "answer IN ({$answers})");
                            $new = new stdClass();
                            $new->question = $id;
                            $new->tolerance = $tolerance;
                            $new->answers = $answers;
                            $success = $success && insert_record('quiz_numerical', $new);
                            unset($numerical, $new, $tolerance);
                        } else {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET question = '{$id}', answers = '{$answers}' WHERE answer IN ({$answers});");
                        }
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}';");
                        }
                    }
                }
                if (!isset($multianswers[$i + 1]) || $parent != $multianswers[$i + 1]->parent) {
                    $success = $success && delete_records('quiz_multianswers', 'question', $parent);
                    $multi = new stdClass();
                    $multi->question = $parent;
                    $multi->sequence = implode(',', $sequence);
                    $success = $success && insert_record('quiz_multianswers', $multi);
                    if (isset($multianswers[$i + 1])) {
                        $parent = $multianswers[$i + 1]->parent;
                        $sequence = array();
                    }
                }
            }
            $db->debug = $olddebug;
        }
        // Remove redundant fields from quiz_multianswers
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN answers');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN positionkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN answertype');
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP COLUMN norm');
        // Change numerical from answer to answers
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP COLUMN answer');
        if ($success) {
            $success = $success && commit_sql();
        } else {
            rollback_sql();
        }
    }
    if ($success && $oldversion < 2005050300) {
        // length of question determines question numbering. Currently all questions require one
        // question number except for DESCRIPTION questions.
        $success = $success && table_column('quiz_questions', '', 'length', 'integer', '10', 'unsigned', '1', 'not null', 'qtype');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET length = 0 WHERE qtype = '7'");
    }
    if ($success && $oldversion < 2005050408) {
        $success = $success && table_column('quiz_questions', '', 'penalty', 'float', '', '', '0.1', 'not null', 'defaultgrade');
    }
    if ($success && $oldversion < 2005051401) {
        // Some earlier changes are undone here, so we need another condition
        if ($oldversion >= 2005042900) {
            // Restore the answer field
            $success = $success && table_column('quiz_numerical', '', 'answer', 'integer', '10', 'unsigned', '0', 'not null', 'answers');
            $singleanswer = array();
            if ($numericals = get_records('quiz_numerical')) {
                $numericals = array_values($numericals);
                $n = count($numericals);
                for ($i = 0; $i < $n; $i++) {
                    $numerical =& $numericals[$i];
                    if (strpos($numerical->answers, ',')) {
                        // comma separated list?
                        // Back this up to delete the record after the new ones are created
                        $id = $numerical->id;
                        unset($numerical->id);
                        // We need to create a record for each answer id
                        $answers = explode(',', $numerical->answers);
                        foreach ($answers as $answer) {
                            $numerical->answer = $answer;
                            $success = $success && insert_record('quiz_numerical', $numerical);
                        }
                        // ... and get rid of the old record
                        $success = $success && delete_records('quiz_numerical', 'id', $id);
                    } else {
                        $singleanswer[] = $numerical->id;
                    }
                }
            }
            // Do all of these at once
            if (!empty($singleanswer)) {
                $singleanswer = implode(',', $singleanswer);
                $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET answer = answers WHERE id IN ({$singleanswer});");
            }
            // All answer fields are set, so we can delete the answers field
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_numerical DROP answers');
            // If the earlier changes weren't made we can safely do only the
            // bits here.
        } else {
            // Comma separated questionids will be stored as sequence
            $success = $success && table_column('quiz_multianswers', '', 'sequence', 'varchar', '255', '', '', 'not null', 'question');
            // Change the type of positionkey to int, so that the sorting works!
            $success = $success && table_column('quiz_multianswers', 'positionkey', 'positionkey', 'integer', '10', 'unsigned', '0', 'not null', '');
            $success = $success && table_column('quiz_questions', '', 'parent', 'integer', '10', 'unsigned', '0', 'not null', 'category');
            $success = $success && modify_database('', "UPDATE prefix_quiz_questions SET parent = id WHERE qtype ='" . RANDOM . "';");
            // Each multianswer record is converted to a question object and then
            // inserted as a new question into the quiz_questions table.
            // After that the question fields in the quiz_answers table and the
            // qtype specific tables are updated to point to the new question id.
            // Note: The quiz_numerical table is different as it stores one record
            //       per defined answer (to allow different tolerance values for
            //       different possible answers. (Currently multiple answers are
            //       not supported by the numerical editing interface, but all
            //       all processing code does support that possibility.
            if ($multianswers = get_records_sql("SELECT m.id, q.category, " . "q.id AS parent, " . "q.name, q.questiontextformat, " . "m.norm AS defaultgrade, " . "m.answertype AS qtype, " . "q.version, q.hidden, m.answers, " . "m.positionkey " . "FROM {$CFG->prefix}quiz_questions q, " . "     {$CFG->prefix}quiz_multianswers m " . "WHERE q.qtype = '" . MULTIANSWER . "' " . "AND   q.id = m.question " . "ORDER BY q.id ASC, m.positionkey ASC")) {
                // ordered by positionkey
                $multianswers = array_values($multianswers);
                $n = count($multianswers);
                $parent = $multianswers[0]->parent;
                $sequence = array();
                $positions = array();
                // Turn reporting off temporarily to avoid one line output per set_field
                global $db;
                $olddebug = $db->debug;
                // $db->debug = false;
                for ($i = 0; $i < $n; $i++) {
                    // Backup these two values before unsetting the object fields
                    $answers = $multianswers[$i]->answers;
                    unset($multianswers[$i]->answers);
                    $pos = $multianswers[$i]->positionkey;
                    unset($multianswers[$i]->positionkey);
                    // Needed for substituting multianswer ids with position keys in the $state->answer field
                    $positions[$multianswers[$i]->id] = $pos;
                    // Create questions for all the multianswer victims
                    unset($multianswers[$i]->id);
                    $multianswers[$i]->length = 0;
                    $multianswers[$i]->questiontext = '';
                    $multianswers[$i]->stamp = make_unique_id_code();
                    // $multianswers[$i]->parent is set in the query
                    // $multianswers[$i]->defaultgrade is set in the query
                    // $multianswers[$i]->qtype is set in the query
                    $id = insert_record('quiz_questions', $multianswers[$i]);
                    $success = $success && $id;
                    $sequence[$pos] = $id;
                    // Update the quiz_answers table to point to these new questions
                    $success = $success && modify_database('', "UPDATE prefix_quiz_answers SET question = '{$id}' WHERE id IN ({$answers});");
                    // Update the questiontype tables to point to these new questions
                    if (SHORTANSWER == $multianswers[$i]->qtype) {
                        $success = $success && modify_database('', "UPDATE prefix_quiz_shortanswer SET question = '{$id}' WHERE answers = '{$answers}';");
                    } else {
                        if (MULTICHOICE == $multianswers[$i]->qtype) {
                            $success = $success && modify_database('', "UPDATE prefix_quiz_multichoice SET question = '{$id}' WHERE answers = '{$answers}';");
                        } else {
                            if (NUMERICAL == $multianswers[$i]->qtype) {
                                $success = $success && modify_database('', "UPDATE prefix_quiz_numerical SET question = '{$id}' WHERE answer IN ({$answers});");
                            }
                        }
                    }
                    // Whenever we're through with the subquestions of one multianswer
                    // question we delete the old records in the multianswers table,
                    // store a new record with the sequence in the multianswers table
                    // and point $parent to the next multianswer question.
                    if (!isset($multianswers[$i + 1]) || $parent != $multianswers[$i + 1]->parent) {
                        // Substituting multianswer ids with position keys in the $state->answer field
                        if ($states = get_records('quiz_states', 'question', $parent)) {
                            foreach ($states as $state) {
                                $reg = array();
                                preg_match_all('/(?:^|,)([0-9]+)-([^,]*)/', $state->answer, $reg);
                                $state->answer = '';
                                $m = count($reg[1]);
                                for ($j = 0; $j < $m; $j++) {
                                    if (isset($positions[$reg[1][$j]])) {
                                        $state->answer .= $positions[$reg[1][$j]] . '-' . $reg[2][$j] . ',';
                                    } else {
                                        notify("Undefined multianswer id ({$reg[1][$j]}) used in state #{$state->id}!");
                                        $state->answer .= $j + 1 . '-' . $reg[2][$j] . ',';
                                    }
                                }
                                $state->answer = rtrim($state->answer, ',');
                                // strip trailing comma
                                $success = $success && update_record('quiz_states', $state);
                            }
                        }
                        $success = $success && delete_records('quiz_multianswers', 'question', $parent);
                        $multi = new stdClass();
                        $multi->question = $parent;
                        $multi->sequence = implode(',', $sequence);
                        $success = $success && insert_record('quiz_multianswers', $multi);
                        if (isset($multianswers[$i + 1])) {
                            $parent = $multianswers[$i + 1]->parent;
                            $sequence = array();
                            $positions = array();
                        }
                    }
                }
                $db->debug = $olddebug;
            }
            // Remove redundant fields from quiz_multianswers
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP answers');
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP positionkey');
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP answertype');
            $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_multianswers DROP norm');
        }
    }
    if ($success && $oldversion < 2005051402) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT category;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}attemptonlast_datasets_category_userid;", false);
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_attemptonlast_datasets DROP CONSTRAINT {$CFG->prefix}quiz_category_userid_unique;", false);
        $success = $success && modify_database('', 'ALTER TABLE prefix_quiz_attemptonlast_datasets ADD CONSTRAINT prefix_quiz_category_userid_unique UNIQUE (category,userid);');
    }
    if ($success && $oldversion < 2005060300) {
        // We need to remove some duplicate entries that may be present in some databases
        // due to a faulty restore script
        // Remove duplicate entries from quiz_numerical
        if ($dups = get_records_sql("\n                SELECT question, answer, count(*) as num\n                FROM {$CFG->prefix}quiz_numerical\n                GROUP BY question, answer\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_numerical\n                    WHERE question = '{$dup->question}'\n                    AND answer = '{$dup->answer}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_numerical', 'id', $id->id);
                    }
                }
            }
        }
        // Remove duplicate entries from quiz_shortanswer
        if ($dups = get_records_sql("\n                SELECT question, answers, count(*) as num\n                FROM {$CFG->prefix}quiz_shortanswer\n                GROUP BY question, answers\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_shortanswer\n                    WHERE question = '{$dup->question}'\n                    AND answers = '{$dup->answers}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_shortanswer', 'id', $id->id);
                    }
                }
            }
        }
        // Remove duplicate entries from quiz_multichoice
        if ($dups = get_records_sql("\n                SELECT question, answers, count(*) as num\n                FROM {$CFG->prefix}quiz_multichoice\n                GROUP BY question, answers\n                HAVING count(*) > 1")) {
            foreach ($dups as $dup) {
                $ids = get_records_sql("\n                    SELECT id, id\n                    FROM {$CFG->prefix}quiz_multichoice\n                    WHERE question = '{$dup->question}'\n                    AND answers = '{$dup->answers}'");
                $skip = true;
                foreach ($ids as $id) {
                    if ($skip) {
                        $skip = false;
                    } else {
                        $success = $success && delete_records('quiz_multichoice', 'id', $id->id);
                    }
                }
            }
        }
        //Search all the orphan categories (those whose course doesn't exist)
        //and process them, deleting or moving them to site course - Bug 2459
        //Set debug to false
        $olddebug = $db->debug;
        $db->debug = false;
        //Iterate over all the quiz_categories records to get their course id
        if ($courses = get_records_sql("SELECT DISTINCT course as id, course\n                                         FROM {$CFG->prefix}quiz_categories")) {
            //Iterate over courses
            foreach ($courses as $course) {
                //If the course doesn't exist, orphan category found!
                //Process it with question_delete_course(). It will do all the hard work.
                if (!record_exists('course', 'id', $course->id)) {
                    require_once "{$CFG->libdir}/questionlib.php";
                    $success = $success && question_delete_course($course);
                }
            }
        }
        //Reset rebug to its original state
        $db->debug = $olddebug;
    }
    if ($success && $oldversion < 2005060301) {
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_type RENAME TO ' . $CFG->prefix . 'quiz_rqp_types');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_type_id_seq RENAME TO ' . $CFG->prefix . 'rqp_types_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_types ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'quiz_rqp_types_id_seq\')');
        $success = $success && execute_sql('DROP INDEX ' . $CFG->prefix . 'quiz_rqp_type_name_uk');
        $success = $success && execute_sql('CREATE UNIQUE INDEX ' . $CFG->prefix . 'quiz_rqp_types_name_uk ON ' . $CFG->prefix . 'quiz_rqp_types (name);');
    }
    if ($success && $oldversion < 2005060302) {
        // Mass cleanup of bad postgres upgrade scripts
        $success = $success && execute_sql('CREATE UNIQUE INDEX ' . $CFG->prefix . 'quiz_newest_states_attempt_idx ON ' . $CFG->prefix . 'quiz_newest_states (attemptid, questionid)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_attemptonlast_datasets DROP CONSTRAINT ' . $CFG->prefix . 'quiz_category_userid_unique', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_attemptonlast_datasets ADD CONSTRAINT ' . $CFG->prefix . 'quiz_attemptonlast_datasets_category_userid UNIQUE (category, userid)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_instances DROP CONSTRAINT ' . $CFG->prefix . 'quiz_question_grades_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_instances ADD CONSTRAINT ' . $CFG->prefix . 'quiz_question_instances_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_versions DROP CONSTRAINT ' . $CFG->prefix . 'quiz_question_version_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_question_versions ADD CONSTRAINT ' . $CFG->prefix . 'quiz_question_versions_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_states DROP CONSTRAINT ' . $CFG->prefix . 'quiz_responses_pkey', false);
        $success = $success && execute_sql('ALTER TABLE ONLY ' . $CFG->prefix . 'quiz_states ADD CONSTRAINT ' . $CFG->prefix . 'quiz_states_pkey PRIMARY KEY (id)', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER decimalpoints SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER optionflags SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER penaltyscheme SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER popup SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER questionsperpage SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz ALTER review SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_answers ALTER answer SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_attempts ALTER layout SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_attempts ALTER preview SET NOT NULL', false);
        $success = $success && table_column('quiz_calculated', 'correctanswerformat', 'correctanswerformat', 'integer', '16', 'unsigned', '2');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories ALTER parent SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories ALTER sortorder SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_grades ALTER grade SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multianswers ALTER sequence SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical ALTER tolerance SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER hidden SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER length SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions ALTER parent SET NOT NULL', false);
        $success = $success && table_column('quiz_questions', 'penalty', 'penalty', 'real', '', 'UNSIGNED', '0.1');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER answer SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER event SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER originalquestion SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER penalty SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER raw_grade SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER seq_number SET NOT NULL', false);
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states ALTER timestamp SET NOT NULL', false);
    }
    if ($success && $oldversion < 2005100500) {
        // clean up an old mistake. This mistake may not have been made, so don't worry about failures.
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_version_id_seq RENAME TO ' . $CFG->prefix . 'quiz_question_versions_id_seq', false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_versions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'quiz_question_versions_id_seq\')', false);
    }
    if ($success && $oldversion < 2006020801) {
        $success = $success && table_column("quiz", "", "delay1", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "popup");
        $success = $success && table_column("quiz", "", "delay2", "INTEGER", "10", "UNSIGNED", "0", "NOT NULL", "delay1");
    }
    if ($success && $oldversion < 2006021101) {
        // set defaultgrade field properly (probably not necessary, but better make sure)
        $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '1' WHERE defaultgrade = '0'", false);
        $success && execute_sql("UPDATE {$CFG->prefix}quiz_questions SET defaultgrade = '0' WHERE qtype = '7'", false);
    }
    if ($success && $oldversion < 2006021103) {
        // add new field to store the question-level shuffleanswers option
        $success = $success && table_column('quiz_match', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'subquestions');
        $success = $success && table_column('quiz_multichoice', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'single');
        $success = $success && table_column('quiz_randomsamatch', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'choose');
    }
    if ($success && $oldversion < 2006021104) {
        // add originalversion field for the new versioning mechanism
        $success = $success && table_column('quiz_question_versions', '', 'originalquestion', 'int', '10', 'unsigned', '0', 'not null', 'newquestion');
    }
    if ($success && $oldversion < 2006021302) {
        $success = $success && table_column('quiz_match_sub', '', 'code', 'int', '10', 'unsigned', '0', 'not null', 'id');
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_match_sub SET code = id", false);
    }
    if ($success && $oldversion < 2006021304) {
        // convert sequence field to text to accomodate very long sequences, see bug 4257
        $success = $success && table_column('quiz_multianswers', 'sequence', 'sequence', 'text', '', '', '', 'not null', 'question');
    }
    if ($success && $oldversion < 2006021400) {
        // modify_database('','CREATE UNIQUE INDEX prefix_quiz_attempts_uniqueid_uk ON prefix_quiz_attempts (uniqueid);');
        // this index will not be created since uniqueid was not added, proper upgrade will be on 2006042801
    }
    if ($success && $oldversion < 2006021501) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME TO {$CFG->prefix}question_sessions", false);
    }
    if ($success && $oldversion < 2006021900) {
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_essay (\n                id SERIAL PRIMARY KEY,\n                question integer NOT NULL default '0',\n                answer varchar(255) NOT NULL default ''\n            ) ");
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_essay_states (\n                id SERIAL PRIMARY KEY,\n                stateid integer NOT NULL default '0',\n                graded integer NOT NULL default '0',\n                fraction varchar(10) NOT NULL default '0.0',\n                response text NOT NULL default ''\n            );");
        // convert grade fields to real
        $success = $success && table_column('quiz_attempts', 'sumgrades', 'sumgrades', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_answers', 'fraction', 'fraction', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_essay_states', 'fraction', 'fraction', 'real', '', '', '0', 'not null');
        $success = $success && set_field('quiz_states', 'grade', 0, 'grade', '');
        // Some values may be wrong, which caused errors in the following table_column calls.
        $success = $success && set_field('quiz_states', 'raw_grade', 0, 'raw_grade', '');
        $success = $success && set_field('quiz_states', 'penalty', 0, 'penalty', '');
        $success = $success && table_column('quiz_states', 'grade', 'grade', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_states', 'raw_grade', 'raw_grade', 'real', '', '', '0', 'not null');
        $success = $success && table_column('quiz_states', 'penalty', 'penalty', 'real', '', '', '0', 'not null');
        $success = $success && table_column('question_sessions', 'sumpenalty', 'sumpenalty', 'real', '', '', '0', 'not null');
    }
    if ($success && $oldversion < 2006030100) {
        // Fix up another table rename :(
        // THIS caused the mistake: execute_sql("ALTER TABLE {$CFG->prefix}quiz_newest_states RENAME TO {$CFG->prefix}question_sessions", false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_newest_states_id_seq RENAME TO ' . $CFG->prefix . 'question_sessions_id_seq', false);
        $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_sessions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_sessions_id_seq\')', false);
    }
    if ($success && $oldversion < 2006030101) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_questions RENAME TO {$CFG->prefix}question");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_questions_id_seq RENAME TO ' . $CFG->prefix . 'question_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_states RENAME TO {$CFG->prefix}question_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_states_id_seq RENAME TO ' . $CFG->prefix . 'question_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_states_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_answers RENAME TO {$CFG->prefix}question_answers");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_answers_id_seq RENAME TO ' . $CFG->prefix . 'question_answers_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_answers ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_answers_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_categories RENAME TO {$CFG->prefix}question_categories");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_categories_id_seq RENAME TO ' . $CFG->prefix . 'question_categories_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_categories ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_categories_id_seq\')');
    }
    if ($success && $oldversion < 2006031202) {
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_truefalse RENAME TO {$CFG->prefix}question_truefalse");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_truefalse_id_seq RENAME TO ' . $CFG->prefix . 'question_truefalse_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_truefalse ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_truefalse_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_shortanswer RENAME TO {$CFG->prefix}question_shortanswer");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_shortanswer_id_seq RENAME TO ' . $CFG->prefix . 'question_shortanswer_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_shortanswer ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_shortanswer_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multianswers RENAME TO {$CFG->prefix}question_multianswer");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multianswers_id_seq RENAME TO ' . $CFG->prefix . 'question_multianswer_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_multianswer ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_multianswer_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_multichoice RENAME TO {$CFG->prefix}question_multichoice");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_multichoice_id_seq RENAME TO ' . $CFG->prefix . 'question_multichoice_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_multichoice ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_multichoice_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical RENAME TO {$CFG->prefix}question_numerical");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical_id_seq RENAME TO ' . $CFG->prefix . 'question_numerical_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_numerical ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_numerical_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_numerical_units RENAME TO {$CFG->prefix}question_numerical_units");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_numerical_units_id_seq RENAME TO ' . $CFG->prefix . 'question_numerical_units_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_numerical_units ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_numerical_units_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_randomsamatch RENAME TO {$CFG->prefix}question_randomsamatch");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_randomsamatch_id_seq RENAME TO ' . $CFG->prefix . 'question_randomsamatch_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_randomsamatch ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_randomsamatch_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match RENAME TO {$CFG->prefix}question_match");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_match_id_seq RENAME TO ' . $CFG->prefix . 'question_match_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_match ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_match_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_match_sub RENAME TO {$CFG->prefix}question_match_sub");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_match_sub_id_seq RENAME TO ' . $CFG->prefix . 'question_match_sub_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_match_sub ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_match_sub_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_calculated RENAME TO {$CFG->prefix}question_calculated");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_calculated_id_seq RENAME TO ' . $CFG->prefix . 'question_calculated_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_calculated ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_calculated_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_definitions RENAME TO {$CFG->prefix}question_dataset_definitions");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_dataset_definitions_id_seq RENAME TO ' . $CFG->prefix . 'question_dataset_definitions_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_dataset_definitions ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_dataset_definitions_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_dataset_items RENAME TO {$CFG->prefix}question_dataset_items");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_dataset_items_id_seq RENAME TO ' . $CFG->prefix . 'question_dataset_items_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_dataset_items ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_dataset_items_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_question_datasets RENAME TO {$CFG->prefix}question_datasets");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_question_datasets_id_seq RENAME TO ' . $CFG->prefix . 'question_datasets_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_datasets ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_datasets_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp RENAME TO {$CFG->prefix}question_rqp");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_states RENAME TO {$CFG->prefix}question_rqp_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_states_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_states_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_rqp_types RENAME TO {$CFG->prefix}question_rqp_types");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_rqp_types_id_seq RENAME TO ' . $CFG->prefix . 'question_rqp_types_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_rqp_types ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_rqp_types_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay RENAME TO {$CFG->prefix}question_essay");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_essay_id_seq RENAME TO ' . $CFG->prefix . 'question_essay_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_essay ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_essay_id_seq\')');
        $success = $success && execute_sql("ALTER TABLE {$CFG->prefix}quiz_essay_states RENAME TO {$CFG->prefix}question_essay_states");
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'quiz_essay_states_id_seq RENAME TO ' . $CFG->prefix . 'question_essay_states_id_seq');
        $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_essay_states ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_essay_states_id_seq\')');
    }
    if ($success && $oldversion < 2006032100) {
        // change from the old questiontype numbers to using the questiontype names
        $success = $success && table_column('question', 'qtype', 'qtype', 'varchar', 20, '', '', 'not null');
        $success = $success && set_field('question', 'qtype', 'shortanswer', 'qtype', 1);
        $success = $success && set_field('question', 'qtype', 'truefalse', 'qtype', 2);
        $success = $success && set_field('question', 'qtype', 'multichoice', 'qtype', 3);
        $success = $success && set_field('question', 'qtype', 'random', 'qtype', 4);
        $success = $success && set_field('question', 'qtype', 'match', 'qtype', 5);
        $success = $success && set_field('question', 'qtype', 'randomsamatch', 'qtype', 6);
        $success = $success && set_field('question', 'qtype', 'description', 'qtype', 7);
        $success = $success && set_field('question', 'qtype', 'numerical', 'qtype', 8);
        $success = $success && set_field('question', 'qtype', 'multianswer', 'qtype', 9);
        $success = $success && set_field('question', 'qtype', 'calculated', 'qtype', 10);
        $success = $success && set_field('question', 'qtype', 'rqp', 'qtype', 11);
        $success = $success && set_field('question', 'qtype', 'essay', 'qtype', 12);
    }
    if ($success && $oldversion < 2006032200) {
        // set version for all questiontypes that already have their tables installed
        $success = $success && set_config('qtype_calculated_version', 2006032100);
        $success = $success && set_config('qtype_essay_version', 2006032100);
        $success = $success && set_config('qtype_match_version', 2006032100);
        $success = $success && set_config('qtype_multianswer_version', 2006032100);
        $success = $success && set_config('qtype_multichoice_version', 2006032100);
        $success = $success && set_config('qtype_numerical_version', 2006032100);
        $success = $success && set_config('qtype_randomsamatch_version', 2006032100);
        $success = $success && set_config('qtype_rqp_version', 2006032100);
        $success = $success && set_config('qtype_shortanswer_version', 2006032100);
        $success = $success && set_config('qtype_truefalse_version', 2006032100);
    }
    if ($success && $oldversion < 2006040600) {
        $success = $success && table_column('question_sessions', '', 'comment', 'text', '', '', '', 'not null', 'sumpenalty');
    }
    if ($success && $oldversion < 2006040900) {
        $success = $success && modify_database('', "UPDATE prefix_question SET parent = id WHERE qtype ='random';");
    }
    if ($success && $oldversion < 2006041000) {
        $success = $success && modify_database('', " INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('quiz', 'continue attempt', 'quiz', 'name');");
    }
    if ($success && $oldversion < 2006041001) {
        $success = $success && table_column('question', 'version', 'version', 'varchar', 255);
    }
    if ($success && $oldversion < 2006042800) {
        // Check we have some un-renamed tables (verified in some servers)
        if ($tables = $db->MetaTables('TABLES')) {
            if (in_array($CFG->prefix . 'quiz_randommatch', $tables) && !in_array($CFG->prefix . 'question_randomsamatch', $tables)) {
                $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch RENAME prefix_question_randomsamatch ");
                $success = $success && modify_database("", "ALTER TABLE prefix_quiz_randommatch_id_seq RENAME prefix_question_randomsamatch_id_seq ");
                $success = $success && execute_sql('ALTER TABLE ' . $CFG->prefix . 'question_randomsamatch ALTER COLUMN id SET DEFAULT nextval(\'' . $CFG->prefix . 'question_randomsamatch_id_seq\')');
            }
            // Check for one possible missing field in one table
            if ($columns = $db->MetaColumnNames($CFG->prefix . 'question_randomsamatch')) {
                if (!in_array('shuffleanswers', $columns)) {
                    $success = $success && table_column('question_randomsamatch', '', 'shuffleanswers', 'tinyint', '4', 'unsigned', '1', 'not null', 'choose');
                }
            }
        }
    }
    if ($success && $oldversion < 2006051300) {
        // this block also exec'ed by 2006042801 on MOODLE_16_STABLE
        // The newgraded field must always point to a valid state
        $success = $success && modify_database("", "UPDATE prefix_question_sessions SET newgraded = newest where newgraded = '0'");
        // Only perform this if hasn't been performed before (in MOODLE_16_STABLE branch - bug 5717)
        $tables = $db->MetaTables('TABLES');
        if (!in_array($CFG->prefix . 'question_attempts', $tables)) {
            // The following table is discussed in bug 5468
            $success = $success && modify_database("", "CREATE TABLE prefix_question_attempts (\n                                     id SERIAL PRIMARY KEY,\n                                     modulename varchar(20) NOT NULL default 'quiz'\n                                  );");
        }
    }
    if ($success && $oldversion < 2006051700) {
        // this block also exec'd by 2006042802 on MOODLE_16_STABLE
        notify("The next set of upgrade operations may report an \n                error if you are upgrading from v1.6. \n                This error mesage is normal, and can be ignored.");
        // this block is taken from mysql.php 2005070202
        // add new unique id to prepare the way for lesson module to have its own attempts table
        table_column('quiz_attempts', '', 'uniqueid', 'integer', '10', 'unsigned', '0', 'not null', 'id');
        // create one entry for all the existing quiz attempts
        // initially we can use the id as the unique id because no other modules use attempts yet.
        $success = $success && execute_sql("UPDATE {$CFG->prefix}quiz_attempts SET uniqueid = id");
        // we set $CFG->attemptuniqueid to the next available id
        $record = get_record_sql("SELECT nextval('{$CFG->prefix}quiz_attempts_id_seq')");
        $success = $success && set_config('attemptuniqueid', empty($record->nextid) ? 1 : $record->nextid);
        // the above will be a race condition, see bug 5468
        modify_database('', 'CREATE UNIQUE INDEX prefix_quiz_attempts_uniqueid_uk ON prefix_quiz_attempts (uniqueid);');
        // create one entry for all the existing quiz attempts
        $success = $success && modify_database("", "INSERT INTO prefix_question_attempts (id)\n                                   SELECT uniqueid\n                                   FROM prefix_quiz_attempts;");
    }
    if ($success && $oldversion < 2006042802) {
        // Copy the teacher comments from the question_essay_states table to the new
        // question_sessions table.
        // Get the attempt unique ID, teacher comment, graded flag, state ID, and question ID
        // based on the quesiont_essay_states
        if ($results = get_records_sql("SELECT a.uniqueid, es.response AS essaycomment, es.graded AS isgraded, \n                                               qs.id AS stateid, qs.question AS questionid \n                                        FROM {$CFG->prefix}question_states as qs,\n                                             {$CFG->prefix}question_essay_states es, \n                                             {$CFG->prefix}quiz_attempts a \n                                        WHERE es.stateid = qs.id AND a.uniqueid = qs.attempt")) {
            foreach ($results as $result) {
                // Create a state object to be used for updating
                $state = new stdClass();
                $state->id = $result->stateid;
                if ($result->isgraded) {
                    // Graded - save comment to the sessions and change state event to QUESTION_EVENTMANUALGRADE
                    if (!($success = $success && set_field('question_sessions', 'comment', $result->essaycomment, 'attemptid', $result->uniqueid, 'questionid', $result->questionid))) {
                        notify("Essay Table Migration: Cannot save comment");
                        break;
                    }
                    $state->event = 9;
                    //QUESTION_EVENTMANUALGRADE;
                } else {
                    // Not graded
                    $state->event = 7;
                    //QUESTION_EVENTSUBMIT;
                }
                // Save the event
                if (!($success = $success && update_record('question_states', $state))) {
                    notify("Essay Table Migration: Cannot update state");
                    break;
                }
            }
        }
        // dropping unused tables
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'question_essay_states');
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'question_essay');
        $success = $success && execute_sql('DROP TABLE ' . $CFG->prefix . 'quiz_attemptonlast_datasets');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question
            ALTER COLUMN qtype SET DEFAULT \'0\'');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question
            ALTER COLUMN version SET DEFAULT \'\'');
        // recreate the indexes that was not moved while quiz was transitioning to question lib
        $success && notify('Errors on indexes not being able to drop or already exists can be ignored as they may have been properly upgraded previously');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_answer_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_question_idx ON prefix_question_numerical (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_answer_idx ON prefix_question_numerical (answer)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_question_datasets_question_datasetdefinition_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_datasets_question_datasetdefinition_idx ON prefix_question_datasets (question, datasetdefinition)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_multichoice_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_multichoice_question_idx ON prefix_question_multichoice (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_categories_course_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_categories_course_idx ON prefix_question_categories (course)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_shortanswer_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_shortanswer_question_idx ON prefix_question_shortanswer (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_questions_category_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_category_idx ON prefix_question (category)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_calculated_answer_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_calculated_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_calculated_question_idx ON prefix_question_calculated (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_calculated_answer_idx ON prefix_question_calculated (answer)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_answers_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_answers_question_idx ON prefix_question_answers (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_dataset_items_definition_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_dataset_items_definition_idx ON prefix_question_dataset_items (definition)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_numerical_units_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_numerical_units_question_idx ON prefix_question_numerical_units (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_randomsamatch_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_randomsamatch_question_idx ON prefix_question_randomsamatch (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_states_question_idx');
        $success && modify_database('', 'DROP INDEX prefix_quiz_states_attempt_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_states_question_idx ON prefix_question_states (question)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_states_attempt_idx ON prefix_question_states (attempt)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_match_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_match_question_idx ON prefix_question_match (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_match_sub_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_match_sub_question_idx ON prefix_question_match_sub (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_multianswers_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_multianswer_question_idx ON prefix_question_multianswer (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_dataset_definitions_category_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_dataset_definitions_category_idx ON prefix_question_dataset_definitions (category)');
        $success = $success && modify_database('', 'CREATE INDEX prefix_log_timecoursemoduleaction_idx ON prefix_log ("time", course, module, "action")');
        $success = $success && modify_database('', 'CREATE INDEX prefix_log_coursemoduleaction_idx ON prefix_log (course, module, "action")');
        $success && modify_database('', 'DROP INDEX prefix_quiz_rqp_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_rqp_question_idx ON prefix_question_rqp (question)');
        $success && modify_database('', 'DROP INDEX prefix_quiz_truefalse_question_idx');
        $success = $success && modify_database('', 'CREATE INDEX prefix_question_truefalse_question_idx ON prefix_question_truefalse (question)');
        $success && notify('End of upgrading of indexes');
        $success && notify('Renaming primary key names');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical DROP CONSTRAINT prefix_quiz_numerical_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical ADD CONSTRAINT prefix_question_numerical_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_datasets DROP CONSTRAINT prefix_quiz_question_datasets_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_datasets ADD CONSTRAINT prefix_question_datasets_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multichoice DROP CONSTRAINT prefix_quiz_multichoice_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multichoice ADD CONSTRAINT prefix_question_multichoice_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_states DROP CONSTRAINT prefix_quiz_rqp_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_states ADD CONSTRAINT prefix_question_rqp_states_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_categories DROP CONSTRAINT prefix_quiz_categories_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_categories ADD CONSTRAINT prefix_question_categories_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_shortanswer DROP CONSTRAINT prefix_quiz_shortanswer_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_shortanswer ADD CONSTRAINT prefix_question_shortanswer_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question DROP CONSTRAINT prefix_quiz_questions_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question ADD CONSTRAINT prefix_question_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_sessions DROP CONSTRAINT prefix_quiz_newest_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_sessions ADD CONSTRAINT prefix_question_sessions_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_calculated DROP CONSTRAINT prefix_quiz_calculated_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_calculated ADD CONSTRAINT prefix_question_calculated_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_answers DROP CONSTRAINT prefix_quiz_answers_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_answers ADD CONSTRAINT prefix_question_answers_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_items DROP CONSTRAINT prefix_quiz_dataset_items_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_items ADD CONSTRAINT prefix_question_dataset_items_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical_units DROP CONSTRAINT prefix_quiz_numerical_units_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_numerical_units ADD CONSTRAINT prefix_question_numerical_units_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_randomsamatch DROP CONSTRAINT prefix_quiz_randomsamatch_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_randomsamatch ADD CONSTRAINT prefix_question_randomsamatch_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_types DROP CONSTRAINT prefix_quiz_rqp_types_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp_types ADD CONSTRAINT prefix_question_rqp_types_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_states DROP CONSTRAINT prefix_quiz_states_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_states ADD CONSTRAINT prefix_question_states_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match DROP CONSTRAINT prefix_quiz_match_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match ADD CONSTRAINT prefix_question_match_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match_sub DROP CONSTRAINT prefix_quiz_match_sub_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_match_sub ADD CONSTRAINT prefix_question_match_sub_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multianswer DROP CONSTRAINT prefix_quiz_multianswers_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_multianswer ADD CONSTRAINT prefix_question_multianswer_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_definitions DROP CONSTRAINT prefix_quiz_dataset_definitions_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_dataset_definitions ADD CONSTRAINT prefix_question_dataset_definitions_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp DROP CONSTRAINT prefix_quiz_rqp_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_rqp ADD CONSTRAINT prefix_question_rqp_pkey PRIMARY KEY (id)');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_truefalse DROP CONSTRAINT prefix_quiz_truefalse_pkey');
        $success = $success && modify_database('', 'ALTER TABLE prefix_question_truefalse ADD CONSTRAINT prefix_question_truefalse_pkey PRIMARY KEY (id)');
        $success && notify('End of renaming primary keys');
    }
    if ($oldversion < 2006081000) {
        // Add a column to the the question table to store the question general feedback.
        $success = $success && table_column('question', '', 'commentarytext', 'text', '', '', '', 'not null', 'image');
        // Adjust the quiz review options so that general feedback is displayed whenever feedback is.
        $success = $success && execute_sql('UPDATE ' . $CFG->prefix . 'quiz SET review = ' . '(review & ~' . QUIZ_REVIEW_GENERALFEEDBACK . ') | ' . '((review & ' . QUIZ_REVIEW_FEEDBACK . ') * 8)');
        // Set the general feedback bits to be the same as the feedback ones.
        // Same adjustment to the defaults for new quizzes.
        $success = $success && set_config('quiz_review', $CFG->quiz_review & ~QUIZ_REVIEW_GENERALFEEDBACK | ($CFG->quiz_review & QUIZ_REVIEW_FEEDBACK) << 3);
    }
    if ($success && $oldversion < 2006081400) {
        $success = $success && modify_database('', "\n            CREATE TABLE prefix_quiz_feedback (\n                id SERIAL PRIMARY KEY,\n                quizid integer NOT NULL default '0',\n                feedbacktext text NOT NULL default '',\n                maxgrade real NOT NULL default '0',\n                mingrade real NOT NULL default '0'\n            );\n        ");
        $success = $success && modify_database('', "CREATE INDEX prefix_quiz_feedback_quizid_idx ON prefix_quiz_feedback (quizid);");
        $success = $success && execute_sql("\n            INSERT INTO {$CFG->prefix}quiz_feedback (quizid, feedbacktext, maxgrade, mingrade)\n            SELECT id, '', grade + 1, 0 FROM {$CFG->prefix}quiz;\n        ");
    }
    if ($success && $oldversion < 2006082400) {
        $success = $success && table_column('question_sessions', 'comment', 'manualcomment', 'text', '', '', '');
    }
    if ($success && $oldversion < 2006091900) {
        $success = $success && table_column('question_dataset_items', 'number', 'itemnumber', 'integer');
    }
    if ($success && $oldversion < 2006091901) {
        $success = $success && table_column('question', 'commentarytext', 'generalfeedback', 'text', '', '', '');
    }
    //////  DO NOT ADD NEW THINGS HERE!!  USE upgrade.php and the lib/ddllib.php functions.
    return $success;
}
Example #14
0
 /**
  * Decode links in question type specific tables.
  * @return bool success or failure.
  */
 function decode_content_links_caller($questionids, $restore, &$i)
 {
     $status = true;
     // Decode links in the question_match_sub table.
     if ($subquestions = get_records_list('question_match_sub', 'question', implode(',', $questionids), '', 'id, questiontext')) {
         foreach ($subquestions as $subquestion) {
             $questiontext = restore_decode_content_links_worker($subquestion->questiontext, $restore);
             if ($questiontext != $subquestion->questiontext) {
                 $subquestion->questiontext = addslashes($questiontext);
                 if (!update_record('question_match_sub', $subquestion)) {
                     $status = false;
                 }
             }
             // Do some output.
             if (++$i % 5 == 0 && !defined('RESTORE_SILENTLY')) {
                 echo ".";
                 if ($i % 100 == 0) {
                     echo "<br />";
                 }
                 backup_flush(300);
             }
         }
     }
     return $status;
 }
Example #15
0
/**
* prints the human understandable search query form
* @param array $fields
*/
function tracker_printsearchfields($fields)
{
    foreach ($fields as $key => $value) {
        switch (trim($key)) {
            case 'datereported':
                if (!function_exists('trk_userdate')) {
                    function trk_userdate(&$a)
                    {
                        $a = userdate($a);
                        $a = preg_replace("/, \\d\\d:\\d\\d/", '', $a);
                    }
                }
                array_walk($value, 'trk_userdate');
                $strs[] = get_string($key, 'tracker') . ' ' . get_string('IN', 'tracker') . " ('" . implode("','", $value) . "')";
                break;
            case 'summary':
                $strs[] = "('" . implode("','", $value) . "') " . get_string('IN', 'tracker') . ' ' . get_string('summary', 'tracker');
                break;
            case 'description':
                $strs[] = "('" . implode("','", $value) . "') " . get_string('IN', 'tracker') . ' ' . get_string('description');
                break;
            case 'reportedby':
                $users = get_records_list('user', 'id', implode(',', $value), 'lastname', 'id,firstname,lastname');
                $reporters = array();
                if ($users) {
                    foreach ($users as $user) {
                        $reporters[] = fullname($user);
                    }
                }
                $reporterlist = implode("', '", $reporters);
                $strs[] = get_string('reportedby', 'tracker') . ' ' . get_string('IN', 'tracker') . " ('" . $reporterlist . "')";
                break;
            default:
                $strs[] = get_string($key, 'tracker') . ' ' . get_string('IN', 'tracker') . " ('" . implode("','", $value) . "')";
        }
    }
    return implode(' ' . get_string('AND', 'tracker') . ' ', $strs);
}
    foreach ($teachers as $teacher) {
        //if ($teacher->id != $course->id && $teacher->id != SITEID){
        if ($teacher->id != SITEID) {
            $tcourseids .= $teacher->id . ',';
        }
    }
}
print_heading(get_string("importsection", 'format_project'));
// quick forms
include_once 'import_form.php';
if (!$fromcourse) {
    // 私が担当したコース
    $taught_courses = array();
    if (!empty($tcourseids)) {
        $tcourseids = substr($tcourseids, 0, -1);
        $taught_courses = get_records_list('course', 'id', $tcourseids);
    }
    if (!empty($creator)) {
        $cat_courses = get_courses($course->category);
    } else {
        $cat_courses = array();
    }
    $options = array();
    foreach ($taught_courses as $tcourse) {
        //if ($tcourse->id != $course->id && $tcourse->id != SITEID){
        if ($tcourse->format == 'project') {
            $options[$tcourse->id] = format_string($tcourse->fullname);
        }
    }
    if (empty($options) && empty($creator)) {
        notify(get_string('courseimportnotaught'));
function quiz_restore_pre15_multianswer($old_question_id, $new_question_id, $info, $restore)
{
    global $CFG;
    $status = true;
    //We need some question fields here so we get the full record from DB
    $parentquestion = get_record('question', 'id', $new_question_id);
    //We need to store all the positions with their created questions
    //to be able to calculate the sequence field
    $createdquestions = array();
    //Under 1.5, every multianswer record becomes a question itself
    //with its parent set to the cloze question. And there is only
    //ONE multianswer record with the sequence of questions used.
    //Get the multianswers array
    $multianswers_array = $info['#']['MULTIANSWERS']['0']['#']['MULTIANSWER'];
    //Iterate over multianswers_array
    for ($i = 0; $i < sizeof($multianswers_array); $i++) {
        $mul_info = $multianswers_array[$i];
        //traverse_xmlize($mul_info);                                                                 //Debug
        //print_object ($GLOBALS['traverse_array']);                                                  //Debug
        //$GLOBALS['traverse_array']="";                                                              //Debug
        //We need this later
        $oldid = backup_todb($mul_info['#']['ID']['0']['#']);
        //Now, build the question_multianswer record structure
        $multianswer->question = $new_question_id;
        $multianswer->answers = backup_todb($mul_info['#']['ANSWERS']['0']['#']);
        $multianswer->positionkey = backup_todb($mul_info['#']['POSITIONKEY']['0']['#']);
        $multianswer->answertype = backup_todb($mul_info['#']['ANSWERTYPE']['0']['#']);
        $multianswer->norm = backup_todb($mul_info['#']['NORM']['0']['#']);
        //Saving multianswer and positionkey to use them later restoring states
        backup_putid($restore->backup_unique_code, 'multianswer-pos', $oldid, $multianswer->positionkey);
        //We have to recode all the answers to their new ids
        $ansarr = explode(",", $multianswer->answers);
        foreach ($ansarr as $key => $value) {
            //Get the answer from backup_ids
            $answer = backup_getid($restore->backup_unique_code, 'question_answers', $value);
            $ansarr[$key] = $answer->new_id;
        }
        $multianswer->answers = implode(",", $ansarr);
        //Build the new question structure
        $question = new object();
        $question->category = $parentquestion->category;
        $question->parent = $parentquestion->id;
        $question->name = $parentquestion->name;
        $question->questiontextformat = $parentquestion->questiontextformat;
        $question->defaultgrade = $multianswer->norm;
        $question->penalty = $parentquestion->penalty;
        $question->qtype = $multianswer->answertype;
        $question->version = $parentquestion->version;
        $question->hidden = $parentquestion->hidden;
        $question->length = 0;
        $question->questiontext = '';
        $question->stamp = make_unique_id_code();
        //Save the new question to DB
        $newid = insert_record('question', $question);
        if ($newid) {
            $createdquestions[$multianswer->positionkey] = $newid;
        }
        //Do some output
        if (($i + 1) % 50 == 0) {
            if (!defined('RESTORE_SILENTLY')) {
                echo ".";
                if (($i + 1) % 1000 == 0) {
                    echo "<br />";
                }
            }
            backup_flush(300);
        }
        //Remap question_answers records from the original multianswer question
        //to their newly created question
        if ($newid) {
            $answersdb = get_records_list('question_answers', 'id', $multianswer->answers);
            foreach ($answersdb as $answerdb) {
                set_field('question_answers', 'question', $newid, 'id', $answerdb->id);
            }
        }
        //If we have created the question record, now, depending of the
        //answertype, delegate the restore to every qtype function
        if ($newid) {
            if ($multianswer->answertype == "1") {
                $status = quiz_restore_pre15_shortanswer($old_question_id, $newid, $mul_info, $restore, $multianswer->answers);
            } else {
                if ($multianswer->answertype == "3") {
                    $status = quiz_restore_pre15_multichoice($old_question_id, $newid, $mul_info, $restore, $multianswer->answers);
                } else {
                    if ($multianswer->answertype == "8") {
                        $status = quiz_restore_pre15_numerical($old_question_id, $newid, $mul_info, $restore, $multianswer->answers);
                    }
                }
            }
        } else {
            $status = false;
        }
    }
    //Everything is created, just going to create the multianswer record
    if ($status) {
        ksort($createdquestions);
        $multianswerdb = new object();
        $multianswerdb->question = $parentquestion->id;
        $multianswerdb->sequence = implode(",", $createdquestions);
        $mid = insert_record('question_multianswer', $multianswerdb);
        if (!$mid) {
            $status = false;
        }
    }
    return $status;
}
Example #18
0
         }
     }
     $graph->parameter['y_max_left'] = $numoptions - 1;
     $graph->parameter['y_axis_gridlines'] = $numoptions;
     $graph->parameter['y_resolution_left'] = 1;
     $graph->parameter['y_decimal_left'] = 1;
     $graph->parameter['x_axis_angle'] = 20;
     $graph->draw();
     break;
 case "studentmultiquestion.png":
     $question = get_record("survey_questions", "id", $qid);
     $question->text = get_string($question->text, "survey");
     $question->options = get_string($question->options, "survey");
     $options = explode(",", $question->options);
     $questionorder = explode(",", $question->multi);
     $qqq = get_records_list("survey_questions", "id", $question->multi);
     foreach ($questionorder as $i => $val) {
         $names[$i] = get_string($qqq[$val]->shorttext, "survey");
         $buckets1[$i] = 0;
         $buckets2[$i] = 0;
         $count1[$i] = 0;
         $count2[$i] = 0;
         $indexof[$val] = $i;
         $studbuckets1[$i] = 0.0;
         $studbuckets2[$i] = 0.0;
         $studcount1[$i] = 0;
         $studcount2[$i] = 0;
         $stdev1[$i] = 0.0;
         $stdev2[$i] = 0.0;
     }
     $aaa = get_records_select("survey_answers", "((survey = {$cm->instance}) AND (question in ({$question->multi})))");
Example #19
0
if (has_capability('moodle/course:create', $syscontext)) {
    $creator = true;
}
$strimport = get_string("importdata");
$tcourseids = '';
if ($teachers = get_user_capability_course('moodle/course:update')) {
    foreach ($teachers as $teacher) {
        if ($teacher->id != $course->id && $teacher->id != SITEID) {
            $tcourseids .= $teacher->id . ',';
        }
    }
}
$taught_courses = array();
if (!empty($tcourseids)) {
    $tcourseids = substr($tcourseids, 0, -1);
    $taught_courses = get_records_list('course', 'id', $tcourseids, 'sortorder');
}
if (!empty($creator)) {
    $cat_courses = get_courses($course->category, $sort = "c.sortorder ASC", $fields = "c.id, c.fullname");
} else {
    $cat_courses = array();
}
print_heading(get_string("importactivities"));
$options = array();
foreach ($taught_courses as $tcourse) {
    if ($tcourse->id != $course->id && $tcourse->id != SITEID) {
        $options[$tcourse->id] = format_string($tcourse->fullname);
    }
}
if (empty($options) && empty($creator)) {
    notify(get_string('courseimportnotaught'));
function attforblock_backup_attendance_log($bf, $preferences, $attforblock)
{
    global $CFG;
    $status = true;
    $sessions = get_records_menu('attendance_sessions', 'courseid', $attforblock->course);
    $sesslist = implode(',', array_keys($sessions));
    $datas = get_records_list('attendance_log', 'sessionid', $sesslist);
    //If there is levels
    if ($datas) {
        //Write start tag
        $status = fwrite($bf, start_tag('LOGS', 4, true));
        //Iterate over each log
        foreach ($datas as $item) {
            //Start log
            $status = fwrite($bf, start_tag('LOG', 5, true));
            //Print log contents
            fwrite($bf, full_tag('ID', 6, false, $item->id));
            fwrite($bf, full_tag('SESSIONID', 6, false, $item->sessionid));
            fwrite($bf, full_tag('STUDENTID', 6, false, $item->studentid));
            fwrite($bf, full_tag('STATUSID', 6, false, $item->statusid));
            fwrite($bf, full_tag('TIMETAKEN', 6, false, $item->timetaken));
            fwrite($bf, full_tag('TAKENBY', 6, false, $item->takenby));
            fwrite($bf, full_tag('STATUSSET', 6, false, $item->statusset));
            fwrite($bf, full_tag('REMARKS', 6, false, $item->remarks));
            //End submission
            $status = fwrite($bf, end_tag('LOG', 5, true));
        }
        //Write end tag
        $status = fwrite($bf, end_tag('LOGS', 4, true));
    }
    return $status;
}
/**
* part of search engine API
* @glossary a glossary instance
* @return an array of searchable documents
*/
function glossary_get_content_for_index(&$glossary)
{
    // global $DB;
    // get context
    $coursemodule = get_field('modules', 'id', 'name', 'glossary');
    $cm = get_record('course_modules', 'course', $glossary->course, 'module', $coursemodule, 'instance', $glossary->id);
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $documents = array();
    $entryIds = array();
    // index entries
    $entries = get_records('glossary_entries', 'glossaryid', $glossary->id);
    if ($entries) {
        foreach ($entries as $entry) {
            $concepts[$entry->id] = $entry->concept;
            if (strlen($entry->definition) > 0) {
                $entryIds[] = $entry->id;
                $documents[] = new GlossarySearchDocument(get_object_vars($entry), $glossary->course, $context->id);
            }
        }
    }
    // index comments
    if (count($entryIds)) {
        $comments = get_records_list('glossary_comments', 'entryid', implode(',', $entryIds));
        if ($comments) {
            foreach ($comments as $comment) {
                if (strlen($comment->entrycomment) > 0) {
                    $comment->concept = $concepts[$comment->entryid];
                    $documents[] = new GlossaryCommentSearchDocument(get_object_vars($comment), $glossary->id, $glossary->course, $context->id);
                }
            }
        }
    }
    return $documents;
}
 function mass_grade()
 {
     global $CFG;
     require_once $CFG->dirroot . '/config.php';
     require_once $CFG->libdir . '/gradelib.php';
     $navigation = build_navigation($this->strsubmissions, $this->cm);
     print_header_simple(format_string($this->assignment->name, true), "", $navigation, '', '', true, update_module_button($this->cm->id, $this->course->id, $this->strassignment), navmenu($this->course, $this->cm));
     print_heading(get_string('settingmarks', 'assignment_peerreview'), 1);
     // Get submissions with reviews so that grades can be set
     $criteriaList = get_records_list('assignment_criteria', 'assignment', $this->assignment->id, 'ordernumber');
     if ($criteriaList && count($criteriaList) > 0) {
         $criteriaList = array_values($criteriaList);
         $query = 'SELECT a.userid, SUM(r.complete) as reviewscomplete, a.timemarked, a.timecreated, a.id, u.firstname, u.lastname ' . 'FROM ' . $CFG->prefix . 'assignment_submissions a, ' . $CFG->prefix . 'assignment_review r, ' . $CFG->prefix . 'user u ' . 'WHERE a.assignment=' . $this->assignment->id . ' ' . 'AND r.assignment=' . $this->assignment->id . ' ' . 'AND r.teacherreview=0 ' . 'AND a.userid=r.reviewer ' . 'AND a.userid=u.id ' . 'GROUP BY a.userid, a.timemarked, a.timecreated, a.id, u.firstname, u.lastname ' . 'ORDER BY a.timecreated ASC, a.id ASC';
         $submissions = get_records_sql($query);
         if ($submissions && count($submissions) > 0) {
             $submissions = array_values($submissions);
             $numberOfSubmissions = count($submissions);
             // Output the table of submissions as they are marked
             echo '<div align="center"><table border="0" cellpadding="5" cellspacing="0">';
             for ($i = 0; $i < $numberOfSubmissions; $i++) {
                 echo '<tr><td><strong>' . fullname($submissions[$i]) . '</strong></td><td>';
                 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submissions[$i]->userid);
                 if (!$grading_info->items[0]->grades[$submissions[$i]->userid]->locked && !$grading_info->items[0]->grades[$submissions[$i]->userid]->overridden && $submissions[$i]->timemarked == 0) {
                     $reviews = $this->get_reviews_of_student($submissions[$i]->userid);
                     $grade = $this->get_marks($reviews, $criteriaList, $submissions[$i]->reviewscomplete, $this->assignment->var1);
                     if ($grade != '???') {
                         $submission = $this->set_grade($submissions[$i]->userid, $grade);
                         echo get_string('gradeset', 'assignment_peerreview') . '</td><td>' . $this->display_grade($grade) . '</td><td>' . ($submission->mailed ? get_string('emailsent', 'assignment_peerreview') : get_string('emailnotsent', 'assignment_peerreview')) . '</td>';
                     } else {
                         echo get_string('unabletoset', 'assignment_peerreview') . '</td><td>' . get_string('moderationrequired', 'assignment_peerreview') . '</td><td>' . get_string('emailnotsent', 'assignment_peerreview') . '</td>';
                     }
                 } else {
                     echo get_string('previouslyset', 'assignment_peerreview') . '</td><td>' . get_string('nochange', 'assignment_peerreview') . '</td><td>' . get_string('emailnotsent', 'assignment_peerreview') . '</td>';
                 }
                 echo '</tr>';
             }
             echo '</table></div>';
         } else {
             notify(get_string('nocompletesubmissions', 'assignment_peerreview'));
         }
     } else {
         notify(get_string('nocriteriaset', 'assignment_peerreview'));
     }
     print_continue($CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
     $this->view_footer();
 }
Example #23
0
 /**
  * Prints a table of course modules in which the question is used
  *
  * TODO: This should be made quiz-independent
  *
  * This function is used near the end of the question edit forms in all question types
  * It prints the table of quizzes in which the question is used
  * containing checkboxes to allow the teacher to replace the old question version
  *
  * @param object $question
  * @param object $course
  * @param integer $cmid optional The id of the course module currently being edited
  */
 function print_replacement_options($question, $course, $cmid = '0')
 {
     // Disable until the versioning code has been fixed
     if (true) {
         return;
     }
     // no need to display replacement options if the question is new
     if (empty($question->id)) {
         return true;
     }
     // get quizzes using the question (using the question_instances table)
     $quizlist = array();
     if (!($instances = get_records('quiz_question_instances', 'question', $question->id))) {
         $instances = array();
     }
     foreach ($instances as $instance) {
         $quizlist[$instance->quiz] = $instance->quiz;
     }
     $quizlist = implode(',', $quizlist);
     if (empty($quizlist) or !($quizzes = get_records_list('quiz', 'id', $quizlist))) {
         $quizzes = array();
     }
     // do the printing
     if (count($quizzes) > 0) {
         // print the table
         $strquizname = get_string('modulename', 'quiz');
         $strdoreplace = get_string('replace', 'quiz');
         $straffectedstudents = get_string('affectedstudents', 'quiz', $course->students);
         echo "<tr valign=\"top\">\n";
         echo "<td align=\"right\"><b>" . get_string("replacementoptions", "quiz") . ":</b></td>\n";
         echo "<td align=\"left\">\n";
         echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
         echo "<tr>\n";
         echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">{$strquizname}</th>\n";
         echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">{$strdoreplace}</th>\n";
         echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">{$straffectedstudents}</th>\n";
         echo "</tr>\n";
         foreach ($quizzes as $quiz) {
             // work out whethere it should be checked by default
             $checked = '';
             if ((int) $cmid === (int) $quiz->id or empty($quiz->usercount)) {
                 $checked = "checked=\"checked\"";
             }
             // find how many different students have already attempted this quiz
             $students = array();
             if ($attempts = get_records_select('quiz_attempts', "quiz = '{$quiz->id}' AND preview = '0'")) {
                 foreach ($attempts as $attempt) {
                     if (record_exists('question_states', 'attempt', $attempt->uniqueid, 'question', $question->id, 'originalquestion', 0)) {
                         $students[$attempt->userid] = 1;
                     }
                 }
             }
             $studentcount = count($students);
             $strstudents = $studentcount === 1 ? $course->student : $course->students;
             echo "<tr>\n";
             echo "<td align=\"left\" class=\"generaltablecell c0\">" . format_string($quiz->name) . "</td>\n";
             echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" " . $checked . " /></td>\n";
             echo "<td align=\"left\" class=\"generaltablecell c0\">" . ($studentcount ? $studentcount . ' ' . $strstudents : '-') . "</td>\n";
             echo "</tr>\n";
         }
         echo "</table>\n";
     }
     echo "</td></tr>\n";
 }
        $accessdata = get_role_access($guestrole->id);
        $accessdata['ra'][$systempath] = array($guestrole->id);
    } else {
        load_user_accessdata($userid);
        $accessdata = $ACCESS[$userid];
    }
}
if ($context->contextlevel > CONTEXT_COURSE && !path_inaccessdata($context->path, $accessdata)) {
    load_subcontext($userid, $context, $accessdata);
}
// Load the roles we need.
$roleids = array();
foreach ($accessdata['ra'] as $roleassignments) {
    $roleids = array_merge($roleassignments, $roleids);
}
$roles = get_records_list('role', 'id', $roleids);
$rolenames = array();
foreach ($roles as $role) {
    $rolenames[$role->id] = $role->name;
}
$rolenames = role_fix_names($rolenames, $context);
// Pass over the data once, to find the cell that determines the result.
$userhascapability = has_capability($capability, $context, $userid, false);
$areprohibits = false;
$decisiveassigncon = 0;
$decisiveoverridecon = 0;
foreach ($contexts as $con) {
    if (!empty($accessdata['ra'][$con->path])) {
        // The array_unique here is to work around bug MDL-14817. Once that bug is
        // fixed, it can be removed
        $ras = array_unique($accessdata['ra'][$con->path]);
Example #25
0
/**
 * Prints tables of detected plugins, one table per plugin type,
 * and prints whether they are part of the standard Moodle 
 * distribution or not.
 */
function print_plugin_tables()
{
    $plugins_standard = array();
    $plugins_standard['mod'] = array('assignment', 'chat', 'choice', 'data', 'exercise', 'forum', 'glossary', 'hotpot', 'journal', 'label', 'lams', 'lesson', 'quiz', 'resource', 'scorm', 'survey', 'wiki', 'workshop');
    $plugins_standard['blocks'] = array('activity_modules', 'admin', 'admin_bookmarks', 'admin_tree', 'blog_menu', 'blog_tags', 'calendar_month', 'calendar_upcoming', 'course_list', 'course_summary', 'glossary_random', 'html', 'loancalc', 'login', 'mentees', 'messages', 'mnet_hosts', 'news_items', 'online_users', 'participants', 'quiz_results', 'recent_activity', 'rss_client', 'search', 'search_forums', 'section_links', 'site_main_menu', 'social_activities', 'tag_flickr', 'tag_youtube', 'tags');
    $plugins_standard['filter'] = array('activitynames', 'algebra', 'censor', 'emailprotect', 'filter', 'mediaplugin', 'multilang', 'tex', 'tidy');
    $plugins_installed = array();
    $installed_mods = get_records_list('modules', '', '', '', 'name');
    $installed_blocks = get_records_list('block', '', '', '', 'name');
    foreach ($installed_mods as $mod) {
        $plugins_installed['mod'][] = $mod->name;
    }
    foreach ($installed_blocks as $block) {
        $plugins_installed['blocks'][] = $block->name;
    }
    $plugins_ondisk = array();
    $plugins_ondisk['mod'] = get_list_of_plugins('mod', 'db');
    $plugins_ondisk['blocks'] = get_list_of_plugins('blocks', 'db');
    $plugins_ondisk['filter'] = get_list_of_plugins('filter', 'db');
    $strstandard = get_string('standard');
    $strnonstandard = get_string('nonstandard');
    $strmissingfromdisk = '(' . get_string('missingfromdisk') . ')';
    $strabouttobeinstalled = '(' . get_string('abouttobeinstalled') . ')';
    $html = '';
    $html .= '<table class="generaltable plugincheckwrapper" cellspacing="4" cellpadding="1"><tr valign="top">';
    foreach ($plugins_ondisk as $cat => $list_ondisk) {
        $strcaption = get_string($cat);
        if ($cat == 'mod') {
            $strcaption = get_string('activitymodule');
        } elseif ($cat == 'filter') {
            $strcaption = get_string('managefilters');
        }
        $html .= '<td><table class="plugincompattable generaltable boxaligncenter" cellspacing="1" cellpadding="5" ' . 'id="' . $cat . 'compattable" summary="compatibility table"><caption>' . $strcaption . '</caption>' . "\n";
        $html .= '<tr class="r0"><th class="header c0">' . get_string('directory') . "</th>\n" . '<th class="header c1">' . get_string('name') . "</th>\n" . '<th class="header c2">' . get_string('status') . "</th>\n</tr>\n";
        $row = 1;
        foreach ($list_ondisk as $k => $plugin) {
            $status = 'ok';
            $standard = 'standard';
            $note = '';
            if (!in_array($plugin, $plugins_standard[$cat])) {
                $standard = 'nonstandard';
                $status = 'warning';
            }
            // Get real name and full path of plugin
            $plugin_name = "[[{$plugin}]]";
            $plugin_path = "{$cat}/{$plugin}";
            $plugin_name = get_plugin_name($plugin, $cat);
            // Determine if the plugin is about to be installed
            if ($cat != 'filter' && !in_array($plugin, $plugins_installed[$cat])) {
                $note = $strabouttobeinstalled;
                $plugin_name = $plugin;
            }
            $html .= "<tr class=\"r{$row}\">\n" . "<td class=\"cell c0\">{$plugin_path}</td>\n" . "<td class=\"cell c1\">{$plugin_name}</td>\n" . "<td class=\"{$standard} {$status} cell c2\">" . ${'str' . $standard} . " {$note}</td>\n</tr>\n";
            $row++;
            // If the plugin was both on disk and in the db, unset the value from the installed plugins list
            if ($key = array_search($plugin, $plugins_installed[$cat])) {
                unset($plugins_installed[$cat][$key]);
            }
        }
        // If there are plugins left in the plugins_installed list, it means they are missing from disk
        foreach ($plugins_installed[$cat] as $k => $missing_plugin) {
            // Make sure the plugin really is missing from disk
            if (!in_array($missing_plugin, $plugins_ondisk[$cat])) {
                $standard = 'standard';
                $status = 'warning';
                if (!in_array($missing_plugin, $plugins_standard[$cat])) {
                    $standard = 'nonstandard';
                }
                $plugin_name = $missing_plugin;
                $html .= "<tr class=\"r{$row}\">\n" . "<td class=\"cell c0\">?</td>\n" . "<td class=\"cell c1\">{$plugin_name}</td>\n" . "<td class=\"{$standard} {$status} cell c2\">" . ${'str' . $standard} . " {$strmissingfromdisk}</td>\n</tr>\n";
                $row++;
            }
        }
        $html .= '</table></td>';
    }
    $html .= '</tr></table><br />';
    echo $html;
}
function xmldb_attforblock_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    if ($result && $oldversion < 2008021904) {
        //New version in version.php
        global $USER;
        if ($sessions = get_records('attendance_sessions', 'takenby', 0)) {
            foreach ($sessions as $sess) {
                if (count_records('attendance_log', 'attsid', $sess->id) > 0) {
                    $sess->takenby = $USER->id;
                    $sess->timetaken = $sess->timemodified ? $sess->timemodified : time();
                    $sess->description = addslashes($sess->description);
                    $result = update_record('attendance_sessions', $sess) and $result;
                }
            }
        }
    }
    if ($oldversion < 2008102401 and $result) {
        $table = new XMLDBTable('attforblock');
        $field = new XMLDBField('grade');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, '100', 'name');
        $result = $result && add_field($table, $field);
        $table = new XMLDBTable('attendance_sessions');
        $field = new XMLDBField('courseid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
        $result = $result && change_field_unsigned($table, $field);
        //        $field = new XMLDBField('creator');
        //        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'courseid');
        //        $result = $result && change_field_unsigned($table, $field);
        $field = new XMLDBField('sessdate');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'creator');
        $result = $result && change_field_unsigned($table, $field);
        $field = new XMLDBField('duration');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'sessdate');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('timetaken');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'takenby');
        $result = $result && change_field_unsigned($table, $field);
        $result = $result && rename_field($table, $field, 'lasttaken');
        $field = new XMLDBField('takenby');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'lasttaken');
        $result = $result && change_field_unsigned($table, $field);
        $result = $result && rename_field($table, $field, 'lasttakenby');
        $field = new XMLDBField('timemodified');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'lasttaken');
        $result = $result && change_field_unsigned($table, $field);
        $table = new XMLDBTable('attendance_log');
        $field = new XMLDBField('attsid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
        $result = $result && change_field_unsigned($table, $field);
        $field = new XMLDBField('studentid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'attsid');
        $result = $result && change_field_unsigned($table, $field);
        $field = new XMLDBField('statusid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'status');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('statusset');
        $field->setAttributes(XMLDB_TYPE_CHAR, '100', null, null, null, null, null, null, 'statusid');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('timetaken');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'statusid');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('takenby');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'timetaken');
        $result = $result && add_field($table, $field);
        //Indexes
        $index = new XMLDBIndex('statusid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('statusid'));
        $result = $result && add_index($table, $index);
        $index = new XMLDBIndex('attsid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('attsid'));
        $result = $result && drop_index($table, $index);
        $field = new XMLDBField('attsid');
        //Rename field
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
        $result = $result && rename_field($table, $field, 'sessionid');
        $index = new XMLDBIndex('sessionid');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('sessionid'));
        $result = $result && add_index($table, $index);
        $table = new XMLDBTable('attendance_settings');
        $field = new XMLDBField('courseid');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'id');
        $result = $result && change_field_unsigned($table, $field);
        $field = new XMLDBField('visible');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '1', 'grade');
        $result = $result && add_field($table, $field);
        $field = new XMLDBField('deleted');
        $field->setAttributes(XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0', 'visible');
        $result = $result && add_field($table, $field);
        //Indexes
        $index = new XMLDBIndex('visible');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('visible'));
        $result = $result && add_index($table, $index);
        $index = new XMLDBIndex('deleted');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('deleted'));
        $result = $result && add_index($table, $index);
        $result = $result && rename_table($table, 'attendance_statuses');
    }
    if ($oldversion < 2008102406 and $result) {
        if ($courses = get_records_sql("SELECT courseid FROM {$CFG->prefix}attendance_sessions GROUP BY courseid")) {
            foreach ($courses as $c) {
                //Adding own status for course (now it must have own)
                if (!count_records('attendance_statuses', 'courseid', $c->courseid)) {
                    $statuses = get_records('attendance_statuses', 'courseid', 0);
                    foreach ($statuses as $stat) {
                        $rec = $stat;
                        $rec->courseid = $c->courseid;
                        insert_record('attendance_statuses', $rec);
                    }
                }
                $statuses = get_records('attendance_statuses', 'courseid', $c->courseid);
                $statlist = implode(',', array_keys($statuses));
                $sess = get_records_select_menu('attendance_sessions', "courseid = {$c->courseid} AND lasttakenby > 0");
                $sesslist = implode(',', array_keys($sess));
                foreach ($statuses as $stat) {
                    execute_sql("UPDATE {$CFG->prefix}attendance_log\n\t\t\t\t\t\t\t\t\t\tSET statusid = {$stat->id}, statusset = '{$statlist}'\n\t\t\t\t\t\t\t\t\t  WHERE sessionid IN ({$sesslist}) AND status = '{$stat->status}'");
                }
                $sessions = get_records_list('attendance_sessions', 'id', $sesslist);
                foreach ($sessions as $sess) {
                    execute_sql("UPDATE {$CFG->prefix}attendance_log\n\t\t\t\t\t\t\t\t\t\tSET timetaken = {$sess->lasttaken}, \n\t\t\t\t\t\t\t\t\t\t\ttakenby = {$sess->lasttakenby}\n\t\t\t\t\t\t\t\t\t  WHERE sessionid = {$sess->id}");
                }
            }
        }
    }
    if ($oldversion < 2008102409 and $result) {
        $table = new XMLDBTable('attendance_statuses');
        $field = new XMLDBField('status');
        $result = $result && drop_field($table, $field);
        $index = new XMLDBIndex('status');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('status'));
        $result = $result && drop_index($table, $index);
        $table = new XMLDBTable('attendance_log');
        $field = new XMLDBField('status');
        $result = $result && drop_field($table, $field);
        $index = new XMLDBIndex('status');
        $index->setAttributes(XMLDB_INDEX_NOTUNIQUE, array('status'));
        $result = $result && drop_index($table, $index);
        $table = new XMLDBTable('attendance_sessions');
        $field = new XMLDBField('creator');
        $result = $result && drop_field($table, $field);
    }
    return $result;
}
Example #27
0
 function save_question_options($question)
 {
     global $QTYPES;
     $result = new stdClass();
     // This function needs to be able to handle the case where the existing set of wrapped
     // questions does not match the new set of wrapped questions so that some need to be
     // created, some modified and some deleted
     // Unfortunately the code currently simply overwrites existing ones in sequence. This
     // will make re-marking after a re-ordering of wrapped questions impossible and
     // will also create difficulties if questiontype specific tables reference the id.
     // First we get all the existing wrapped questions
     if (!($oldwrappedids = get_field('question_multianswer', 'sequence', 'question', $question->id))) {
         $oldwrappedquestions = array();
     } else {
         $oldwrappedquestions = get_records_list('question', 'id', $oldwrappedids, 'id ASC');
     }
     $sequence = array();
     foreach ($question->options->questions as $wrapped) {
         if (!empty($wrapped)) {
             // if we still have some old wrapped question ids, reuse the next of them
             if (is_array($oldwrappedquestions) && ($oldwrappedquestion = array_shift($oldwrappedquestions))) {
                 $wrapped->id = $oldwrappedquestion->id;
                 if ($oldwrappedquestion->qtype != $wrapped->qtype) {
                     switch ($oldwrappedquestion->qtype) {
                         case 'multichoice':
                             delete_records('question_multichoice', 'question', $oldwrappedquestion->id);
                             break;
                         case 'shortanswer':
                             delete_records('question_shortanswer', 'question', $oldwrappedquestion->id);
                             break;
                         case 'numerical':
                             delete_records('question_numerical', 'question', $oldwrappedquestion->id);
                             break;
                         default:
                             print_error('qtypenotrecognized', 'qtype_multianswer', '', $oldwrappedquestion->qtype);
                             $wrapped->id = 0;
                     }
                 }
             } else {
                 $wrapped->id = 0;
             }
         }
         $wrapped->name = $question->name;
         $wrapped->parent = $question->id;
         $previousid = $wrapped->id;
         $wrapped->category = $question->category . ',1';
         // save_question strips this extra bit off again.
         $wrapped = $QTYPES[$wrapped->qtype]->save_question($wrapped, $wrapped, $question->course);
         $sequence[] = $wrapped->id;
         if ($previousid != 0 && $previousid != $wrapped->id) {
             // for some reasons a new question has been created
             // so delete the old one
             delete_question($previousid);
         }
     }
     // Delete redundant wrapped questions
     if (is_array($oldwrappedquestions) && count($oldwrappedquestions)) {
         foreach ($oldwrappedquestions as $oldwrappedquestion) {
             delete_question($oldwrappedquestion->id);
         }
     }
     if (!empty($sequence)) {
         $multianswer = new stdClass();
         $multianswer->question = $question->id;
         $multianswer->sequence = implode(',', $sequence);
         if ($oldid = get_field('question_multianswer', 'id', 'question', $question->id)) {
             $multianswer->id = $oldid;
             if (!update_record("question_multianswer", $multianswer)) {
                 $result->error = "Could not update cloze question options! " . "(id={$multianswer->id})";
                 return $result;
             }
         } else {
             if (!insert_record("question_multianswer", $multianswer)) {
                 $result->error = "Could not insert cloze question options!";
                 return $result;
             }
         }
     }
 }
Example #28
0
function hotpot_get_chain(&$cm)
{
    // get details of course_modules in this section
    $course_module_ids = get_field('course_sections', 'sequence', 'id', $cm->section);
    if (empty($course_module_ids)) {
        $hotpot_modules = array();
    } else {
        $hotpot_modules = get_records_select('course_modules', "id IN ({$course_module_ids}) AND module={$cm->module}");
        if (empty($hotpot_modules)) {
            $hotpot_modules = array();
        }
    }
    // get ids of hotpot modules in this section
    $ids = array();
    foreach ($hotpot_modules as $hotpot_module) {
        $ids[] = $hotpot_module->instance;
    }
    // get details of hotpots in this section
    if (empty($ids)) {
        $hotpots = array();
    } else {
        $hotpots = get_records_list('hotpot', 'id', implode(',', $ids));
    }
    $found = false;
    $chain = array();
    // loop through course_modules in this section
    $ids = explode(',', $course_module_ids);
    foreach ($ids as $id) {
        // check this course_module is a hotpot activity
        if (isset($hotpot_modules[$id])) {
            // store details of this course module and hotpot activity
            $hotpot_id = $hotpot_modules[$id]->instance;
            $chain[$id] =& $hotpot_modules[$id];
            $chain[$id]->hotpot =& $hotpots[$hotpot_id];
            // set $found, if this is the course module we're looking for
            if (isset($cm->coursemodule)) {
                if ($id == $cm->coursemodule) {
                    $found = true;
                }
            } else {
                if ($id == $cm->id) {
                    $found = true;
                }
            }
            // is this the end of a chain
            if (empty($hotpots[$hotpot_id]->shownextquiz)) {
                if ($found) {
                    break;
                    // out of loop
                } else {
                    // restart chain (target cm has not been found yet)
                    $chain = array();
                }
            }
        }
    }
    // end foreach $ids
    return $found ? $chain : false;
}
/**
 * Gets link data for all passed links and organizes the records
 * in an array keyed on the linkid.
 *
 * @param array $links An array of links with the keys = linkid
 * @return array
 **/
function pagemenu_get_link_data($links)
{
    $organized = array();
    if ($data = get_records_list('pagemenu_link_data', 'linkid', implode(',', array_keys($links)))) {
        foreach ($data as $datum) {
            if (!array_key_exists($datum->linkid, $organized)) {
                $organized[$datum->linkid] = array();
            }
            $organized[$datum->linkid][] = $datum;
        }
    }
    return $organized;
}
        redirect('manage.php?id=' . $id, get_string('sessionupdated', 'attforblock'), 3);
    }
    print_heading(get_string('update', 'attforblock') . ' ' . get_string('attendanceforthecourse', 'attforblock') . ' :: ' . $course->fullname);
    $mform_subject->display();
}
//////////////////////////////////////////////////////////
// Change sessiontitles
//////////////////////////////////////////////////////////
if ($action === 'changesessiontitle') {
    $fromform = data_submitted();
    $slist = isset($fromform->sessid) ? implode('_', array_keys($fromform->sessid)) : '';
    $mform_sessiontitle = new mod_attforblock_sessiontitle_form('sessions.php', array('course' => $course, 'cm' => $cm, 'modcontext' => $context, 'ids' => $slist));
    if ($mform_sessiontitle->is_cancelled()) {
        redirect('manage.php?id=' . $id);
    }
    if ($fromform = $mform_sessiontitle->get_data()) {
        $slist = implode(',', explode('_', $fromform->ids));
        if (!($sessions = get_records_list('attendance_sessions', 'id', $slist))) {
            error('No such session in this course');
        }
        foreach ($sessions as $sess) {
            $sess->sessiontitle = $fromform->ssessiontitle;
            update_record('attendance_sessions', $sess);
        }
        add_to_log($course->id, 'attforblock', 'Session updated', 'manage.php?id=' . $id, $user->lastname . ' ' . $user->firstname);
        redirect('manage.php?id=' . $id, get_string('sessionupdated', 'attforblock'), 3);
    }
    print_heading(get_string('update', 'attforblock') . ' ' . get_string('attendanceforthecourse', 'attforblock') . ' :: ' . $course->fullname);
    $mform_sessiontitle->display();
}
print_footer($course);