From: nicolasconnault Date: Fri, 6 Jun 2008 14:43:15 +0000 (+0000) Subject: MDL-15102 Upgrade to DMLLIB 2.0. Needs further testing and bug-fixing. X-Git-Url: http://git.mjollnir.org/gw?a=commitdiff_plain;h=f34488b2e6332b61ca4ac9e651ec3078478587c6;p=moodle.git MDL-15102 Upgrade to DMLLIB 2.0. Needs further testing and bug-fixing. --- diff --git a/lib/simpletestlib/errors.php b/lib/simpletestlib/errors.php index 76745f88a8..1fdcdb1e9d 100644 --- a/lib/simpletestlib/errors.php +++ b/lib/simpletestlib/errors.php @@ -210,6 +210,10 @@ E_USER_ERROR => 'E_USER_ERROR', E_USER_WARNING => 'E_USER_WARNING', E_USER_NOTICE => 'E_USER_NOTICE'); + if (!isset($map[$severity])) { + debug_print_backtrace(); + die(); + } return $map[$severity]; } } @@ -239,4 +243,4 @@ set_error_handler('SimpleTestErrorHandler'); } } -?> \ No newline at end of file +?> diff --git a/question/backuplib.php b/question/backuplib.php index b24ec3776c..f09284c062 100644 --- a/question/backuplib.php +++ b/question/backuplib.php @@ -416,9 +416,9 @@ WHERE backup_code = ? AND table_name = 'question'", array($backup_unique_code)); } - + //Function for inserting question and category ids into db that are all called from - // quiz_check_backup_mods during execution of backup_check.html + // quiz_check_backup_mods during execution of backup_check.html function question_insert_c_and_q_ids_for_course($coursecontext, $backup_unique_code){ global $CFG, $DB; @@ -441,12 +441,12 @@ $status = $DB->execute("INSERT INTO {backup_ids} (backup_code, table_name, old_id, info) SELECT '$backup_unique_code', 'question', q.id, '' FROM {question} q, {backup_ids} bk - WHERE q.category = bk.old_id AND bk.table_name = 'question_categories' + WHERE q.category = bk.old_id AND bk.table_name = 'question_categories' AND bk.info = ? AND bk.backup_code = ?", array($info, $backup_unique_code)); return $status; } - + function question_insert_c_and_q_ids_for_module($backup_unique_code, $course, $modulename, $instances){ global $CFG, $DB; $status = true; @@ -454,18 +454,21 @@ // if two key names are the same. $cmcontexts = array(); if(!empty($instances)) { + list($usql, $params) = $DB->get_in_or_equal(array_keys($instances)); + $params[] = $modulename; + $params[] = $course; $cmcontexts = $DB->get_records_sql_menu("SELECT c.id, c.id AS dummykeyname FROM {modules} m, {course_modules} cm, {context} c - WHERE m.name = ? AND m.id = cm.module AND cm.id = c.instanceid - AND c.contextlevel = ".CONTEXT_MODULE." AND cm.course = ? - AND cm.instance IN (".implode(',',array_keys($instances)).")", array($modulename, $course)); + WHERE cm.instance $usql AND m.name = ? AND m.id = cm.module AND cm.id = c.instanceid + AND c.contextlevel = ".CONTEXT_MODULE." AND cm.course = ?", $params); } - + if ($cmcontexts){ + list($usql, $params) = $DB->get_in_or_equal(array_keys($cmcontexts)); $status = $status && $DB->execute("INSERT INTO {backup_ids} (backup_code, table_name, old_id, info) SELECT '$backup_unique_code', 'question_categories', qc.id, '$modulename' FROM {question_categories} qc - WHERE qc.contextid IN (".join(array_keys($cmcontexts), ', ').")"); + WHERE qc.contextid $usql", $params); } $status = $status && question_insert_q_ids($backup_unique_code, $modulename); return $status; diff --git a/question/category.php b/question/category.php index f2a0a0617d..ee75c34890 100644 --- a/question/category.php +++ b/question/category.php @@ -46,8 +46,8 @@ $param->moveupcontext, $param->movedowncontext, $param->tocontext); } } - if ($param->delete && ($questionstomove = count_records("question", "category", $param->delete))){ - if (!$category = get_record("question_categories", "id", $param->delete)) { // security + if ($param->delete && ($questionstomove = $DB->count_records("question", array("category" => $param->delete)))){ + if (!$category = $DB->get_record("question_categories", array("id" => $param->delete))) { // security print_error('nocate', 'question', $thispageurl->out(), $param->delete); } $categorycontext = get_context_instance_by_id($category->contextid); @@ -60,7 +60,7 @@ list($tocategoryid, $tocontextid) = explode(',', $formdata->category); $qcobject->move_questions_and_delete_category($formdata->delete, $tocategoryid); $thispageurl->remove_params('cat'); - $thispageurl->remove_params('category'); // TODO check in fix for bug 5353 + $thispageurl->remove_params('category'); // TODO check in fix for bug 5353 redirect($thispageurl->out()); } } else { diff --git a/question/category_class.php b/question/category_class.php index 9a91402857..26f1b631a6 100644 --- a/question/category_class.php +++ b/question/category_class.php @@ -15,28 +15,28 @@ require_once("$CFG->dirroot/question/category_form.php"); require_once('move_form.php'); class question_category_list extends moodle_list { - var $table = "question_categories"; - var $listitemclassname = 'question_category_list_item'; + public $table = "question_categories"; + public $listitemclassname = 'question_category_list_item'; /** * @var reference to list displayed below this one. */ - var $nextlist = null; + public $nextlist = null; /** * @var reference to list displayed above this one. */ - var $lastlist = null; + public $lastlist = null; - var $context = null; + public $context = null; - function question_category_list($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){ + public function question_category_list($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){ parent::moodle_list('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage); $this->context = $context; } - function get_records() { + public function get_records() { $this->records = get_categories_for_contexts($this->context->id, $this->sortby); } - function process_actions($left, $right, $moveup, $movedown, $moveupcontext, $movedowncontext, $tocontext){ + public function process_actions($left, $right, $moveup, $movedown, $moveupcontext, $movedowncontext, $tocontext){ global $CFG; //parent::procces_actions redirects after any action parent::process_actions($left, $right, $moveup, $movedown); @@ -59,7 +59,7 @@ class question_category_list extends moodle_list { class question_category_list_item extends list_item { - function set_icon_html($first, $last, &$lastitem){ + public function set_icon_html($first, $last, &$lastitem){ global $CFG; $category = $this->item; $this->icons['edit']= $this->image_icon(get_string('editthiscategory'), @@ -67,15 +67,21 @@ class question_category_list_item extends list_item { parent::set_icon_html($first, $last, $lastitem); $toplevel = ($this->parentlist->parentitem === null);//this is a top level item if (($this->parentlist->nextlist !== null) && $last && $toplevel && (count($this->parentlist->items)>1)){ - $this->icons['down'] = $this->image_icon(get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)), - $this->parentlist->pageurl->out_action(array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id)), 'down'); + $this->icons['down'] = $this->image_icon( + get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)), + $this->parentlist->pageurl->out_action( + array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id) + ), 'down'); } if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){ - $this->icons['up'] = $this->image_icon(get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)), - $this->parentlist->pageurl->out_action(array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id)), 'up'); + $this->icons['up'] = $this->image_icon( + get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)), + $this->parentlist->pageurl->out_action( + array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id) + ), 'up'); } } - function item_html($extraargs = array()){ + public function item_html($extraargs = array()){ global $CFG; $pixpath = $CFG->pixpath; $str = $extraargs['str']; @@ -135,7 +141,7 @@ class question_category_object { * * Gets necessary strings and sets relevant path information */ - function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) { + public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) { global $CFG, $COURSE; $this->tab = str_repeat(' ', $this->tabsize); @@ -174,7 +180,7 @@ class question_category_object { /** * Initializes this classes general category-related variables */ - function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) { + public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) { $lastlist = null; foreach ($contexts as $context){ $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context); @@ -199,7 +205,7 @@ class question_category_object { * Displays the user interface * */ - function display_user_interface() { + public function display_user_interface() { /// Interface for editing existing categories $this->output_edit_lists(); @@ -215,7 +221,7 @@ class question_category_object { /** * Outputs a table to allow entry of a new category */ - function output_new_table() { + public function output_new_table() { $this->catform->display(); } @@ -226,7 +232,7 @@ class question_category_object { * $this->initialize() must have already been called * */ - function output_edit_lists() { + public function output_edit_lists() { print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question'); foreach ($this->editlists as $context => $list){ $listhtml = $list->to_html(0, array('str'=>$this->str)); @@ -248,7 +254,7 @@ class question_category_object { * @param array categories contains category objects in a tree representation * @return array courseids flat array in form categoryid=>courseid */ - function get_course_ids($categories) { + public function get_course_ids($categories) { $courseids = array(); foreach ($categories as $key=>$cat) { $courseids[$key] = $cat->course; @@ -261,11 +267,11 @@ class question_category_object { - function edit_single_category($categoryid) { + public function edit_single_category($categoryid) { /// Interface for adding a new category - global $COURSE; + global $COURSE, $DB; /// Interface for editing existing categories - if ($category = get_record("question_categories", "id", $categoryid)) { + if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) { $category->parent = "$category->parent,$category->contextid"; $category->submitbutton = get_string('savechanges'); @@ -287,7 +293,7 @@ class question_category_object { * @param array parentstrings a list of parentstrings * @param object category */ - function set_viable_parents(&$parentstrings, $category) { + public function set_viable_parents(&$parentstrings, $category) { unset($parentstrings[$category->id]); if (isset($category->children)) { @@ -304,13 +310,13 @@ class question_category_object { * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}] * @return array categories */ - function get_question_categories($parent=null, $sort="sortorder ASC") { - global $COURSE; + public function get_question_categories($parent=null, $sort="sortorder ASC") { + global $COURSE, $DB; if (is_null($parent)) { - $categories = get_records('question_categories', 'course', "{$COURSE->id}", $sort); + $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort); } else { - $select = "parent = '$parent' AND course = '{$COURSE->id}'"; - $categories = get_records_select('question_categories', $select, $sort); + $select = "parent = ? AND course = ?"; + $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort); } return $categories; } @@ -320,30 +326,30 @@ class question_category_object { * * @param int deletecat id of category to delete */ - function delete_category($categoryid) { - global $CFG; + public function delete_category($categoryid) { + global $CFG, $DB; question_can_delete_cat($categoryid); - if (!$category = get_record("question_categories", "id", $categoryid)) { // security + if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security print_error('unknowcategory'); } /// Send the children categories to live with their grandparent - if (!set_field("question_categories", "parent", $category->parent, "parent", $category->id)) { + if (!$DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id))) { print_error('cannotupdatesubcate', 'question'); } /// Finally delete the category itself - if (delete_records("question_categories", "id", $category->id)) { + if ($DB->delete_records("question_categories", array("id" => $category->id))) { notify(get_string("categorydeleted", "quiz", format_string($category->name)), 'notifysuccess'); redirect($this->pageurl->out());//always redirect after successful action } } - function move_questions_and_delete_category($oldcat, $newcat){ + public function move_questions_and_delete_category($oldcat, $newcat){ question_can_delete_cat($oldcat); $this->move_questions($oldcat, $newcat); $this->delete_category($oldcat); } - function display_move_form($questionsincategory, $category){ + public function display_move_form($questionsincategory, $category){ $vars = new stdClass; $vars->name = $category->name; $vars->count = $questionsincategory; @@ -351,7 +357,7 @@ class question_category_object { $this->moveform->display(); } - function move_questions($oldcat, $newcat){ + public function move_questions($oldcat, $newcat){ global $DB; $questionids = $DB->get_records_select_menu('question', "category = ? AND (parent = 0 OR parent = id)", array($oldcat), '', 'id,1'); if (!question_move_questions_to_category(implode(',', array_keys($questionids)), $newcat)) { @@ -363,7 +369,8 @@ class question_category_object { * Creates a new category with given params * */ - function add_category($newparent, $newcategory, $newinfo) { + public function add_category($newparent, $newcategory, $newinfo) { + global $DB; if (empty($newcategory)) { print_error('categorynamecantbeblank', 'quiz'); } @@ -372,7 +379,7 @@ class question_category_object { require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid)); if ($parentid) { - if(!(get_field('question_categories', 'contextid', 'id', $parentid) == $contextid)) { + if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) { print_error('cannotinsertquestioncatecontext', 'question', '', array($newcategory, $contextid)); } } @@ -384,7 +391,7 @@ class question_category_object { $cat->info = $newinfo; $cat->sortorder = 999; $cat->stamp = make_unique_id_code(); - if (!insert_record("question_categories", $cat)) { + if (!$DB->insert_record("question_categories", $cat)) { print_error('cannotinsertquestioncate', 'question', '', $newcategory); } else { redirect($this->pageurl->out());//always redirect after successful action @@ -395,15 +402,15 @@ class question_category_object { * Updates an existing category with given params * */ - function update_category($updateid, $newparent, $newname, $newinfo) { - global $CFG, $QTYPES; + public function update_category($updateid, $newparent, $newname, $newinfo) { + global $CFG, $QTYPES, $DB; if (empty($newname)) { print_error('categorynamecantbeblank', 'quiz'); } list($parentid, $tocontextid) = explode(',', $newparent); - $oldcat = get_record('question_categories', 'id', $updateid); + $oldcat = $DB->get_record('question_categories', array('id' => $updateid)); $fromcontext = get_context_instance_by_id($oldcat->contextid); require_capability('moodle/question:managecategory', $fromcontext); if ($oldcat->contextid == $tocontextid){ @@ -415,24 +422,28 @@ class question_category_object { $cat->name = $newname; $cat->info = $newinfo; //never move category where it is the default - if (1 != count_records_sql("SELECT count(*) FROM {$CFG->prefix}question_categories c1, {$CFG->prefix}question_categories c2 WHERE c2.id = $updateid AND c1.contextid = c2.contextid")){ + if (1 != $DB->count_records_sql("SELECT count(*) + FROM {question_categories} c1, + {question_categories} c2 + WHERE c2.id = ? + AND c1.contextid = c2.contextid", array($updateid))){ // If the question name has changed, rename any random questions in that category. if (addslashes($oldcat->name) != $cat->name) { $randomqname = $QTYPES[RANDOM]->question_name($cat); - set_field('question', 'name', addslashes($randomqname), 'category', $cat->id, 'qtype', RANDOM); + $DB->set_field('question', 'name', $randomqname, array('category' => $cat->id), 'qtype', RANDOM); // Ignore errors here. It is not a big deal if the questions are not renamed. } // Then update the category itself. if ($oldcat->contextid == $tocontextid){ // not moving contexts $cat->parent = $parentid; - if (!update_record("question_categories", $cat)) { + if (!$DB->update_record("question_categories", $cat)) { print_error('cannotupdatecate', 'question', $this->pageurl->out(), $newname); } else { redirect($this->pageurl->out()); } } else { - if (!update_record("question_categories", $cat)) { + if (!$DB->update_record("question_categories", $cat)) { print_error('cannotupdatecate', 'question', $this->pageurl->out(), $newname); } else { redirect($CFG->wwwroot.'/question/contextmove.php?'. @@ -445,12 +456,12 @@ class question_category_object { } } - function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){ - global $QTYPES; + public function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){ + global $QTYPES, $DB; if (!$question){ $questions[] = $question; } else { - $questions = get_records('question', 'category', $tocat->id); + $questions = $DB->get_records('question', array('category' => $tocat->id)); } $urls = array(); foreach ($questions as $question){ diff --git a/question/category_form.php b/question/category_form.php index bb772bc40d..1dd2011f53 100644 --- a/question/category_form.php +++ b/question/category_form.php @@ -5,7 +5,7 @@ require_once($CFG->libdir.'/formslib.php'); class question_category_edit_form extends moodleform { function definition() { - global $CFG; + global $CFG, $DB; $mform =& $this->_form; $contexts = $this->_customdata['contexts']; @@ -16,7 +16,11 @@ class question_category_edit_form extends moodleform { $questioncategoryel = $mform->addElement('questioncategory', 'parent', get_string('parent', 'quiz'), array('contexts'=>$contexts, 'top'=>true, 'currentcat'=>$currentcat, 'nochildrenof'=>$currentcat)); $mform->setType('parent', PARAM_SEQUENCE); - if (1 == count_records_sql("SELECT count(*) FROM {$CFG->prefix}question_categories c1, {$CFG->prefix}question_categories c2 WHERE c2.id = $currentcat AND c1.contextid = c2.contextid")){ + if (1 == $DB->count_records_sql("SELECT count(*) + FROM {question_categories} c1, + {question_categories} c2 + WHERE c2.id = ? + AND c1.contextid = c2.contextid", array($currentcat))){ $mform->hardFreeze('parent'); } $mform->setHelpButton('parent', array('categoryparent', get_string('parent', 'quiz'), 'question')); diff --git a/question/contextmove.php b/question/contextmove.php index 4b6f165afb..8a0c2b2e52 100644 --- a/question/contextmove.php +++ b/question/contextmove.php @@ -25,7 +25,7 @@ $onerrorurl = $CFG->wwwroot.'/question/category.php?'.$thispageurl->get_query_string(); list($toparent, $contextto) = explode(',', $toparent); if (!empty($toparent)){//not top level category, make it a child of $toparent - if (!$toparent = get_record('question_categories', 'id', $toparent)){ + if (!$toparent = $DB->get_record('question_categories', array('id' => $toparent))){ print_error('invalidcategoryidforparent', 'question', $onerrorurl); } $contextto = $toparent->contextid; @@ -34,7 +34,7 @@ $toparent->id = 0; $toparent->contextid = $contextto; } - if (!$cattomove = get_record('question_categories', 'id', $cattomove)){ + if (!$cattomove = $DB->get_record('question_categories', array('id' => $cattomove))){ print_error('invalidcategoryidtomove', 'question', $onerrorurl); } if ($cattomove->contextid == $contextto){ @@ -57,7 +57,8 @@ $fromcoursefilesid = get_filesdir_from_context($contextfrom);//siteid or courseid $tocoursefilesid = get_filesdir_from_context($contextto);//siteid or courseid if ($fromcoursefilesid != $tocoursefilesid){ - $questions = get_records_select('question', "category IN ({$cattomove->categorylist})"); + list($usql, $params) = $DB->get_in_or_equal(explode(',', $cattomove->categorylist)); + $questions = $DB->get_records_select('question', "category $usql", $params); $urls = array(); if ($questions){ foreach ($questions as $id => $question){ @@ -154,7 +155,7 @@ } //adjust sortorder before we make the cat a peer of it's new peers - $peers = $DB->get_records_select_menu('question_categories', "contextid = ? AND parent = ?", array($toparent->contextid, $toparent->id), + $peers = $DB->get_records_select_menu('question_categories', "contextid = ? AND parent = ?", array($toparent->contextid, $toparent->id), "sortorder ASC", "id, id"); $peers = array_keys($peers); if ($totop){ @@ -164,7 +165,7 @@ } $sortorder = 0; foreach ($peers as $peer) { - if (! set_field('question_categories', "sortorder", $sortorder, "id", $peer)) { + if (! $DB->set_field('question_categories', "sortorder", $sortorder, array("id" => $peer))) { print_error('listupdatefail', '', $onerrorurl); } $sortorder++; @@ -174,11 +175,14 @@ $cat->id = $cattomove->id; $cat->parent = $toparent->id; //set context of category we are moving and all children also! - if (!execute_sql("UPDATE {$CFG->prefix}question_categories SET contextid = {$contextto->id} WHERE id IN ({$cattomove->categorylist})", false)){ + list($usql, $params) = $DB->get_in_or_equal(explode(',', $cattomove->categorylist)); + $params = array_merge(array($contextto->id), $params); + + if (!$DB->execute("UPDATE {question_categories} SET contextid = ? WHERE id $usql", $params)){ print_error('cannotmovefromto', 'question', $onerrorurl, array($newname, $contexttostring)); } //finally set the new parent id - if (!update_record("question_categories", $cat)) { + if (!$DB->update_record("question_categories", $cat)) { print_error('cannotupdatecate', 'question', $onerrorurl, $updatename); } $thispageurl->remove_params('cattomove', 'toparent', 'totop'); diff --git a/question/contextmoveq.php b/question/contextmoveq.php index 140f8590a5..ae2c01af34 100644 --- a/question/contextmoveq.php +++ b/question/contextmoveq.php @@ -46,11 +46,12 @@ if ($cmid){ } $contexts = new question_edit_contexts($thiscontext); +list($usql, $params) = $DB->get_in_or_equal(explode(',', $ids)); -if (!$questions = get_records_sql("SELECT q.*, c.contextid FROM {$CFG->prefix}question q, {$CFG->prefix}question_categories c WHERE q.id IN ($ids) AND c.id = q.category")) { +if (!$questions = $DB->get_records_sql("SELECT q.*, c.contextid FROM {question} q, {question_categories} c WHERE q.id $usql AND c.id = q.category", $params)) { print_error('questiondoesnotexist', 'question', $returnurl); } -if (!$tocat = get_record('question_categories', 'id', $tocatid)){ +if (!$tocat = $DB->get_record('question_categories', array('id' => $tocatid))){ print_error('categorydoesnotexist', 'question', $returnurl); } $tocat->context = get_context_instance_by_id($tocat->contextid); diff --git a/question/editlib.php b/question/editlib.php index 05c8d7a6da..51081c03d2 100644 --- a/question/editlib.php +++ b/question/editlib.php @@ -15,14 +15,14 @@ require_once($CFG->libdir.'/questionlib.php'); define('DEFAULT_QUESTIONS_PER_PAGE', 20); function get_module_from_cmid($cmid){ - global $CFG; - if (!$cmrec = get_record_sql("SELECT cm.*, md.name as modname - FROM {$CFG->prefix}course_modules cm, - {$CFG->prefix}modules md - WHERE cm.id = '$cmid' AND - md.id = cm.module")){ + global $CFG, $DB; + if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname + FROM {course_modules} cm, + {modules} md + WHERE cm.id = ? AND + md.id = cm.module", array($cmid))){ print_error('cmunknown'); - } elseif (!$modrec =get_record($cmrec->modname, 'id', $cmrec->instance)) { + } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) { print_error('cmunknown'); } $modrec->instance = $modrec->id; @@ -42,7 +42,7 @@ function get_module_from_cmid($cmid){ */ function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) { - global $QTYPES; + global $QTYPES, $DB; // questions will be added to an array $qresults = array(); @@ -62,7 +62,8 @@ function get_questions_category( $category, $noparent=false, $recurse=true, $exp } // get the list of questions for the category - if ($questions = get_records_select("question","category IN ($categorylist) $npsql", "qtype, name ASC")) { + list ($usql, $params) = $DB->get_in_or_equal(explode(',', $categorylist)); + if ($questions = $DB->get_records_select("question","category $usql $npsql", $params, "qtype, name ASC")) { // iterate through questions, getting stuff we need foreach($questions as $question) { @@ -78,10 +79,10 @@ function get_questions_category( $category, $noparent=false, $recurse=true, $exp function question_can_delete_cat($todelete){ - global $CFG; - $record = get_record_sql("SELECT count(*) as count, c1.contextid as contextid FROM {$CFG->prefix}question_categories c1, - {$CFG->prefix}question_categories c2 WHERE c2.id = $todelete - AND c1.contextid = c2.contextid GROUP BY c1.contextid"); + global $CFG, $DB; + $record = $DB->get_record_sql("SELECT count(*) as count, c1.contextid as contextid FROM {question_categories} c1, + {question_categories} c2 WHERE c2.id = ? + AND c1.contextid = c2.contextid GROUP BY c1.contextid", array($todelete)); $contextid = $record->contextid; $count = $record->count; if ($count < 2) { @@ -146,7 +147,7 @@ function question_category_form_checkbox($name, $checked) { function question_list($contexts, $pageurl, $categoryandcontext, $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false, $sortorder='typename', $sortorderdecoded='qtype, name ASC', $showquestiontext = false, $addcontexts = array()) { - global $USER, $CFG, $THEME, $COURSE; + global $USER, $CFG, $THEME, $COURSE, $DB; list($categoryid, $contextid)= explode(',', $categoryandcontext); @@ -181,7 +182,7 @@ function question_list($contexts, $pageurl, $categoryandcontext, $cm = null, return; } - if (!$category = get_record('question_categories', 'id', $categoryid, 'contextid', $contextid)) { + if (!$category = $DB->get_record('question_categories', array('id' => $categoryid, 'contextid' => $contextid))) { notify('Category not found!'); return; } @@ -239,18 +240,19 @@ function question_list($contexts, $pageurl, $categoryandcontext, $cm = null, // hide-feature $showhidden = $showhidden ? '' : " AND hidden = '0'"; - - if (!$totalnumber = count_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden")) { + $categorylist_array = explode(',', $categorylist); + list($usql, $params) = $DB->get_in_or_equal($categorylist_array); + if (!$totalnumber = $DB->count_records_select('question', "category $usql AND parent = '0' $showhidden", $params)) { echo "

"; print_string("noquestions", "quiz"); echo "

"; return; } - if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', $page*$perpage, $perpage)) { + if (!$questions = $DB->get_records_select('question', "category $usql AND parent = '0' $showhidden", $params, $sortorderdecoded, '*', $page*$perpage, $perpage)) { // There are no questions on the requested page. $page = 0; - if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', 0, $perpage)) { + if (!$questions = $DB->get_records_select('question', "category $usql AND parent = '0' $showhidden", $params, $sortorderdecoded, '*', 0, $perpage)) { // There are no questions at all echo "

"; print_string("noquestions", "quiz"); @@ -412,12 +414,12 @@ function question_sort_options($pageurl, $sortorder){ } function question_showbank_actions($pageurl, $cm){ - global $CFG, $COURSE; + global $CFG, $COURSE, $DB; /// Now, check for commands on this page and modify variables as necessary if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) { /// Move selected questions to new category $category = required_param('category', PARAM_SEQUENCE); list($tocategoryid, $contextid) = explode(',', $category); - if (! $tocategory = get_record('question_categories', 'id', $tocategoryid, 'contextid', $contextid)) { + if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) { error('Could not find category record'); } $tocontext = get_context_instance_by_id($contextid); @@ -431,9 +433,9 @@ function question_showbank_actions($pageurl, $cm){ } } if ($questionids){ - $questionidlist = join($questionids, ','); - $sql = "SELECT q.*, c.contextid FROM {$CFG->prefix}question q, {$CFG->prefix}question_categories c WHERE q.id IN ($questionidlist) AND c.id = q.category"; - if (!$questions = get_records_sql($sql)){ + list($usql, $params) = $DB->get_in_or_equal($questionids); + $sql = "SELECT q.*, c.contextid FROM {question} q, {question_categories} c WHERE q.id $usql AND c.id = q.category"; + if (!$questions = $DB->get_records_sql($sql, $params)){ print_error('questiondoesnotexist', 'question', $pageurl->out()); } $checkforfiles = false; @@ -474,8 +476,8 @@ function question_showbank_actions($pageurl, $cm){ // for each question either hide it if it is in use or delete it foreach ($questionlist as $questionid) { question_require_capability_on($questionid, 'edit'); - if (record_exists('quiz_question_instances', 'question', $questionid)) { - if (!set_field('question', 'hidden', 1, 'id', $questionid)) { + if ($DB->record_exists('quiz_question_instances', array('question' => $questionid))) { + if (!$DB->set_field('question', 'hidden', 1, array('id', $questionid))) { question_require_capability_on($questionid, 'edit'); error('Was not able to hide question'); } @@ -494,7 +496,7 @@ function question_showbank_actions($pageurl, $cm){ // Unhide a question if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) { question_require_capability_on($unhide, 'edit'); - if(!set_field('question', 'hidden', 0, 'id', $unhide)) { + if(!$DB->set_field('question', 'hidden', 0, array('id', $unhide))) { error("Failed to unhide the question."); } redirect($pageurl->out()); @@ -519,7 +521,7 @@ function question_showbank_actions($pageurl, $cm){ * @param moodle_url $pageurl object representing this pages url. */ function question_showbank($tabname, $contexts, $pageurl, $cm, $page, $perpage, $sortorder, $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){ - global $COURSE; + global $COURSE, $DB; if (optional_param('deleteselected', false, PARAM_BOOL)){ // teacher still has to confirm // make a list of all the questions that are selected @@ -533,11 +535,11 @@ function question_showbank($tabname, $contexts, $pageurl, $cm, $page, $perpage, $key = $matches[1]; $questionlist .= $key.','; question_require_capability_on($key, 'edit'); - if (record_exists('quiz_question_instances', 'question', $key)) { + if ($DB->record_exists('quiz_question_instances', array('question' => $key))) { $questionnames .= '* '; $inuse = true; } - $questionnames .= get_field('question', 'name', 'id', $key).'
'; + $questionnames .= $DB->get_field('question', 'name', array('id' => $key)).'
'; } } if (!$questionlist) { // no questions were selected @@ -580,7 +582,7 @@ function question_showbank($tabname, $contexts, $pageurl, $cm, $page, $perpage, * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars */ function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = true){ - global $COURSE, $QUESTION_EDITTABCAPS; + global $COURSE, $QUESTION_EDITTABCAPS, $DB; //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array //of parameters that are passed from page to page. @@ -673,7 +675,8 @@ function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = $contextlist = join($contextlistarr, ' ,'); if (!empty($pagevars['cat'])){ $catparts = explode(',', $pagevars['cat']); - if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) || !count_records_select("question_categories", "id = '".$catparts[0]."' AND contextid = $catparts[1]")) { + if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) || + !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) { print_error('invalidcategory', 'quiz'); } } else { @@ -870,6 +873,7 @@ $QUESTION_EDITTABCAPS = array( * Make sure user is logged in as required in this context. */ function require_login_in_context($contextorid = null){ + global $DB; if (!is_object($contextorid)){ $context = get_context_instance_by_id($contextorid); } else { @@ -878,8 +882,8 @@ function require_login_in_context($contextorid = null){ if ($context && ($context->contextlevel == CONTEXT_COURSE)) { require_login($context->instanceid); } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) { - if ($cm = get_record('course_modules','id',$context->instanceid)) { - if (!$course = get_record('course', 'id', $cm->course)) { + if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) { + if (!$course = $DB->get_record('course', array('id' => $cm->course))) { print_error('invalidcourseid'); } require_course_login($course, true, $cm); diff --git a/question/export.php b/question/export.php index d96ff93f7a..5ebf3a3dc9 100644 --- a/question/export.php +++ b/question/export.php @@ -40,7 +40,7 @@ // ensure the files area exists for this course make_upload_directory("$COURSE->id"); list($catid, $catcontext) = explode(',', $pagevars['cat']); - if (!$category = get_record("question_categories", "id", $catid, 'contextid', $catcontext)) { + if (!$category = $DB->get_record("question_categories", array("id" => $catid, 'contextid' => $catcontext))) { print_error('nocategory','quiz'); } diff --git a/question/file.php b/question/file.php index 164a4b3a2e..3fa8b05418 100644 --- a/question/file.php +++ b/question/file.php @@ -47,7 +47,7 @@ // security: check that the user has permission to access this file $haspermission = false; - if ($attempt = get_record("question_attempts", "id", $args[0])) { + if ($attempt = $DB->get_record("question_attempts", array("id" => $args[0]))) { $modfile = $CFG->dirroot .'/mod/'. $attempt->modulename .'/lib.php'; $modcheckfileaccess = $attempt->modulename .'_check_file_access'; if (file_exists($modfile)) { diff --git a/question/format.php b/question/format.php index 32dabeccb0..1553521081 100644 --- a/question/format.php +++ b/question/format.php @@ -197,7 +197,7 @@ class qformat_default { * @return boolean success */ function importprocess() { - global $USER; + global $USER, $DB; // reset the timer in case file upload was slow @set_time_limit(); @@ -293,7 +293,7 @@ class qformat_default { $question->createdby = $USER->id; $question->timecreated = time(); - if (!$question->id = insert_record("question", $question)) { + if (!$question->id = $DB->insert_record("question", $question)) { print_error('cannotinsert','quiz'); } @@ -316,16 +316,16 @@ class qformat_default { } // Give the question a unique version stamp determined by question_hash() - set_field('question', 'version', question_hash($question), 'id', $question->id); + $DB->set_field('question', 'version', question_hash($question), array('id', $question->id)); } return true; } /** * Count all non-category questions in the questions array. - * + * * @param array questions An array of question objects. * @return int The count. - * + * */ function count_questions($questions) { $count = 0; @@ -354,6 +354,7 @@ class qformat_default { * @return mixed category object or null if fails */ function create_category_path($catpath, $delimiter='/') { + global $DB; $catpath = clean_param($catpath, PARAM_PATH); $catnames = explode($delimiter, $catpath); $parent = 0; @@ -371,7 +372,7 @@ class qformat_default { $context = get_context_instance_by_id($this->category->contextid); } foreach ($catnames as $catname) { - if ($category = get_record( 'question_categories', 'name', $catname, 'contextid', $context->id, 'parent', $parent)) { + if ($category = $DB->get_record( 'question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) { $parent = $category->id; } else { require_capability('moodle/question:managecategory', $context); @@ -383,7 +384,7 @@ class qformat_default { $category->parent = $parent; $category->sortorder = 999; $category->stamp = make_unique_id_code(); - if (!($id = insert_record('question_categories', $category))) { + if (!($id = $DB->insert_record('question_categories', $category))) { print_error( "cannot create new category - $catname" ); } $category->id = $id; @@ -714,8 +715,9 @@ class qformat_default { * @return string the path */ function get_category_path($id, $delimiter='/', $includecontext = true) { + global $DB; $path = ''; - if (!$firstcategory = get_record('question_categories','id',$id)) { + if (!$firstcategory = $DB->get_record('question_categories',array('id' =>$id))) { print_error('cannotfindcategory', 'error', '', $id); } $category = $firstcategory; @@ -729,7 +731,7 @@ class qformat_default { else { $path = $name; } - } while ($category = get_record( 'question_categories','id',$id )); + } while ($category = $DB->get_record( 'question_categories',array('id' =>$id ))); if ($includecontext){ $path = '$'.$contextstring.'$'."{$delimiter}{$path}"; diff --git a/question/format/coursetestmanager/format.php b/question/format/coursetestmanager/format.php index 14a0923b5d..0f8cb172bd 100755 --- a/question/format/coursetestmanager/format.php +++ b/question/format/coursetestmanager/format.php @@ -25,8 +25,7 @@ class qformat_coursetestmanager extends qformat_default { } function importprocess($filename) { - global $CFG, $USER, $strimportquestions,$form,$question_category,$category,$COURSE, - $hostname, $mdapath, $mdbpath; + global $CFG, $USER, $strimportquestions,$form,$question_category,$category,$COURSE, $DB, $hostname, $mdapath, $mdbpath; if ((PHP_OS == "Linux") and isset($hostname)) { $hostname = trim($hostname); // test the ODBC socket server connection @@ -204,8 +203,8 @@ class qformat_coursetestmanager extends qformat_default { $question->feedback[$i-3] = (($qrec[8] == $i-3)?"Correct. ":"Incorrect. ") . $ref; } } - if ($fractionset == 0) { - $question->fraction[1] = 1; + if ($fractionset == 0) { + $question->fraction[1] = 1; } break; case 2: // TRUE FALSE @@ -213,10 +212,10 @@ class qformat_coursetestmanager extends qformat_default { $question->questiontext = addslashes(trim($qrec[2])); $question->name = preg_replace("/
/", "", $question->questiontext); // for TF, $question->answer should be 1 for true, 0 for false - if ($qrec[8] == "T") { + if ($qrec[8] == "T") { $question->answer =1; - } else { - $question->answer = 0; + } else { + $question->answer = 0; } // for TF, use $question->feedbacktrue and feedbackfalse $question->feedbacktrue = (($qrec[8] =="T")?"Correct. ":"Incorrect. ") . $ref; @@ -246,8 +245,8 @@ class qformat_coursetestmanager extends qformat_default { notify("Misformatted Record. Question Skipped."); break; } - if ($question) { - $questions[] = $question; + if ($question) { + $questions[] = $question; } } $count = 0; @@ -263,7 +262,7 @@ class qformat_coursetestmanager extends qformat_default { $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed) $question->createdby = $USER->id; $question->timecreated = time(); - if (!$question->id = insert_record("question", $question)) { + if (!$question->id = $DB->insert_record("question", $question)) { print_error('cannotinsertquestion', 'question'); } $this->questionids[] = $question->id; @@ -280,7 +279,7 @@ class qformat_coursetestmanager extends qformat_default { return true; } // Give the question a unique version stamp determined by question_hash() - set_field('question', 'version', question_hash($question), 'id', $question->id); + $DB->set_field('question', 'version', question_hash($question), array('id', $question->id)); } $this->deletedatabase($filename); return true; @@ -475,15 +474,15 @@ class qformat_coursetestmanager extends qformat_default { } function getcoursedirs() { - global $CFG; + global $CFG, $DB; // for every course in the system, find the root of the data directory - $courses = get_records_sql("select distinct id,fullname from ".$CFG->prefix."course"); + $courses = $DB->get_records_sql("select distinct id,fullname from {course}"); $dirs = array(); if ($courses) { foreach ($courses as $course) { $dir = $CFG->dataroot . "/" . $course->id; - if (is_dir($dir)) { - $dirs[] = $dir; + if (is_dir($dir)) { + $dirs[] = $dir; } } } @@ -528,7 +527,7 @@ class qformat_coursetestmanager extends qformat_default { //handler for character data function quiz_xmldata($parser, $data) { global $result, $row, $col, $incolumn; - if ($incolumn) { + if ($incolumn) { $result[$row][$col] = $result[$row][$col] . $data; } } diff --git a/question/format/examview/format.php b/question/format/examview/format.php index 32bf0e5733..99df6087ca 100755 --- a/question/format/examview/format.php +++ b/question/format/examview/format.php @@ -9,8 +9,8 @@ require_once("$CFG->libdir/xmlize.php"); class qformat_examview extends qformat_default { - - var $qtypes = array( + + public $qtypes = array( 'tf' => TRUEFALSE, 'mc' => MULTICHOICE, 'yn' => TRUEFALSE, @@ -24,13 +24,13 @@ class qformat_examview extends qformat_default { 'ot' => 99, 'sa' => ESSAY ); - - var $matching_questions = array(); + + public $matching_questions = array(); function provide_import() { return true; } - + /** * unxmlise reconstructs part of the xml data structure in order * to identify the actual data therein @@ -47,7 +47,7 @@ class qformat_examview extends qformat_default { $text = ''; foreach ($xml as $tag=>$data) { // if tag is '@' then it's attributes and we don't care - if ($tag!=='@') { + if ($tag!=='@') { $text = $text . $this->unxmlise( $data ); } } @@ -57,7 +57,7 @@ class qformat_examview extends qformat_default { $text = strip_tags($text); return $text; } - + function parse_matching_groups($matching_groups) { if (empty($matching_groups)) { @@ -81,7 +81,7 @@ class qformat_examview extends qformat_default { $this->matching_questions[$groupname] = $newgroup; } } - + function parse_ma($qrec, $groupname) { $match_group = $this->matching_questions[$groupname]; @@ -93,7 +93,7 @@ class qformat_examview extends qformat_default { $this->matching_questions[$groupname] = $match_group; return NULL; } - + function process_matches(&$questions) { if (empty($this->matching_questions)) { @@ -117,7 +117,7 @@ class qformat_examview extends qformat_default { $questions[] = $question; } } - + function cleanUnicode($text) { return str_replace('’', "'", $text); } @@ -129,7 +129,7 @@ class qformat_examview extends qformat_default { $questions = array(); $currentquestion = array(); - + $text = implode($lines, ' '); $text = $this->cleanUnicode($text); @@ -137,22 +137,22 @@ class qformat_examview extends qformat_default { if (!empty($xml['examview']['#']['matching-group'])) { $this->parse_matching_groups($xml['examview']['#']['matching-group']); } - + $questionNode = $xml['examview']['#']['question']; foreach($questionNode as $currentquestion) { if ($question = $this->readquestion($currentquestion)) { $questions[] = $question; } } - + $this->process_matches($questions); return $questions; } // end readquestions - + function readquestion($qrec) { - + $type = trim($qrec['@']['type']); $question = $this->defaultquestion(); if (array_key_exists($type, $this->qtypes)) { @@ -166,7 +166,7 @@ class qformat_examview extends qformat_default { $htmltext = $this->unxmlise($qrec['#']['text'][0]['#']); $question->questiontext = $htmltext; $question->name = shorten_text( $question->questiontext, 250 ); - + switch ($question->qtype) { case MULTICHOICE: $question = $this->parse_mc($qrec['#'], $question); @@ -193,11 +193,11 @@ class qformat_examview extends qformat_default { $question = NULL; } // end switch ($question->qtype) - + return $question; } // end readquestion - + function parse_tf_yn($qrec, $question) { $choices = array('T' => 1, 'Y' => 1, 'F' => 0, 'N' => 0 ); @@ -213,15 +213,15 @@ class qformat_examview extends qformat_default { } return $question; } - + function parse_mc($qrec, $question) { $answer = 'choice-'.strtolower(trim($qrec['answer'][0]['#'])); - + $choices = $qrec['choices'][0]['#']; foreach($choices as $key => $value) { if (strpos(trim($key),'choice-') !== FALSE) { - + $question->answer[$key] = s($this->unxmlise($value[0]['#'])); if (strcmp($key, $answer) == 0) { $question->fraction[$key] = 1; @@ -234,14 +234,14 @@ class qformat_examview extends qformat_default { } return $question; } - + function parse_co($qrec, $question) { $question->usecase = 0; $answer = trim($this->unxmlise($qrec['answer'][0]['#'])); $answer = strip_tags( $answer ); $answers = explode("\n",$answer); - + foreach($answers as $key => $value) { $value = trim($value); if (strlen($value) > 0) { @@ -259,13 +259,13 @@ class qformat_examview extends qformat_default { $question->fraction = 0; return $question; } - + function parse_nr($qrec, $question) { $answer = trim($this->unxmlise($qrec['answer'][0]['#'])); $answer = strip_tags( $answer ); $answers = explode("\n",$answer); - + foreach($answers as $key => $value) { $value = trim($value); if (is_numeric($value)) { @@ -278,8 +278,8 @@ class qformat_examview extends qformat_default { } } return $question; - } - + } + } // end class diff --git a/question/format/qti2/format.php b/question/format/qti2/format.php index cfca410330..7e3660ae0b 100644 --- a/question/format/qti2/format.php +++ b/question/format/qti2/format.php @@ -15,127 +15,127 @@ require_once("$CFG->dirroot/question/format/qti2/qt_common.php"); define('CLOZE_TRAILING_TEXT_ID', 9999999); class qformat_qti2 extends qformat_default { - + var $lang; function provide_export() { return true; } - - function indent_xhtml($source, $indenter = ' ') { + + function indent_xhtml($source, $indenter = ' ') { // xml tidier-upper // (c) Ari Koivula http://ventionline.com - - // Remove all pre-existing formatting. - // Remove all newlines. - $source = str_replace("\n", '', $source); - $source = str_replace("\r", '', $source); - // Remove all tabs. - $source = str_replace("\t", '', $source); - // Remove all space after ">" and before "<". - $source = ereg_replace(">( )*", ">", $source); - $source = ereg_replace("( )*<", "<", $source); - - // Iterate through the source. - $level = 0; - $source_len = strlen($source); - $pt = 0; - while ($pt < $source_len) { - if ($source{$pt} === '<') { - // We have entered a tag. - // Remember the point where the tag starts. - $started_at = $pt; - $tag_level = 1; - // If the second letter of the tag is "/", assume its an ending tag. - if ($source{$pt+1} === '/') { - $tag_level = -1; - } - // If the second letter of the tag is "!", assume its an "invisible" tag. - if ($source{$pt+1} === '!') { - $tag_level = 0; - } - // Iterate throught the source until the end of tag. - while ($source{$pt} !== '>') { - $pt++; - } - // If the second last letter is "/", assume its a self ending tag. - if ($source{$pt-1} === '/') { - $tag_level = 0; - } - $tag_lenght = $pt+1-$started_at; - - // Decide the level of indention for this tag. - // If this was an ending tag, decrease indent level for this tag.. - if ($tag_level === -1) { - $level--; - } - // Place the tag in an array with proper indention. - $array[] = str_repeat($indenter, $level).substr($source, $started_at, $tag_lenght); - // If this was a starting tag, increase the indent level after this tag. - if ($tag_level === 1) { - $level++; - } - // if it was a self closing tag, dont do shit. - } - // Were out of the tag. - // If next letter exists... - if (($pt+1) < $source_len) { - // ... and its not an "<". - if ($source{$pt+1} !== '<') { - $started_at = $pt+1; - // Iterate through the source until the start of new tag or until we reach the end of file. - while ($source{$pt} !== '<' && $pt < $source_len) { - $pt++; - } - // If we found a "<" (we didnt find the end of file) - if ($source{$pt} === '<') { - $tag_lenght = $pt-$started_at; - // Place the stuff in an array with proper indention. - $array[] = str_repeat($indenter, $level).substr($source, $started_at, $tag_lenght); - } - // If the next tag is "<", just advance pointer and let the tag indenter take care of it. - } else { - $pt++; - } - // If the next letter doesnt exist... Were done... well, almost.. - } else { - break; - } - } - // Replace old source with the new one we just collected into our array. - $source = implode($array, "\n"); - return $source; - } - + + // Remove all pre-existing formatting. + // Remove all newlines. + $source = str_replace("\n", '', $source); + $source = str_replace("\r", '', $source); + // Remove all tabs. + $source = str_replace("\t", '', $source); + // Remove all space after ">" and before "<". + $source = ereg_replace(">( )*", ">", $source); + $source = ereg_replace("( )*<", "<", $source); + + // Iterate through the source. + $level = 0; + $source_len = strlen($source); + $pt = 0; + while ($pt < $source_len) { + if ($source{$pt} === '<') { + // We have entered a tag. + // Remember the point where the tag starts. + $started_at = $pt; + $tag_level = 1; + // If the second letter of the tag is "/", assume its an ending tag. + if ($source{$pt+1} === '/') { + $tag_level = -1; + } + // If the second letter of the tag is "!", assume its an "invisible" tag. + if ($source{$pt+1} === '!') { + $tag_level = 0; + } + // Iterate throught the source until the end of tag. + while ($source{$pt} !== '>') { + $pt++; + } + // If the second last letter is "/", assume its a self ending tag. + if ($source{$pt-1} === '/') { + $tag_level = 0; + } + $tag_lenght = $pt+1-$started_at; + + // Decide the level of indention for this tag. + // If this was an ending tag, decrease indent level for this tag.. + if ($tag_level === -1) { + $level--; + } + // Place the tag in an array with proper indention. + $array[] = str_repeat($indenter, $level).substr($source, $started_at, $tag_lenght); + // If this was a starting tag, increase the indent level after this tag. + if ($tag_level === 1) { + $level++; + } + // if it was a self closing tag, dont do shit. + } + // Were out of the tag. + // If next letter exists... + if (($pt+1) < $source_len) { + // ... and its not an "<". + if ($source{$pt+1} !== '<') { + $started_at = $pt+1; + // Iterate through the source until the start of new tag or until we reach the end of file. + while ($source{$pt} !== '<' && $pt < $source_len) { + $pt++; + } + // If we found a "<" (we didnt find the end of file) + if ($source{$pt} === '<') { + $tag_lenght = $pt-$started_at; + // Place the stuff in an array with proper indention. + $array[] = str_repeat($indenter, $level).substr($source, $started_at, $tag_lenght); + } + // If the next tag is "<", just advance pointer and let the tag indenter take care of it. + } else { + $pt++; + } + // If the next letter doesnt exist... Were done... well, almost.. + } else { + break; + } + } + // Replace old source with the new one we just collected into our array. + $source = implode($array, "\n"); + return $source; + } + function importpreprocess() { global $CFG; - print_error('cannotimportformat', '', + print_error('cannotimportformat', '', "$CFG->wwwroot/mod/quiz/import.php?category=$category->id"); } function exportpreprocess() { global $CFG; - + require_once("{$CFG->libdir}/smarty/Smarty.class.php"); - + // assign the language for the export: by parameter, SESSION, USER, or the default of 'en' $lang = current_language(); $this->lang = $lang; - + return parent::exportpreprocess(); } - - + + function export_file_extension() { // override default type so extension is .xml - + return ".zip"; } - + function get_qtype( $type_id ) { // translates question type code number into actual name - + switch( $type_id ) { case TRUEFALSE: $name = 'truefalse'; @@ -165,15 +165,15 @@ class qformat_qti2 extends qformat_default { } function writetext( $raw ) { - // generates tags, processing raw text therein - - // for now, don't allow any additional tags in text + // generates tags, processing raw text therein + + // for now, don't allow any additional tags in text // otherwise xml rules would probably get broken $raw = strip_tags( $raw ); - + return "$raw\n"; } - + /** * flattens $object['media'], copies $object['media'] to $path, and sets $object['mediamimetype'] @@ -182,7 +182,7 @@ class qformat_qti2 extends qformat_default { * @param string $path the full path name to where the media files need to be copied * @param int $courseid * @return: mixed - true on success or in case of an empty media field, an error string if the file copy fails - */ + */ function copy_and_flatten(&$object, $path, $courseid) { global $CFG; if (!empty($object['media'])) { @@ -196,7 +196,7 @@ function copy_and_flatten(&$object, $path, $courseid) { } } return true; -} +} /** * copies all files needed by the questions to the given $path, and flattens the file names * @@ -204,12 +204,12 @@ function copy_and_flatten(&$object, $path, $courseid) { * @param string $path the full path name to where the media files need to be copied * @param int $courseid * @return mixed true on success, an array of error messages otherwise - */ + */ function handle_questions_media(&$questions, $path, $courseid) { global $CFG; $errors = array(); foreach ($questions as $key=>$question) { - + // todo: handle in-line media (specified in the question text) if (!empty($question->image)) { $location = $questions[$key]->image; @@ -222,7 +222,7 @@ function handle_questions_media(&$questions, $path, $courseid) { } } } - + return empty($errors) ? true : $errors; } @@ -233,7 +233,7 @@ function handle_questions_media(&$questions, $path, $courseid) { * * @param string $filename the directory name which will hold the exported files * @return boolean - or errors out - */ + */ function exportprocess() { global $CFG; @@ -246,22 +246,22 @@ function handle_questions_media(&$questions, $path, $courseid) { $path = $CFG->dataroot.'/'.$this->question_get_export_dir().'/'.$this->filename; // get the questions (from database) in this category - // $questions = get_records("question","category",$this->category->id); + // $questions = $DB->get_records("question",array("category" => $this->category->id); $questions = get_questions_category( $this->category ); - + notify("Exporting ".count($questions)." questions."); $count = 0; // create the imsmanifest file $smarty =& $this->init_smarty(); $this->add_qti_info($questions); - + // copy files used by the main questions to the export directory $result = $this->handle_questions_media($questions, $path, $courseid); if ($result !== true) { notify(implode("
", $result)); } - + $manifestquestions = $this->objects_to_array($questions); $manifestid = str_replace(array(':', '/'), array('-','_'), "question_category_{$this->category->id}---{$CFG->wwwroot}"); $smarty->assign('externalfiles', 1); @@ -286,13 +286,13 @@ function handle_questions_media(&$questions, $path, $courseid) { // iterate through questions foreach($questions as $question) { - + // results are first written into string (and then to a file) $count++; echo "


$count. ".stripslashes($question->questiontext)."

"; $expout = $this->writequestion( $question , null, true, $path) . "\n"; $expout = $this->presave_process( $expout ); - + $filepath = $path.'/'.$this->get_assesment_item_id($question) . ".xml"; if (!$fh=fopen($filepath,"w")) { print_error('cannotopenforwrit', '', '', $filepath); @@ -301,7 +301,7 @@ function handle_questions_media(&$questions, $path, $courseid) { print_error('cannotwriteto', 'question', '', $filepath); } fclose($fh); - + } // zip files into single export file @@ -309,10 +309,10 @@ function handle_questions_media(&$questions, $path, $courseid) { // remove the temporary directory remove_dir( $path ); - + return true; } - + /** * exports a quiz (as opposed to exporting a category of questions) * @@ -324,7 +324,7 @@ function handle_questions_media(&$questions, $path, $courseid) { * @param string $redirect - a URL to redirect to in case of failure * @param string $submiturl - the URL for the qti player to send the results to (e.g. attempt.php) * @todo use $result in the ouput - */ + */ function export_quiz($course, $quiz, $questions, $result, $redirect, $submiturl = null) { $this->xml_entitize($course); $this->xml_entitize($quiz); @@ -342,7 +342,7 @@ function handle_questions_media(&$questions, $path, $courseid) { } } - + /** * This function is called to export a quiz (as opposed to exporting a category of questions) @@ -352,7 +352,7 @@ function handle_questions_media(&$questions, $path, $courseid) { * @param array $questions - an array of question objects * @param object $result - if set, contains result of calling quiz_grade_responses() * @todo use $result in the ouput - */ + */ function exportprocess_quiz($quiz, $questions, $result, $submiturl, $course) { global $USER; global $CFG; @@ -366,12 +366,12 @@ function handle_questions_media(&$questions, $path, $courseid) { $smarty =& $this->init_smarty(); $smarty->assign('questions', $questions); - + // quiz level smarty variables $manifestid = str_replace(array(':', '/'), array('-','_'), "quiz{$quiz->id}-{$CFG->wwwroot}"); $smarty->assign('manifestidentifier', $manifestid); $smarty->assign('submiturl', $submiturl); - $smarty->assign('userid', $USER->id); + $smarty->assign('userid', $USER->id); $smarty->assign('username', htmlspecialchars($USER->username, ENT_COMPAT, 'UTF-8')); $smarty->assign('quiz_level_export', 1); $smarty->assign('quiztitle', format_string($quiz->name,true)); //assigned specifically so as not to cause problems with category-level export @@ -386,8 +386,8 @@ function handle_questions_media(&$questions, $path, $courseid) { return true; } - - + + /** * Prepares questions for quiz export @@ -401,7 +401,7 @@ function handle_questions_media(&$questions, $path, $courseid) { * @param array $questions - an array of question objects * @param int $quizid * @return an array of question arrays - */ + */ function quiz_export_prepare_questions($questions, $quizid, $courseid, $shuffleanswers = null) { global $CFG; // add the answers to the questions and format the image property @@ -409,13 +409,13 @@ function handle_questions_media(&$questions, $path, $courseid) { $questions[$key] = get_question_data($question); $questions[$key]->courseid = $courseid; $questions[$key]->quizid = $quizid; - + if ($question->image) { - + if (empty($question->mediamimetype)) { - $questions[$key]->mediamimetype = mimeinfo('type',$question->image); + $questions[$key]->mediamimetype = mimeinfo('type',$question->image); } - + $localfile = (substr(strtolower($question->image), 0, 7) == 'http://') ? false : true; if ($localfile) { @@ -424,7 +424,7 @@ function handle_questions_media(&$questions, $path, $courseid) { $questions[$key]->mediaurl = "$CFG->wwwroot/file.php/$question->image"; } else { $questions[$key]->mediaurl = "$CFG->wwwroot/file.php?file=$question->image"; - } + } } else { $questions[$key]->mediaurl = $question->image; } @@ -439,11 +439,11 @@ function handle_questions_media(&$questions, $path, $courseid) { /** * calls htmlspecialchars for each string field, to convert, for example, & to & - * + * * collections are processed recursively * * @param array $collection - an array or object or string - */ + */ function xml_entitize(&$collection) { if (is_array($collection)) { foreach ($collection as $key=>$var) { @@ -451,7 +451,7 @@ function xml_entitize(&$collection) { $collection[$key]= htmlspecialchars($var, ENT_COMPAT, 'UTF-8'); } else if (is_array($var) || is_object($var)) { $this->xml_entitize($collection[$key]); - } + } } } else if (is_object($collection)) { $vars = get_object_vars($collection); @@ -460,13 +460,13 @@ function xml_entitize(&$collection) { $collection->$key = htmlspecialchars($var, ENT_COMPAT, 'UTF-8'); } else if (is_array($var) || is_object($var)) { $this->xml_entitize($collection->$key); - } + } } } else if (is_string($collection)) { $collection = htmlspecialchars($collection, ENT_COMPAT, 'UTF-8'); } } - + /** * adds exporttext property to the questions * @@ -474,7 +474,7 @@ function xml_entitize(&$collection) { * * @param array $questions - an array of question objects * @return an array of question objects - */ + */ function questions_with_export_info($questions, $shuffleanswers = null) { $exportquestions = array(); foreach($questions as $key=>$question) { @@ -496,19 +496,19 @@ function xml_entitize(&$collection) { * @param boolean $courselevel whether or not this is a course-level export * @param string $path provide the path to copy question media files to, if $courselevel == true * @return string containing export text - */ + */ function writequestion($question, $shuffleanswers = null, $courselevel = false, $path = '') { // turns question into string // question reflects database fields for general question and specific to type global $CFG; $expout = ''; - //need to unencode the html entities in the questiontext field. + //need to unencode the html entities in the questiontext field. // the whole question object was earlier run throught htmlspecialchars in xml_entitize(). $question->questiontext = html_entity_decode($question->questiontext, ENT_COMPAT); - + $hasimage = empty($question->image) ? 0 : 1; $hassize = empty($question->mediax) ? 0 : 1; - + $allowedtags = '

      • '; // all other tags will be stripped from question text $smarty =& $this->init_smarty(); $assesmentitemid = $this->get_assesment_item_id($question); @@ -520,19 +520,19 @@ function xml_entitize(&$collection) { $smarty->assign('assessmentitemidentifier', $assesmentitemid); $smarty->assign('assessmentitemtitle', $question->name); $smarty->assign('courselevelexport', $courselevel); - + if ($question->qtype == MULTIANSWER) { $question->questiontext = strip_tags($question->questiontext, $allowedtags . ''); $smarty->assign('questionText', $this->get_cloze_intro($question->questiontext)); } else { $smarty->assign('questionText', strip_tags($question->questiontext, $allowedtags)); } - + $smarty->assign('question', $question); // the following two are left for compatibility; the templates should be changed, though, to make object tags for the questions //$smarty->assign('questionimage', $question->image); //$smarty->assign('questionimagealt', "image: $question->image"); - + // output depends on question type switch($question->qtype) { case TRUEFALSE: @@ -541,11 +541,11 @@ function xml_entitize(&$collection) { $answers[0]['answer'] = get_string("true", "quiz"); $answers[1] = (array)$qanswers['false']; $answers[1]['answer'] = get_string("false", "quiz"); - + if (!empty($shuffleanswers)) { $answers = $this->shuffle_things($answers); } - + if (isset($question->response)) { $correctresponseid = $question->response[$questionid]; if ($answers[0]['id'] == $correctresponseid) { @@ -557,7 +557,7 @@ function xml_entitize(&$collection) { else { $correctresponse = ''; } - + $smarty->assign('correctresponse', $correctresponse); $smarty->assign('answers', $answers); $expout = $smarty->fetch('choice.tpl'); @@ -570,7 +570,7 @@ function xml_entitize(&$collection) { $correctresponses = $this->get_correct_answers($answers); $correctcount = count($correctresponses); - + $smarty->assign('responsedeclarationcardinality', $correctcount > 1 ? 'multiple' : 'single'); $smarty->assign('correctresponses', $correctresponses); $smarty->assign('answers', $answers); @@ -582,7 +582,7 @@ function xml_entitize(&$collection) { if (!empty($shuffleanswers)) { $answers = $this->shuffle_things($answers); } - + $correctresponses = $this->get_correct_answers($answers); $correctcount = count($correctresponses); @@ -593,9 +593,9 @@ function xml_entitize(&$collection) { break; case NUMERICAL: $qanswer = array_pop( $question->options->answers ); - $smarty->assign('lowerbound', $qanswer->answer - $qanswer->tolerance); - $smarty->assign('upperbound', $qanswer->answer + $qanswer->tolerance); - $smarty->assign('answer', $qanswer->answer); + $smarty->assign('lowerbound', $qanswer->answer - $qanswer->tolerance); + $smarty->assign('upperbound', $qanswer->answer + $qanswer->tolerance); + $smarty->assign('answer', $qanswer->answer); $expout = $smarty->fetch('numerical.tpl'); break; case MATCH: @@ -605,7 +605,7 @@ function xml_entitize(&$collection) { $subquestions = $this->shuffle_things($subquestions); } $setcount = count($subquestions); - + $smarty->assign('setcount', $setcount); $smarty->assign('matchsets', $subquestions); $expout = $smarty->fetch('match.tpl'); @@ -619,8 +619,8 @@ function xml_entitize(&$collection) { case MULTIANSWER: $answers = $this->get_cloze_answers_array($question); $questions = $this->get_cloze_questions($question, $answers, $allowedtags); - - $smarty->assign('cloze_trailing_text_id', CLOZE_TRAILING_TEXT_ID); + + $smarty->assign('cloze_trailing_text_id', CLOZE_TRAILING_TEXT_ID); $smarty->assign('answers', $answers); $smarty->assign('questions', $questions); $expout = $smarty->fetch('composite.tpl'); @@ -629,7 +629,7 @@ function xml_entitize(&$collection) { $smarty->assign('questionText', "This question type (Unknown: type $question_type) has not yet been implemented"); $expout = $smarty->fetch('notimplemented.tpl'); } - + // run through xml tidy function //$tidy_expout = $this->indent_xhtml( $expout, ' ' ) . "\n\n"; //return $tidy_expout; @@ -641,7 +641,7 @@ function xml_entitize(&$collection) { * * @param object $question * @return string containing a qti assesment item id - */ + */ function get_assesment_item_id($question) { return "question{$question->id}"; } @@ -651,7 +651,7 @@ function xml_entitize(&$collection) { * * @param array $answers * @return array (0-indexed) containing the answers whose grade fraction > 0 - */ + */ function get_correct_answers($answers) { $correctanswers = array(); @@ -667,7 +667,7 @@ function xml_entitize(&$collection) { * gets a new Smarty object, with the template and compile directories set * * @return object a smarty object - */ + */ function & init_smarty() { global $CFG; @@ -689,7 +689,7 @@ function xml_entitize(&$collection) { * * @param array $objectarray * @return array - an array of answer arrays - */ + */ function objects_to_array($objectarray) { $arrayarray = array(); @@ -698,13 +698,13 @@ function xml_entitize(&$collection) { } return $arrayarray; } - + /** * gets a question's cloze answer objects as arrays containing only arrays and basic data types * * @param object $question * @return array - an array of answer arrays - */ + */ function get_cloze_answers_array($question) { $answers = $this->get_answers($question); $this->xml_entitize($answers); @@ -713,7 +713,7 @@ function xml_entitize(&$collection) { } return $this->objects_to_array($answers); } - + /** * gets an array with text and question arrays for the given cloze question * @@ -724,13 +724,13 @@ function xml_entitize(&$collection) { * @param array $answers - an array of arrays containing the question's answers * @param string $allowabletags - tags not to strip out of the question text (e.g. '
        ') * @return array with text and question arrays for the given cloze question - */ + */ function get_cloze_questions($question, $answers, $allowabletags) { $questiontext = strip_tags($question->questiontext, $allowabletags); if (preg_match_all('/(.*){#([0-9]+)}/U', $questiontext, $matches)) { // matches[1] contains the text inbetween the question blanks // matches[2] contains the id of the question blanks (db: question_multianswer.positionkey) - + // find any trailing text after the last {#XX} and add it to the array if (preg_match('/.*{#[0-9]+}(.*)$/', $questiontext, $tail)) { $matches[1][] = $tail[1]; @@ -750,15 +750,15 @@ function xml_entitize(&$collection) { // to have a matching number of question and text array entries: $questions['question'][] = array('id'=>CLOZE_TRAILING_TEXT_ID, 'answertype'=>SHORTANSWER); } - + } else { $questions['text'][0] = $question->questiontext; $questions['question'][0] = array('id'=>CLOZE_TRAILING_TEXT_ID, 'answertype'=>SHORTANSWER); } - + return $questions; } - + /** * strips out the ... section, if any, and returns the text * @@ -766,7 +766,7 @@ function xml_entitize(&$collection) { * * @param string $&text * @return string the intro text, if there was an intro tag. '' otherwise. - */ + */ function get_cloze_intro(&$text) { if (preg_match('/(.*)?\(.+)?\<\/intro>(.*)/s', $text, $matches)) { $text = $matches[1] . $matches[3]; @@ -775,16 +775,16 @@ function xml_entitize(&$collection) { else { return ''; } - } - + } + /** * adds qti metadata properties to the questions * - * The passed array of questions is altered by this function + * The passed array of questions is altered by this function * * @param &questions an array of question objects - */ + */ function add_qti_info(&$questions) { foreach ($questions as $key=>$question) { @@ -792,15 +792,15 @@ function xml_entitize(&$collection) { $questions[$key]->qtiscoreable = $this->get_qti_scoreable($question); $questions[$key]->qtisolutionavailable = $this->get_qti_solution_available($question); } - + } - + /** * returns whether or not a given question is scoreable * * @param object $question * @return boolean - */ + */ function get_qti_scoreable($question) { switch ($question->qtype) { case DESCRIPTION: @@ -809,15 +809,15 @@ function xml_entitize(&$collection) { return 'true'; } } - + /** - * returns whether or not a solution is available for a given question + * returns whether or not a solution is available for a given question * * The results are based on whether or not Moodle stores answers for the given question type * * @param object $question * @return boolean - */ + */ function get_qti_solution_available($question) { switch($question->qtype) { case TRUEFALSE: @@ -837,15 +837,15 @@ function xml_entitize(&$collection) { default: return 'true'; } - + } - + /** * maps a moodle question type to a qti 2.0 question type * * @param int type_id - the moodle question type * @return string qti 2.0 question type - */ + */ function get_qti_interaction_type($type_id) { switch( $type_id ) { case TRUEFALSE: @@ -881,9 +881,9 @@ function xml_entitize(&$collection) { * * @param array $things * @return array - */ + */ function shuffle_things($things) { - $things = swapshuffle_assoc($things); + $things = swapshuffle_assoc($things); $oldthings = $things; $things = array(); foreach ($oldthings as $key=>$value) { @@ -891,15 +891,15 @@ function xml_entitize(&$collection) { } return $things; } - + /** * returns a flattened image name - with all /, \ and : replaced with other characters * * used to convert a file or url to a qti-permissable identifier * * @param string name - * @return string - */ + * @return string + */ function flatten_image_name($name) { return str_replace(array('/', '\\', ':'), array ('_','-','.'), $name); } diff --git a/question/import.php b/question/import.php index 4d6faeec02..b735f41013 100644 --- a/question/import.php +++ b/question/import.php @@ -23,7 +23,7 @@ $txt->importquestions = get_string("importquestions", "quiz"); list($catid, $catcontext) = explode(',', $pagevars['cat']); - if (!$category = get_record("question_categories", "id", $catid)) { + if (!$category = $DB->get_record("question_categories", array("id" => $catid))) { print_error('nocategory','quiz'); } diff --git a/question/preview.php b/question/preview.php index f0c74b1a92..c8bc1516b6 100644 --- a/question/preview.php +++ b/question/preview.php @@ -59,7 +59,7 @@ redirect($url->out()); } // Load the question information - if (!$questions = get_records('question', 'id', $id)) { + if (!$questions = $DB->get_records('question', array('id' => $id))) { error('Could not load question'); } if (empty($quizid)) { @@ -68,7 +68,7 @@ $quiz->review = $CFG->quiz_review; require_login($courseid, false); $quiz->course = $courseid; - } else if (!$quiz = get_record('quiz', 'id', $quizid)) { + } else if (!$quiz = $DB->get_record('quiz', array('id' => $quizid))) { error("Quiz id $quizid does not exist"); } else { require_login($quiz->course, false, get_coursemodule_from_instance('quiz', $quizid, $quiz->course)); @@ -76,7 +76,7 @@ - if ($maxgrade = get_field('quiz_question_instances', 'grade', 'quiz', $quiz->id, 'question', $id)) { + if ($maxgrade = $DB->get_field('quiz_question_instances', 'grade', array('quiz' => $quiz->id, 'question' => $id))) { $questions[$id]->maxgrade = $maxgrade; } else { $questions[$id]->maxgrade = $questions[$id]->defaultgrade; @@ -85,7 +85,7 @@ $quiz->id = 0; // just for safety $quiz->questions = $id; - if (!$category = get_record("question_categories", "id", $questions[$id]->category)) { + if (!$category = $DB->get_record("question_categories", array("id" => $questions[$id]->category))) { error("This question doesn't belong to a valid category!"); } @@ -188,8 +188,7 @@ // Fill in the correct responses (unless the question is in readonly mode) if ($fillcorrect && !$options->readonly) { - $curstate->responses = $QTYPES[$questions[$id]->qtype] - ->get_correct_responses($questions[$id], $curstate); + $curstate->responses = $QTYPES[$questions[$id]->qtype]->get_correct_responses($questions[$id], $curstate); } $strpreview = get_string('preview', 'quiz').' '.format_string($questions[$id]->name); diff --git a/question/question.php b/question/question.php index b66ba7d72a..65a60c1737 100644 --- a/question/question.php +++ b/question/question.php @@ -53,7 +53,7 @@ if (!$returnurl) { if ($id) { - if (!$question = get_record('question', 'id', $id)) { + if (!$question = $DB->get_record('question', array('id' => $id))) { print_error('questiondoesnotexist', 'question', $returnurl); } get_question_options($question); @@ -66,7 +66,7 @@ if ($id) { } // Validate the question category. -if (!$category = get_record('question_categories', 'id', $question->category)) { +if (!$category = $DB->get_record('question_categories', array('id' => $question->category))) { print_error('categorydoesnotexist', 'question', $returnurl); } diff --git a/question/restorelib.php b/question/restorelib.php index 9128a932f9..0ac7e145e4 100644 --- a/question/restorelib.php +++ b/question/restorelib.php @@ -586,8 +586,7 @@ //mappings in backup_ids to use them later where restoring states (user level). //Get the answer from DB (by question and answer) - $db_answer = $DB->get_record ("question_answers", array("question"=>$new_question_id, - "answer"=>$answer->answer)); + $db_answer = $DB->get_record ("question_answers", array("question"=>$new_question_id, "answer"=>$answer->answer)); //Do some output if (($i+1) % 50 == 0) { @@ -602,8 +601,7 @@ if ($db_answer) { //We have the database answer, update backup_ids - backup_putid($restore->backup_unique_code,"question_answers",$oldid, - $db_answer->id); + backup_putid($restore->backup_unique_code,"question_answers",$oldid, $db_answer->id); } else { $status = false; } @@ -946,10 +944,11 @@ } $coursemodulecontextslist = join($coursemodulecontexts, ','); // Decode links in questions. - if ($questions = $DB->get_records_sql('SELECT q.id, q.qtype, q.questiontext, q.generalfeedback + list($usql, $params) = $DB->get_in_or_equal(explode(',', $coursemodulecontextslist)); + if ($questions = $DB->get_records_sql("SELECT q.id, q.qtype, q.questiontext, q.generalfeedback FROM {question} q, {question_categories} qc WHERE q.category = qc.id - AND qc.contextid IN (' .$coursemodulecontextslist.')')) { + AND qc.contextid $usql", $params)) { foreach ($questions as $question) { $questiontext = restore_decode_content_links_worker($question->questiontext, $restore); @@ -982,11 +981,11 @@ } // Decode links in answers. - if ($answers = $DB->get_records_sql('SELECT qa.id, qa.answer, qa.feedback, q.qtype + if ($answers = $DB->get_records_sql("SELECT qa.id, qa.answer, qa.feedback, q.qtype FROM {question_answers} qa, {question} q, {question_categories} qc WHERE qa.question = q.id AND q.category = qc.id - AND qc.contextid IN ('.$coursemodulecontextslist.')')) { + AND qc.contextid $usql", $params)) { foreach ($answers as $answer) { $feedback = restore_decode_content_links_worker($answer->feedback, $restore); diff --git a/question/type/calculated/questiontype.php b/question/type/calculated/questiontype.php index f4cf5a10f5..e7a2b7446c 100644 --- a/question/type/calculated/questiontype.php +++ b/question/type/calculated/questiontype.php @@ -20,14 +20,14 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype function get_question_options(&$question) { // First get the datasets and default options - global $CFG; - if (!$question->options->answers = get_records_sql( + global $CFG, $DB; + if (!$question->options->answers = $DB->get_records_sql( "SELECT a.*, c.tolerance, c.tolerancetype, c.correctanswerlength, c.correctanswerformat " . - "FROM {$CFG->prefix}question_answers a, " . - " {$CFG->prefix}question_calculated c " . - "WHERE a.question = $question->id " . + "FROM {question_answers} a, " . + " {question_calculated} c " . + "WHERE a.question = ? " . "AND a.id = c.answer ". - "ORDER BY a.id ASC")) { + "ORDER BY a.id ASC", array($question->id))) { notify('Error: Missing question answer for calculated question ' . $question->id . '!'); return false; } @@ -37,16 +37,16 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype return false; } - if (!$options = get_records('question_calculated', 'question', $question->id)) { + if (!$options = $DB->get_records('question_calculated', array('question' => $question->id))) { notify("No options were found for calculated question #{$question->id}! Proceeding with defaults."); - // $options = new Array(); + // $options = new Array(); $options= new stdClass; $options->tolerance = 0.01; $options->tolerancetype = 1; // relative $options->correctanswerlength = 2; $options->correctanswerformat = 1; // decimals - } + } // For historic reasons we also need these fields in the answer objects. // This should eventually be removed and related code changed to use @@ -62,44 +62,45 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $virtualqtype = $this->get_virtual_qtype(); $virtualqtype->get_numerical_units($question); - + if( isset($question->export_process)&&$question->export_process){ $question->options->datasets = $this->get_datasets_for_export($question); - } + } return true; } - + function get_datasets_for_export(&$question){ + global $DB; $datasetdefs = array(); if (!empty($question->id)) { global $CFG; $sql = "SELECT i.* - FROM {$CFG->prefix}question_datasets d, - {$CFG->prefix}question_dataset_definitions i - WHERE d.question = '$question->id' + FROM {question_datasets} d, + {question_dataset_definitions} i + WHERE d.question = ? AND d.datasetdefinition = i.id "; - if ($records = get_records_sql($sql)) { + if ($records = $DB->get_records_sql($sql, array($question->id))) { foreach ($records as $r) { $def = $r ; if ($def->category=='0'){ $def->status='private'; - } else { + } else { $def->status='shared'; - } + } $def->type ='calculated' ; list($distribution, $min, $max,$dec) = explode(':', $def->options, 4); $def->distribution=$distribution; $def->minimum=$min; $def->maximum=$max; - $def->decimals=$dec ; + $def->decimals=$dec ; if ($def->itemcount > 0 ) { // get the datasetitems $def->items = array(); $sql1= (" SELECT itemnumber, definition, id, value - FROM {$CFG->prefix}question_dataset_items - WHERE definition = '$def->id' order by itemnumber ASC "); - if ($items = get_records_sql($sql1)){ + FROM {question_dataset_items} + WHERE definition = ? order by itemnumber ASC "); + if ($items = $DB->get_records_sql($sql1, array($def->id))){ $n = 0; foreach( $items as $ii){ $n++; @@ -110,24 +111,24 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $def->number_of_items=$n ; } } - $datasetdefs["1-$r->category-$r->name"] = $def; + $datasetdefs["1-$r->category-$r->name"] = $def; } } } return $datasetdefs ; - } - + } + function save_question_options($question) { //$options = $question->subtypeoptions; // Get old answers: - global $CFG; - + global $CFG, $DB; + // Get old versions of the objects - if (!$oldanswers = get_records('question_answers', 'question', $question->id, 'id ASC')) { + if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) { $oldanswers = array(); } - if (!$oldoptions = get_records('question_calculated', 'question', $question->id, 'answer ASC')) { + if (!$oldoptions = $DB->get_records('question_calculated', array('question' => $question->id), 'answer ASC')) { $oldoptions = array(); } // Save the units. @@ -141,21 +142,21 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } // Insert all the new answers foreach ($question->answers as $key => $dataanswer) { - if ( trim($dataanswer) != '' ) { + if ( trim($dataanswer) != '' ) { $answer = new stdClass; $answer->question = $question->id; $answer->answer = trim($dataanswer); $answer->fraction = $question->fraction[$key]; $answer->feedback = trim($question->feedback[$key]); - + if ($oldanswer = array_shift($oldanswers)) { // Existing answer, so reuse it $answer->id = $oldanswer->id; - if (! update_record("question_answers", $answer)) { + if (! $DB->update_record("question_answers", $answer)) { $result->error = "Could not update question answer! (id=$answer->id)"; return $result; } } else { // This is a completely new answer - if (! $answer->id = insert_record("question_answers", $answer)) { + if (! $answer->id = $DB->insert_record("question_answers", $answer)) { $result->error = "Could not insert question answer!"; return $result; } @@ -171,15 +172,15 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $options->tolerancetype = trim($question->tolerancetype[$key]); $options->correctanswerlength = trim($question->correctanswerlength[$key]); $options->correctanswerformat = trim($question->correctanswerformat[$key]); - + // Save options if (isset($options->id)) { // reusing existing record - if (! update_record('question_calculated', $options)) { + if (! $DB->update_record('question_calculated', $options)) { $result->error = "Could not update question calculated options! (id=$options->id)"; return $result; } } else { // new options - if (! insert_record('question_calculated', $options)) { + if (! $DB->insert_record('question_calculated', $options)) { $result->error = "Could not insert question calculated options!"; return $result; } @@ -189,21 +190,21 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype // delete old answer records if (!empty($oldanswers)) { foreach($oldanswers as $oa) { - delete_records('question_answers', 'id', $oa->id); + $DB->delete_records('question_answers', array('id' => $oa->id)); } } // delete old answer records if (!empty($oldoptions)) { foreach($oldoptions as $oo) { - delete_records('question_calculated', 'id', $oo->id); + $DB->delete_records('question_calculated', array('id' => $oo->id)); } } if( isset($question->import_process)&&$question->import_process){ $this->import_datasets($question); - } + } // Report any problems. if (!empty($result->notice)) { return $result; @@ -212,24 +213,25 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } function import_datasets($question){ + global $DB; $n = count($question->dataset); foreach ($question->dataset as $dataset) { - // name, type, option, + // name, type, option, $datasetdef = new stdClass(); $datasetdef->name = $dataset->name; $datasetdef->type = 1 ; $datasetdef->options = $dataset->distribution.':'.$dataset->min.':'.$dataset->max.':'.$dataset->length; - $datasetdef->itemcount=$dataset->itemcount; + $datasetdef->itemcount=$dataset->itemcount; if ( $dataset->status =='private'){ $datasetdef->category = 0; $todo='create' ; }else if ($dataset->status =='shared' ){ - if ($sharedatasetdefs = get_records_select( + if ($sharedatasetdefs = $DB->get_records_select( 'question_dataset_definitions', "type = '1' - AND name = '$dataset->name' - AND category = '$question->category' - ORDER BY id DESC;" + AND name = ? + AND category = ? + ORDER BY id DESC;", array($dataset->name, $question->category) )) { // so there is at least one $sharedatasetdef = array_shift($sharedatasetdefs); if ( $sharedatasetdef->options == $datasetdef->options ){// identical so use it @@ -238,24 +240,22 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } else { // different so create a private one $datasetdef->category = 0; $todo='create' ; - } + } }else { // no so create one $datasetdef->category =$question->category ; $todo='create' ; - } - } + } + } if ( $todo=='create'){ - if (!$datasetdef->id = insert_record( - 'question_dataset_definitions', $datasetdef)) { + if (!$datasetdef->id = $DB->insert_record( 'question_dataset_definitions', $datasetdef)) { print_error('cannotcreatedataset', 'question', '', $defid); - } - } + } + } // Create relation to the dataset: $questiondataset = new stdClass; $questiondataset->question = $question->id; $questiondataset->datasetdefinition = $datasetdef->id; - if (!insert_record('question_datasets', - $questiondataset)) { + if (!$DB->insert_record('question_datasets', $questiondataset)) { print_error("cannotcreaterelation", 'question', '', array($dataset->name, $todo)); } @@ -265,15 +265,15 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $datasetitem->definition=$datasetdef->id ; $datasetitem->itemnumber = $dataitem->itemnumber ; $datasetitem->value = $dataitem->value ; - if (!insert_record('question_dataset_items', $datasetitem)) { + if (!$DB->insert_record('question_dataset_items', $datasetitem)) { print_error('cannotinsertitem', 'question', '', array($item->itemnumber, $item->value, $datasetdef->name)); } - } - } + } + } } } - + function create_runtime_question($question, $form) { $question = parent::create_runtime_question($question, $form); $question->options->answers = array(); @@ -342,15 +342,16 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_calculated", "question", $questionid); - delete_records("question_numerical_units", "question", $questionid); - if ($datasets = get_records('question_datasets', 'question', $questionid)) { + global $DB; + $DB->delete_records("question_calculated", array("question" => $questionid)); + $DB->delete_records("question_numerical_units", array("question" => $questionid)); + if ($datasets = $DB->get_records('question_datasets', array('question' => $questionid))) { foreach ($datasets as $dataset) { - delete_records('question_dataset_definitions', 'id', $dataset->datasetdefinition); - delete_records('question_dataset_items', 'definition', $dataset->datasetdefinition); + $DB->delete_records('question_dataset_definitions', array('id' => $dataset->datasetdefinition)); + $DB->delete_records('question_dataset_items', array('definition' => $dataset->datasetdefinition)); } } - delete_records("question_datasets", "question", $questionid); + $DB->delete_records("question_datasets", array("question" => $questionid)); return true; } @@ -362,7 +363,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $unit = $unit->unit; } else { $unit = ''; - } + } // We modify the question to look like a numerical question $numericalquestion = fullclone($question); foreach ($numericalquestion->options->answers as $key => $answer) { @@ -375,7 +376,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } $numericalquestion->questiontext = parent::substitute_variables( $numericalquestion->questiontext, $state->options->dataset); - //evaluate the equations i.e {=5+4) + //evaluate the equations i.e {=5+4) $qtext = ""; $qtextremaining = $numericalquestion->questiontext ; while (ereg('\{=([^[:space:]}]*)}', $qtextremaining, $regs1)) { @@ -387,17 +388,17 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } else { if( $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])){ $str=$formulaerrors ; - }else { - eval('$str = '.$regs1[1].';'); + }else { + eval('$str = '.$regs1[1].';'); } } - $qtext = $qtext.$str ; - } + $qtext = $qtext.$str ; + } $numericalquestion->questiontext = $qtext.$qtextremaining ; // end replace equations $virtualqtype->print_question_formulation_and_controls($numericalquestion, $state, $cmoptions, $options); } function grade_responses(&$question, &$state, $cmoptions) { - // Forward the grading to the virtual qtype + // Forward the grading to the virtual qtype // We modify the question to look like a numerical question $numericalquestion = fullclone($question); foreach ($numericalquestion->options->answers as $key => $answer) { @@ -578,10 +579,10 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } function save_dataset_items($question, $fromform){ - global $CFG ; + global $CFG, $DB; // max datasets = 100 items $max100 = 100 ; - if(isset($fromform->nextpageparam["forceregeneration"])) { + if(isset($fromform->nextpageparam["forceregeneration"])) { $regenerate = $fromform->nextpageparam["forceregeneration"]; }else{ $regenerate = 0 ; @@ -599,7 +600,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype if (isset($datasetdef->id) && $datasetdef->options != $olddatasetdefs[$defid]->options) { // Save the new value for options - update_record('question_dataset_definitions', $datasetdef); + $DB->update_record('question_dataset_definitions', $datasetdef); } // Get maxnumber @@ -624,11 +625,11 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype if ($fromform->itemid[$i]) { // Reuse any previously used record $addeditem->id = $fromform->itemid[$i]; - if (!update_record('question_dataset_items', $addeditem)) { + if (!$DB->update_record('question_dataset_items', $addeditem)) { print_error('cannotupdateitem', 'question'); } } else { - if (!insert_record('question_dataset_items', $addeditem)) { + if (!$DB->insert_record('question_dataset_items', $addeditem)) { print_error('cannotinsert', 'question'); } } @@ -641,7 +642,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype if (isset($newdef->id) && $newdef->itemcount <= $maxnumber) { $newdef->itemcount = $maxnumber; // Save the new value for options - update_record('question_dataset_definitions', $newdef); + $DB->update_record('question_dataset_definitions', $newdef); } } } @@ -656,10 +657,10 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype // Generate a new dataset item (or reuse an old one) foreach ($datasetdefs as $defid => $datasetdef) { if (isset($datasetdef->id)) { - $datasetdefs[$defid]->items = get_records_sql( // Use number as key!! + $datasetdefs[$defid]->items = $DB->get_records_sql( // Use number as key!! " SELECT itemnumber, definition, id, value - FROM {$CFG->prefix}question_dataset_items - WHERE definition = $datasetdef->id ORDER BY itemnumber"); + FROM {question_dataset_items} + WHERE definition = ? ORDER BY itemnumber", array($datasetdef->id)); } // echo "
        "; print_r($datasetdefs[$defid]->items);
                         for ($numberadded =$maxnumber+1 ; $numberadded <= $maxnumber+$numbertoadd ; $numberadded++){
        @@ -675,9 +676,9 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype
                                     $datasetitem->value = '';
                                 }
                                 //pp  echo "
        "; print_r( $datasetitem );
        -                        if (!insert_record('question_dataset_items', $datasetitem)) {
        +                        if (!$DB->insert_record('question_dataset_items', $datasetitem)) {
                                     print_error('cannotinsert', 'question');
        -                        }                        
        +                        }
                             }
                         }//for number added
                     }// datasetsdefs end
        @@ -686,10 +687,10 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype
                         if (isset($newdef->id) && $newdef->itemcount <= $maxnumber) {
                             $newdef->itemcount = $maxnumber;
                             // Save the new value for options
        -                    update_record('question_dataset_definitions', $newdef);
        +                    $DB->update_record('question_dataset_definitions', $newdef);
                         }
                     }
        -        }        
        +        }
         
                 if (isset($fromform->deletebutton))  {
                     if(isset($fromform->selectdelete)) $newmaxnumber = $maxnumber-$fromform->selectdelete ;
        @@ -697,8 +698,8 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype
                     if ($newmaxnumber < 0 ) $newmaxnumber = 0 ;
                     foreach ($datasetdefs as $datasetdef) {
                         if ($datasetdef->itemcount == $maxnumber) {
        -                    $datasetdef->itemcount= $newmaxnumber ;        
        -                    if (!update_record('question_dataset_definitions',
        +                    $datasetdef->itemcount= $newmaxnumber ;
        +                    if (!$DB->update_record('question_dataset_definitions',
                                                $datasetdef)) {
                                  print_error('cannotupdatecount', 'question');
                             }
        @@ -718,9 +719,9 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype
         
                 } else if ($regs[1] == 'loguniform') {
                     $log0 = log(abs($regs[2])); // It would have worked the other way to
        -            $nbr = exp($log0 + (log(abs($regs[3])) - $log0)*mt_rand()/mt_getrandmax());        
        +            $nbr = exp($log0 + (log(abs($regs[3])) - $log0)*mt_rand()/mt_getrandmax());
                     return sprintf("%.".$regs[4]."f",$nbr);
        - 
        +
                 } else {
                     print_error('disterror', 'question', '', $regs[1]);
                 }
        @@ -746,9 +747,9 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype
             }
         
             function comment_on_datasetitems($question, $data, $number) {
        +        global $DB;
                 /// Find a default unit:
        -        if (!empty($question->id) && $unit = get_record('question_numerical_units',
        -                'question', $question->id, 'multiplier', 1.0)) {
        +        if (!empty($question->id) && $unit = $DB->get_record('question_numerical_units', array('question'=> $question->id, 'multiplier' => 1.0))) {
                     $unit = $unit->unit;
                 } else {
                     $unit = '';
        @@ -777,7 +778,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype
                     $virtualqtype->get_tolerance_interval($calculated);
                     if ($calculated->min === '') {
                         // This should mean that something is wrong
        -                $stranswers .= " -$calculated->answer".'

        '; + $stranswers .= " -$calculated->answer".'

        '; } else { $stranswers .= $formula.' = '.$calculated->answer.'
        ' ; $stranswers .= $strmin. $delimiter.$calculated->min.'---'; @@ -798,7 +799,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype // Takes datasets from the parent implementation but // filters options that are currently not accepted by calculated // It also determines a default selection... - //$renameabledatasets not implemented anmywhere + //$renameabledatasets not implemented anmywhere list($options, $selected) = parent::dataset_options($form, $name,'','qtype_calculated'); // list($options, $selected) = $this->dataset_optionsa($form, $name); @@ -808,11 +809,11 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } } if (!$selected) { - if ($mandatory){ + if ($mandatory){ $selected = LITERAL . "-0-$name"; // Default }else { $selected = "0"; // Default - } + } } return array($options, $selected); } @@ -851,7 +852,7 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $unit = $unit->unit; } else { $unit = ''; - } + } foreach ($question->options->answers as $answer) { if (((int) $answer->fraction) === 1) { $answernumerical = qtype_calculated_calculate_answer( @@ -873,47 +874,47 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype if (empty($formula)) { $str = ''; } else { - eval('$str = '.$formula.';'); + eval('$str = '.$formula.';'); } return $str; } - + /** * This function retrieve the item count of the available category shareable - * wild cards that is added as a comment displayed when a wild card with + * wild cards that is added as a comment displayed when a wild card with * the same name is displayed in datasetdefinitions_form.php - */ + */ function get_dataset_definitions_category($form) { - global $CFG; + global $CFG, $DB; $datasetdefs = array(); $lnamemax = 30; - if (!empty($form->category)) { + if (!empty($form->category)) { $sql = "SELECT i.*,d.* - FROM {$CFG->prefix}question_datasets d, - {$CFG->prefix}question_dataset_definitions i + FROM {question_datasets} d, + {question_dataset_definitions} i WHERE i.id = d.datasetdefinition - AND i.category = '$form->category' + AND i.category = ? ; "; - if ($records = get_records_sql($sql)) { + if ($records = $DB->get_records_sql($sql, array($form->category))) { foreach ($records as $r) { if ( !isset ($datasetdefs["$r->name"])) $datasetdefs["$r->name"] = $r->itemcount; } } - } + } return $datasetdefs ; - } + } /** * This function build a table showing the available category shareable * wild cards, their name, their definition (Min, Max, Decimal) , the item count * and the name of the question where they are used. - * This table is intended to be add before the question text to help the user use + * This table is intended to be add before the question text to help the user use * these wild cards - */ - + */ + function print_dataset_definitions_category($form) { - global $CFG; + global $CFG, $DB; $datasetdefs = array(); $lnamemax = 22; $namestr =get_string('name', 'quiz'); @@ -923,32 +924,32 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype $questionusingstr = get_string('usedinquestion','qtype_calculated'); $itemscountstr = get_string('itemscount','qtype_datasetdependent'); $text =''; - if (!empty($form->category)) { + if (!empty($form->category)) { list($category) = explode(',', $form->category); $sql = "SELECT i.*,d.* - FROM {$CFG->prefix}question_datasets d, - {$CFG->prefix}question_dataset_definitions i + FROM {question_datasets} d, + {question_dataset_definitions} i WHERE i.id = d.datasetdefinition - AND i.category = $category; + AND i.category = ?; " ; - if ($records = get_records_sql($sql)) { + if ($records = $DB->get_records_sql($sql, array($category))) { foreach ($records as $r) { $sql1 = "SELECT q.* - FROM {$CFG->prefix}question q - WHERE q.id = $r->question - "; + FROM {question} q + WHERE q.id = ? + "; if ( !isset ($datasetdefs["$r->type-$r->category-$r->name"])){ $datasetdefs["$r->type-$r->category-$r->name"]= $r; } - if ($questionb = get_records_sql($sql1)) { + if ($questionb = $DB->get_records_sql($sql1, array($r->question))) { $datasetdefs["$r->type-$r->category-$r->name"]->questions[$r->question]->name =$questionb[$r->question]->name ; } } } } if (!empty ($datasetdefs)){ - - $text =""; + + $text ="
        $namestr$rangeofvaluestr$itemscountstr$questionusingstr
        "; foreach ($datasetdefs as $datasetdef){ list($distribution, $min, $max,$dec) = explode(':', $datasetdef->options, 4); $text .=""; } $text .="
        $namestr$rangeofvaluestr$itemscountstr$questionusingstr
        $datasetdef->name $min - $max $datasetdef->itemcount  "; @@ -960,16 +961,16 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype } else { $qu->name = ''; } - $text .="    $qu->name
        "; - } + $text .="    $qu->name
        "; + } $text .="
        "; }else{ - $text .=get_string('nosharedwildcard', 'qtype_calculated'); + $text .=get_string('nosharedwildcard', 'qtype_calculated'); } return $text ; - } + } /// BACKUP FUNCTIONS //////////////////////////// @@ -980,10 +981,10 @@ class question_calculated_qtype extends question_dataset_dependent_questiontype * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { - + global $DB; $status = true; - $calculateds = get_records("question_calculated","question",$question,"id"); + $calculateds = $DB->get_records("question_calculated",array("question" =>$question,"id")); //If there are calculated-s if ($calculateds) { //Iterate over each calculateds diff --git a/question/type/datasetdependent/abstractqtype.php b/question/type/datasetdependent/abstractqtype.php index 82806d2d09..633b9cf965 100644 --- a/question/type/datasetdependent/abstractqtype.php +++ b/question/type/datasetdependent/abstractqtype.php @@ -16,7 +16,7 @@ define("LINK", "3"); class question_dataset_dependent_questiontype extends default_questiontype { - var $virtualqtype = false; + public $virtualqtype = false; function name() { return 'datasetdependent'; @@ -29,13 +29,13 @@ class question_dataset_dependent_questiontype extends default_questiontype { function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) { // Find out how many datasets are available - global $CFG; - if(!$maxnumber = (int)get_field_sql( + global $CFG, $DB; + if(!$maxnumber = (int)$DB->get_field_sql( "SELECT MIN(a.itemcount) - FROM {$CFG->prefix}question_dataset_definitions a, - {$CFG->prefix}question_datasets b - WHERE b.question = $question->id - AND a.id = b.datasetdefinition")) { + FROM {question_dataset_definitions} a, + {question_datasets} b + WHERE b.question = ? + AND a.id = b.datasetdefinition", array($question->id))) { print_error('cannotgetdsforquestion', 'question', '', $question->id); } @@ -68,12 +68,12 @@ class question_dataset_dependent_questiontype extends default_questiontype { } function save_session_and_responses(&$question, &$state) { + global $DB; $responses = 'dataset'.$state->options->datasetitem.'-'. $state->responses['']; // Set the legacy answer field - if (!set_field('question_states', 'answer', $responses, 'id', - $state->id)) { + if (!$DB->set_field('question_states', 'answer', $responses, array('id', $state->id))) { return false; } return true; @@ -90,15 +90,15 @@ class question_dataset_dependent_questiontype extends default_questiontype { function uses_quizfile($question, $relativefilepath) { // Check whether the specified file is available by any // dataset item on this question... - global $CFG; - if (get_record_sql(" SELECT * - FROM {$CFG->prefix}question_dataset_items i, - {$CFG->prefix}question_dataset_definitions d, - {$CFG->prefix}question_datasets q - WHERE i.value = '$relativefilepath' + global $CFG, $DB; + if ($DB->get_record_sql(" SELECT * + FROM {question_dataset_items} i, + {question_dataset_definitions} d, + {question_datasets} q + WHERE i.value = ? AND d.id = i.definition AND d.type = 2 AND d.id = q.datasetdefinition - AND q.question = $question->id ")) { + AND q.question = ? ", array($relativefilepath, $question->id))) { return true; } else { @@ -323,17 +323,18 @@ class question_dataset_dependent_questiontype extends default_questiontype { } function get_dataset_definitions($questionid, $newdatasets) { + global $DB; //get the existing datasets for this question $datasetdefs = array(); if (!empty($questionid)) { global $CFG; $sql = "SELECT i.* - FROM {$CFG->prefix}question_datasets d, - {$CFG->prefix}question_dataset_definitions i - WHERE d.question = '$questionid' + FROM {question_datasets} d, + {question_dataset_definitions} i + WHERE d.question = ? AND d.datasetdefinition = i.id "; - if ($records = get_records_sql($sql)) { + if ($records = $DB->get_records_sql($sql, array($questionid->id))) { foreach ($records as $r) { $datasetdefs["$r->type-$r->category-$r->name"] = $r; } @@ -361,6 +362,7 @@ class question_dataset_dependent_questiontype extends default_questiontype { } function save_dataset_definitions($form) { + global $DB; // Save datasets $datasetdefinitions = $this->get_dataset_definitions($form->id, $form->dataset); $tmpdatasets = array_flip($form->dataset); @@ -370,14 +372,10 @@ class question_dataset_dependent_questiontype extends default_questiontype { if (isset($datasetdef->id)) { if (!isset($tmpdatasets[$defid])) { // This dataset is not used any more, delete it - delete_records('question_datasets', - 'question', $form->id, - 'datasetdefinition', $datasetdef->id); + $DB->delete_records('question_datasets', array('question' => $form->id, 'datasetdefinition' => $datasetdef->id)); if ($datasetdef->category == 0) { // Question local dataset - delete_records('question_dataset_definitions', - 'id', $datasetdef->id); - delete_records('question_dataset_items', - 'definition', $datasetdef->id); + $DB->delete_records('question_dataset_definitions', array('id' => $datasetdef->id)); + $DB->delete_records('question_dataset_items', array('definition' => $datasetdef->id)); } } // This has already been saved or just got deleted @@ -385,8 +383,7 @@ class question_dataset_dependent_questiontype extends default_questiontype { continue; } - if (!$datasetdef->id = insert_record( - 'question_dataset_definitions', $datasetdef)) { + if (!$datasetdef->id = $DB->insert_record('question_dataset_definitions', $datasetdef)) { print_error("cannotcreatedataset", 'question', '', $defid); } @@ -396,17 +393,15 @@ class question_dataset_dependent_questiontype extends default_questiontype { // By first creating the datasetdefinition above we // can manage to automatically take care of // some possible realtime concurrence - if ($olderdatasetdefs = get_records_select( - 'question_dataset_definitions', - "type = '$datasetdef->type' - AND name = '$datasetdef->name' - AND category = '$datasetdef->category' - AND id < $datasetdef->id - ORDER BY id DESC")) { + if ($olderdatasetdefs = $DB->get_records_select( 'question_dataset_definitions', + "type = ? + AND name = ? + AND category = ? + AND id < ? + ORDER BY id DESC", array($datasetdef->type, $datasetdef->name, $datasetdef->category, $datasetdef->id))) { while ($olderdatasetdef = array_shift($olderdatasetdefs)) { - delete_records('question_dataset_definitions', - 'id', $datasetdef->id); + $DB->delete_records('question_dataset_definitions', array('id' => $datasetdef->id)); $datasetdef = $olderdatasetdef; } } @@ -416,8 +411,7 @@ class question_dataset_dependent_questiontype extends default_questiontype { $questiondataset = new stdClass; $questiondataset->question = $form->id; $questiondataset->datasetdefinition = $datasetdef->id; - if (!insert_record('question_datasets', - $questiondataset)) { + if (!$DB->insert_record('question_datasets', $questiondataset)) { print_error('cannotcreaterelation', 'question', '', $name); } unset($datasetdefinitions[$defid]); @@ -427,14 +421,11 @@ class question_dataset_dependent_questiontype extends default_questiontype { // to datasets in other categories: if (!empty($datasetdefinitions)) { foreach ($datasetdefinitions as $def) { - delete_records('question_datasets', - 'question', $form->id, - 'datasetdefinition', $def->id); + $DB->delete_records('question_datasets', array('question' => $form->id, 'datasetdefinition' => $def->id)); if ($def->category == 0) { // Question local dataset - delete_records('question_dataset_definitions', 'id', $def->id); - delete_records('question_dataset_items', - 'definition', $def->id); + $DB->delete_records('question_dataset_definitions', array('id' => $def->id)); + $DB->delete_records('question_dataset_items', array('definition' => $def->id)); } } } @@ -445,7 +436,7 @@ class question_dataset_dependent_questiontype extends default_questiontype { * save_dataset_definitions() */ function save_as_new_dataset_definitions($form, $initialid) { - global $CFG ; + global $CFG, $DB; // Get the datasets from the intial question $datasetdefinitions = $this->get_dataset_definitions($initialid, $form->dataset); // $tmpdatasets contains those of the new question @@ -465,27 +456,26 @@ class question_dataset_dependent_questiontype extends default_questiontype { $olddatasetid = $datasetdef->id ; $olditemcount = $datasetdef->itemcount ; $datasetdef->itemcount =0; - if (!$datasetdef->id = insert_record( - 'question_dataset_definitions', $datasetdef)) { + if (!$datasetdef->id = $DB->insert_record('question_dataset_definitions', $datasetdef)) { print_error('cannotcreatedataset', 'question', '', $defid); } //copy the dataitems - $olditems = get_records_sql( // Use number as key!! + $olditems = $DB->get_records_sql( // Use number as key!! " SELECT itemnumber, value - FROM {$CFG->prefix}question_dataset_items - WHERE definition = $olddatasetid "); + FROM {question_dataset_items} + WHERE definition = ? ", array($olddatasetid)); if (count($olditems) > 0 ) { $itemcount = 0; foreach($olditems as $item ){ $item->definition = $datasetdef->id; - if (!insert_record('question_dataset_items', $item)) { + if (!$DB->insert_record('question_dataset_items', $item)) { print_error('cannotinsertitem', 'question', '', array($item->itemnumber, $item->value, $datasetdef->name)); } $itemcount++; } //update item count $datasetdef->itemcount =$itemcount; - update_record('question_dataset_definitions', $datasetdef); + $DB->update_record('question_dataset_definitions', $datasetdef); } // end of copy the dataitems }// end of copy the datasetdef // Create relation to the new question with this @@ -493,16 +483,14 @@ class question_dataset_dependent_questiontype extends default_questiontype { $questiondataset = new stdClass; $questiondataset->question = $form->id; $questiondataset->datasetdefinition = $datasetdef->id; - if (!insert_record('question_datasets', - $questiondataset)) { + if (!$DB->insert_record('question_datasets', $questiondataset)) { print_error('cannotcreaterelation', 'question', '', $name); } unset($datasetdefinitions[$defid]); continue; }// end of datasetdefs from the initial question // really new one code similar to save_dataset_definitions() - if (!$datasetdef->id = insert_record( - 'question_dataset_definitions', $datasetdef)) { + if (!$datasetdef->id = $DB->insert_record('question_dataset_definitions', $datasetdef)) { print_error('cannotcreatedataset', 'question', '', $defid); } @@ -512,17 +500,16 @@ class question_dataset_dependent_questiontype extends default_questiontype { // By first creating the datasetdefinition above we // can manage to automatically take care of // some possible realtime concurrence - if ($olderdatasetdefs = get_records_select( + if ($olderdatasetdefs = $DB->get_records_select( 'question_dataset_definitions', - "type = '$datasetdef->type' - AND name = '$datasetdef->name' - AND category = '$datasetdef->category' - AND id < $datasetdef->id - ORDER BY id DESC")) { + "type = ? + AND name = ? + AND category = ? + AND id < ? + ORDER BY id DESC", array($datasetdef->type, $datasetdef->name, $datasetdef->category, $datasetdef->id))) { while ($olderdatasetdef = array_shift($olderdatasetdefs)) { - delete_records('question_dataset_definitions', - 'id', $datasetdef->id); + $DB->delete_records('question_dataset_definitions', array('id' => $datasetdef->id)); $datasetdef = $olderdatasetdef; } } @@ -532,8 +519,7 @@ class question_dataset_dependent_questiontype extends default_questiontype { $questiondataset = new stdClass; $questiondataset->question = $form->id; $questiondataset->datasetdefinition = $datasetdef->id; - if (!insert_record('question_datasets', - $questiondataset)) { + if (!$DB->insert_record('question_datasets', $questiondataset)) { print_error('cannotcreaterelation', 'question', '', $name); } unset($datasetdefinitions[$defid]); @@ -543,14 +529,11 @@ class question_dataset_dependent_questiontype extends default_questiontype { // to datasets in other categories: if (!empty($datasetdefinitions)) { foreach ($datasetdefinitions as $def) { - delete_records('question_datasets', - 'question', $form->id, - 'datasetdefinition', $def->id); + $DB->delete_records('question_datasets', array('question' => $form->id, 'datasetdefinition' => $def->id)); if ($def->category == 0) { // Question local dataset - delete_records('question_dataset_definitions', 'id', $def->id); - delete_records('question_dataset_items', - 'definition', $def->id); + $DB->delete_records('question_dataset_definitions', array('id' => $def->id)); + $DB->delete_records('question_dataset_items', array('definition' => $def->id)); } } } @@ -622,16 +605,16 @@ class question_dataset_dependent_questiontype extends default_questiontype { // Select a dataset in the following format: // An array indexed by the variable names (d.name) pointing to the value // to be substituted - global $CFG; - if (!$dataset = get_records_sql( + global $CFG, $DB; + if (!$dataset = $DB->get_records_sql( "SELECT d.name, i.value - FROM {$CFG->prefix}question_dataset_definitions d, - {$CFG->prefix}question_dataset_items i, - {$CFG->prefix}question_datasets q - WHERE q.question = $question->id + FROM {question_dataset_definitions} d, + {question_dataset_items} i, + {question_datasets} q + WHERE q.question = ? AND q.datasetdefinition = d.id AND d.id = i.definition - AND i.itemnumber = $datasetitem")) { + AND i.itemnumber = ?", array($question->id, $datasetitem))) { print_error('cannotgetdsfordependent', 'question', '', array($question->id, $datasetitem)); } array_walk($dataset, create_function('&$val', '$val = $val->value;')); @@ -693,14 +676,14 @@ class question_dataset_dependent_questiontype extends default_questiontype { $options['0'] = get_string($prefix.'nodataset', $langfile); // Construct question local options - global $CFG; - $currentdatasetdef = get_record_sql( + global $CFG, $DB; + $currentdatasetdef = $DB->get_record_sql( "SELECT a.* - FROM {$CFG->prefix}question_dataset_definitions a, - {$CFG->prefix}question_datasets b + FROM {question_dataset_definitions} a, + {question_datasets} b WHERE a.id = b.datasetdefinition - AND b.question = '$form->id' - AND a.name = '$name'") + AND b.question = ? + AND a.name = ?", array($form->id, $name)) or $currentdatasetdef->type = '0'; foreach (array( LITERAL, FILE, LINK) as $type) { $key = "$type-0-$name"; @@ -713,13 +696,13 @@ class question_dataset_dependent_questiontype extends default_questiontype { } // Construct question category options - $categorydatasetdefs = get_records_sql( + $categorydatasetdefs = $DB->get_records_sql( "SELECT a.type, a.id - FROM {$CFG->prefix}question_dataset_definitions a, - {$CFG->prefix}question_datasets b + FROM {question_dataset_definitions} a, + {question_datasets} b WHERE a.id = b.datasetdefinition - AND a.category = '$form->category' - AND a.name = '$name'"); + AND a.category = ? + AND a.name = ?", array($form->category, $name)); foreach(array( LITERAL, FILE, LINK) as $type) { $key = "$type-$form->category-$name"; if (isset($categorydatasetdefs[$type]) diff --git a/question/type/datasetdependent/datasetitems_form.php b/question/type/datasetdependent/datasetitems_form.php index 3a17e65c4e..1fba187f7b 100644 --- a/question/type/datasetdependent/datasetitems_form.php +++ b/question/type/datasetdependent/datasetitems_form.php @@ -7,28 +7,28 @@ class question_dataset_dependent_items_form extends moodleform { * * @var object */ - var $question; + public $question; /** * Reference to question type object * * @var question_dataset_dependent_questiontype */ - var $qtypeobj; + public $qtypeobj; - var $datasetdefs; + public $datasetdefs; - var $maxnumber = -1; + public $maxnumber = -1; - var $regenerate; + public $regenerate; - var $noofitems; + public $noofitems; /** * Add question-type specific form fields. * * @param MoodleQuickForm $mform the form being built. */ function question_dataset_dependent_items_form($submiturl, $question, $regenerate){ - global $QTYPES, $SESSION, $CFG; + global $QTYPES, $SESSION, $CFG, $DB; $this->regenerate = $regenerate; $this->question = $question; $this->qtypeobj =& $QTYPES[$this->question->qtype]; @@ -51,10 +51,10 @@ class question_dataset_dependent_items_form extends moodleform { } foreach ($this->datasetdefs as $defid => $datasetdef) { if (isset($datasetdef->id)) { - $this->datasetdefs[$defid]->items = get_records_sql( // Use number as key!! + $this->datasetdefs[$defid]->items = $DB->get_records_sql( // Use number as key!! " SELECT itemnumber, definition, id, value - FROM {$CFG->prefix}question_dataset_items - WHERE definition = $datasetdef->id "); + FROM {question_dataset_items} + WHERE definition = ? ", array($datasetdef->id)); } } parent::moodleform($submiturl); @@ -75,7 +75,7 @@ class question_dataset_dependent_items_form extends moodleform { foreach ($this->datasetdefs as $defkey => $datasetdef){ $mform->addElement('text', "number[$j]", get_string('param', 'qtype_datasetdependent', $datasetdef->name)); $mform->setType("number[$j]", PARAM_NUMBER); - $this->qtypeobj->custom_generator_tools_part(&$mform, $idx, $j); + $this->qtypeobj->custom_generator_tools_part($mform, $idx, $j); $idx++; $mform->addElement('hidden', "definition[$j]"); $mform->addElement('hidden', "itemid[$j]"); @@ -162,7 +162,7 @@ class question_dataset_dependent_items_form extends moodleform { $mform->addElement('hidden', 'wizard', 'datasetitems'); $mform->setType('wizard', PARAM_ALPHA); - + $mform->addElement('hidden', 'returnurl'); $mform->setType('returnurl', PARAM_LOCALURL); $mform->setDefault('returnurl', 0); @@ -239,4 +239,4 @@ class question_dataset_dependent_items_form extends moodleform { } -?> \ No newline at end of file +?> diff --git a/question/type/edit_question_form.php b/question/type/edit_question_form.php index de676bcee5..7e10d87def 100644 --- a/question/type/edit_question_form.php +++ b/question/type/edit_question_form.php @@ -26,12 +26,12 @@ class question_edit_form extends moodleform { * * @var object */ - var $question; + public $question; - var $contexts; - var $category; - var $categorycontext; - var $coursefilesid; + public $contexts; + public $category; + public $categorycontext; + public $coursefilesid; function question_edit_form($submiturl, $question, $category, $contexts, $formeditable = true){ @@ -57,7 +57,7 @@ class question_edit_form extends moodleform { * override this method and remove the ones you don't want with $mform->removeElement(). */ function definition() { - global $COURSE, $CFG; + global $COURSE, $CFG, $DB; $qtype = $this->qtype(); $langfile = "qtype_$qtype"; @@ -151,7 +151,7 @@ class question_edit_form extends moodleform { $a = new object(); if (!empty($this->question->createdby)){ $a->time = userdate($this->question->timecreated); - $a->user = fullname(get_record('user', 'id', $this->question->createdby)); + $a->user = fullname($DB->get_record('user', array('id' => $this->question->createdby))); } else { $a->time = get_string('unknown', 'question'); $a->user = get_string('unknown', 'question'); @@ -160,7 +160,7 @@ class question_edit_form extends moodleform { if (!empty($this->question->modifiedby)){ $a = new object(); $a->time = userdate($this->question->timemodified); - $a->user = fullname(get_record('user', 'id', $this->question->modifiedby)); + $a->user = fullname($DB->get_record('user', array('id' => $this->question->modifiedby))); $mform->addElement('static', 'modified', get_string('modified', 'question'), get_string('byandon', 'question', $a)); } } @@ -259,4 +259,4 @@ class question_edit_form extends moodleform { } } -?> \ No newline at end of file +?> diff --git a/question/type/essay/questiontype.php b/question/type/essay/questiontype.php index f45eff0646..d96dddda2b 100644 --- a/question/type/essay/questiontype.php +++ b/question/type/essay/questiontype.php @@ -24,9 +24,10 @@ class question_essay_qtype extends default_questiontype { } function save_question_options($question) { + global $DB; $result = true; $update = true; - $answer = get_record("question_answers", "question", $question->id); + $answer = $DB->get_record("question_answers", array("question" => $question->id)); if (!$answer) { $answer = new stdClass; $answer->question = $question->id; @@ -36,12 +37,12 @@ class question_essay_qtype extends default_questiontype { $answer->feedback = $question->feedback; $answer->fraction = $question->fraction; if ($update) { - if (!update_record("question_answers", $answer)) { + if (!$DB->update_record("question_answers", $answer)) { $result = new stdClass; $result->error = "Could not update quiz answer!"; } } else { - if (!$answer->id = insert_record("question_answers", $answer)) { + if (!$answer->id = $DB->insert_record("question_answers", $answer)) { $result = new stdClass; $result->error = "Could not insert quiz answer!"; } diff --git a/question/type/match/questiontype.php b/question/type/match/questiontype.php index a442f74389..051a7b9184 100644 --- a/question/type/match/questiontype.php +++ b/question/type/match/questiontype.php @@ -16,15 +16,17 @@ class question_match_qtype extends default_questiontype { } function get_question_options(&$question) { - $question->options = get_record('question_match', 'question', $question->id); - $question->options->subquestions = get_records('question_match_sub', 'question', $question->id, 'id ASC'); + global $DB; + $question->options = $DB->get_record('question_match', array('question' => $question->id)); + $question->options->subquestions = $DB->get_records('question_match_sub', array('question' => $question->id), 'id ASC'); return true; } function save_question_options($question) { + global $DB; $result = new stdClass; - if (!$oldsubquestions = get_records("question_match_sub", "question", $question->id, "id ASC")) { + if (!$oldsubquestions = $DB->get_records("question_match_sub", array("question" => $question->id), "id ASC")) { $oldsubquestions = array(); } @@ -38,7 +40,7 @@ class question_match_qtype extends default_questiontype { if ($subquestion = array_shift($oldsubquestions)) { // Existing answer, so reuse it $subquestion->questiontext = $questiontext; $subquestion->answertext = $answertext; - if (!update_record("question_match_sub", $subquestion)) { + if (!$DB->update_record("question_match_sub", $subquestion)) { $result->error = "Could not insert match subquestion! (id=$subquestion->id)"; return $result; } @@ -46,13 +48,13 @@ class question_match_qtype extends default_questiontype { $subquestion = new stdClass; // Determine a unique random code $subquestion->code = rand(1,999999999); - while (record_exists('question_match_sub', 'code', $subquestion->code, 'question', $question->id)) { + while ($DB->record_exists('question_match_sub', array('code' => $subquestion->code, 'question' => $question->id))) { $subquestion->code = rand(); } $subquestion->question = $question->id; $subquestion->questiontext = $questiontext; $subquestion->answertext = $answertext; - if (!$subquestion->id = insert_record("question_match_sub", $subquestion)) { + if (!$subquestion->id = $DB->insert_record("question_match_sub", $subquestion)) { $result->error = "Could not insert match subquestion!"; return $result; } @@ -67,14 +69,14 @@ class question_match_qtype extends default_questiontype { // delete old subquestions records if (!empty($oldsubquestions)) { foreach($oldsubquestions as $os) { - delete_records('question_match_sub', 'id', $os->id); + $DB->delete_records('question_match_sub', array('id' => $os->id)); } } - if ($options = get_record("question_match", "question", $question->id)) { + if ($options = $DB->get_record("question_match", array("question" => $question->id))) { $options->subquestions = implode(",",$subquestions); $options->shuffleanswers = $question->shuffleanswers; - if (!update_record("question_match", $options)) { + if (!$DB->update_record("question_match", $options)) { $result->error = "Could not update match options! (id=$options->id)"; return $result; } @@ -83,7 +85,7 @@ class question_match_qtype extends default_questiontype { $options->question = $question->id; $options->subquestions = implode(",",$subquestions); $options->shuffleanswers = $question->shuffleanswers; - if (!insert_record("question_match", $options)) { + if (!$DB->insert_record("question_match", $options)) { $result->error = "Could not insert match options!"; return $result; } @@ -108,13 +110,15 @@ class question_match_qtype extends default_questiontype { * @param integer $question->id */ function delete_question($questionid) { - delete_records("question_match", "question", $questionid); - delete_records("question_match_sub", "question", $questionid); + global $DB; + $DB->delete_records("question_match", array("question" => $questionid)); + $DB->delete_records("question_match_sub", array("question" => $questionid)); return true; } function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) { - if (!$state->options->subquestions = get_records('question_match_sub', 'question', $question->id, 'id ASC')) { + global $DB; + if (!$state->options->subquestions = $DB->get_records('question_match_sub', array('question' => $question->id), 'id ASC')) { notify('Error: Missing subquestions!'); return false; } @@ -143,6 +147,7 @@ class question_match_qtype extends default_questiontype { } function restore_session_and_responses(&$question, &$state) { + global $DB; // The serialized format for matching questions is a comma separated // list of question answer pairs (e.g. 1-1,2-3,3-2), where the ids of // both refer to the id in the table question_match_sub. @@ -150,7 +155,7 @@ class question_match_qtype extends default_questiontype { $responses = array_map(create_function('$val', 'return explode("-", $val);'), $responses); - if (!$questions = get_records('question_match_sub', 'question', $question->id, 'id ASC')) { + if (!$questions = $DB->get_records('question_match_sub', array('question' => $question->id), 'id ASC')) { notify('Error: Missing subquestions!'); return false; } @@ -180,6 +185,7 @@ class question_match_qtype extends default_questiontype { } function save_session_and_responses(&$question, &$state) { + global $DB; $subquestions = &$state->options->subquestions; // Prepare an array to help when disambiguating equal answers. @@ -213,7 +219,7 @@ class question_match_qtype extends default_questiontype { $responses = implode(',', $responses); // Set the legacy answer field - if (!set_field('question_states', 'answer', $responses, 'id', $state->id)) { + if (!$DB->set_field('question_states', 'answer', $responses, array('id' => $state->id))) { return false; } return true; @@ -428,10 +434,10 @@ class question_match_qtype extends default_questiontype { * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { - + global $DB; $status = true; - $matchs = get_records('question_match_sub', 'question', $question, 'id ASC'); + $matchs = $DB->get_records('question_match_sub', array('question' => $question), 'id ASC'); //If there are matchs if ($matchs) { $status = fwrite ($bf,start_tag("MATCHS",6,true)); @@ -532,7 +538,7 @@ class question_match_qtype extends default_questiontype { } function restore_map($old_question_id,$new_question_id,$info,$restore) { - + global $DB; $status = true; //Get the matchs array @@ -560,9 +566,9 @@ class question_match_qtype extends default_questiontype { //mappings in backup_ids to use them later where restoring states (user level). //Get the match_sub from DB (by question, questiontext and answertext) - $db_match_sub = get_record ("question_match_sub","question",$new_question_id, - "questiontext",$match_sub->questiontext, - "answertext",$match_sub->answertext); + $db_match_sub = $DB->get_record ("question_match_sub",array("question"=>$new_question_id, + "questiontext"=>$match_sub->questiontext, + "answertext"=>$match_sub->answertext)); //Do some output if (($i+1) % 50 == 0) { if (!defined('RESTORE_SILENTLY')) { @@ -644,7 +650,7 @@ class question_match_qtype extends default_questiontype { $questiontext = restore_decode_content_links_worker($subquestion->questiontext, $restore); if ($questiontext != $subquestion->questiontext) { $subquestion->questiontext = addslashes($questiontext); - if (!update_record('question_match_sub', $subquestion)) { + if (!$DB->update_record('question_match_sub', $subquestion)) { $status = false; } } @@ -682,6 +688,7 @@ class question_match_qtype extends default_questiontype { } function replace_file_links($question, $fromcourseid, $tocourseid, $url, $destination){ + global $DB; parent::replace_file_links($question, $fromcourseid, $tocourseid, $url, $destination); // replace links in the question_match_sub table. if (isset($question->options->subquestions)){ @@ -689,7 +696,7 @@ class question_match_qtype extends default_questiontype { $subquestionchanged = false; $subquestion->questiontext = question_replace_file_links_in_html($subquestion->questiontext, $fromcourseid, $tocourseid, $url, $destination, $subquestionchanged); if ($subquestionchanged){//need to update rec in db - if (!update_record('question_match_sub', addslashes_recursive($subquestion))) { + if (!$DB->update_record('question_match_sub', $subquestion)) { print_error('Couldn\'t update \'question_match_sub\' record '.$subquestion->id); } diff --git a/question/type/multianswer/edit_multianswer_form.php b/question/type/multianswer/edit_multianswer_form.php index 09e59a38d6..6239f1f8e6 100644 --- a/question/type/multianswer/edit_multianswer_form.php +++ b/question/type/multianswer/edit_multianswer_form.php @@ -15,7 +15,7 @@ class question_edit_multianswer_form extends question_edit_form { // $questiondisplay will contain the qtype_multianswer_extract_question from the questiontext - var $questiondisplay ; + var $questiondisplay ; function definition_inner(&$mform) { $question_type_names = question_type_menu(); @@ -23,15 +23,15 @@ class question_edit_multianswer_form extends question_edit_form { // Remove meaningless defaultgrade field. $mform->removeElement('defaultgrade'); - + // display the questions from questiontext; if ( "" != optional_param('questiontext','', PARAM_RAW)) { - + $this->questiondisplay = fullclone(qtype_multianswer_extract_question(optional_param('questiontext','', PARAM_RAW))) ; - + }else { $this->questiondisplay = ""; - } + } if ( isset($this->questiondisplay->options->questions) && is_array($this->questiondisplay->options->questions) ) { $countsubquestions =0; @@ -39,7 +39,7 @@ class question_edit_multianswer_form extends question_edit_form { if ($subquestion != ''){ $countsubquestions++; } - } + } } else { $countsubquestions =0; } @@ -50,7 +50,7 @@ class question_edit_multianswer_form extends question_edit_form { for ($sub =1;$sub <=$countsubquestions ;$sub++) { $this->editas[$sub] = 'unknown type'; if (isset( $this->questiondisplay->options->questions[$sub]->qtype) ) { - $this->editas[$sub] = $this->questiondisplay->options->questions[$sub]->qtype ; + $this->editas[$sub] = $this->questiondisplay->options->questions[$sub]->qtype ; } else if (optional_param('sub_'.$sub."_".'qtype', '', PARAM_RAW) != '') { $this->editas[$sub] = optional_param('sub_'.$sub."_".'qtype', '', PARAM_RAW); } @@ -68,26 +68,27 @@ class question_edit_multianswer_form extends question_edit_form { if ($this->questiondisplay->options->questions[$sub]->qtype =='multichoice' ) { $mform->addElement('checkbox', 'sub_'.$sub."_".'layout', get_string('layout', 'quiz')) ;//, $gradeoptions); - } + } foreach ($this->questiondisplay->options->questions[$sub]->answer as $key =>$ans) { $mform->addElement('static', 'sub_'.$sub."_".'answer['.$key.']', get_string('answer', 'quiz'), array('cols'=>60, 'rows'=>1)); - + if ($this->questiondisplay->options->questions[$sub]->qtype =='numerical' && $key == 0 ) { $mform->addElement('static', 'sub_'.$sub."_".'tolerance['.$key.']', get_string('acceptederror', 'quiz')) ;//, $gradeoptions); - } + } $mform->addElement('static', 'sub_'.$sub."_".'fraction['.$key.']', get_string('grade')) ;//, $gradeoptions); $mform->addElement('static', 'sub_'.$sub."_".'feedback['.$key.']', get_string('feedback', 'quiz')); - } + } } } - + function set_data($question) { + global $DB; $default_values =array(); if (isset($question->id) and $question->id and $question->qtype and $question->questiontext) { @@ -129,7 +130,7 @@ class question_edit_multianswer_form extends question_edit_form { } $parsableanswerdef .= '}'; // Fix the questiontext fields of old questions - set_field('question', 'questiontext', addslashes($parsableanswerdef), 'id', $wrapped->id); + $DB->set_field('question', 'questiontext', $parsableanswerdef, array('id' => $wrapped->id)); } else { $parsableanswerdef = str_replace('&#', '&\#', $wrapped->questiontext); } @@ -137,13 +138,13 @@ class question_edit_multianswer_form extends question_edit_form { } } } - + // set default to $questiondisplay questions elements - if (isset($this->questiondisplay->options->questions)) { - $subquestions = fullclone($this->questiondisplay->options->questions) ; + if (isset($this->questiondisplay->options->questions)) { + $subquestions = fullclone($this->questiondisplay->options->questions) ; if (count($subquestions)) { - $sub =1; - foreach ($subquestions as $subquestion) { + $sub =1; + foreach ($subquestions as $subquestion) { $prefix = 'sub_'.$sub.'_' ; // validate parameters @@ -163,14 +164,14 @@ class question_edit_multianswer_form extends question_edit_form { } if ($subquestion->fraction[$key] == 1) { $maxgrade = true; - } + } if ($subquestion->fraction[$key] > $maxfraction) { $maxfraction = $subquestion->fraction[$key] ; } } - - $default_values[$prefix.'answer['.$key.']'] = $answer; - } + + $default_values[$prefix.'answer['.$key.']'] = $answer; + } if ($answercount == 0) { if ($subquestion->qtype == 'multichoice' ) { $this->_form->setElementError($prefix.'answer[0]' , get_string('notenoughanswers', 'qtype_multichoice', 2)); @@ -180,21 +181,21 @@ class question_edit_multianswer_form extends question_edit_form { } if ($maxgrade == false) { $this->_form->setElementError($prefix.'fraction[0]' ,get_string('fractionsnomax', 'question')); - } + } foreach ($subquestion->feedback as $key=>$answer) { - + $default_values[$prefix.'feedback['.$key.']'] = $answer; - } + } foreach ( $subquestion->fraction as $key=>$answer) { $default_values[$prefix.'fraction['.$key.']'] = $answer; - } - - - $sub++; + } + + + $sub++; } } } - if( $default_values != "") { + if( $default_values != "") { $question = (object)((array)$question + $default_values); } parent::set_data($question); @@ -202,13 +203,13 @@ class question_edit_multianswer_form extends question_edit_form { function validation($data, $files) { $errors = parent::validation($data, $files); - + if (isset($this->questiondisplay->options->questions)) { - - $subquestions = fullclone($this->questiondisplay->options->questions) ; + + $subquestions = fullclone($this->questiondisplay->options->questions) ; if (count($subquestions)) { - $sub =1; - foreach ($subquestions as $subquestion) { + $sub =1; + foreach ($subquestions as $subquestion) { $prefix = 'sub_'.$sub.'_' ; $answercount = 0; $maxgrade = false; @@ -222,12 +223,12 @@ class question_edit_multianswer_form extends question_edit_form { } if ($subquestion->fraction[$key] == 1) { $maxgrade = true; - } + } if ($subquestion->fraction[$key] > $maxfraction) { $maxfraction = $subquestion->fraction[$key] ; } - } - } + } + } if ($answercount==0) { if ( $subquestion->qtype =='multichoice' ) { $errors[$prefix.'answer[0]']= get_string('notenoughanswers', 'qtype_multichoice', 2); @@ -237,11 +238,11 @@ class question_edit_multianswer_form extends question_edit_form { } if ($maxgrade == false) { $errors[$prefix.'fraction[0]']=get_string('fractionsnomax', 'question'); - } - $sub++; + } + $sub++; } } else { - $errors['questiontext']=get_string('questionsmissing', 'qtype_multianswer'); + $errors['questiontext']=get_string('questionsmissing', 'qtype_multianswer'); } } diff --git a/question/type/multianswer/questiontype.php b/question/type/multianswer/questiontype.php index 2367509e37..c2befa6054 100644 --- a/question/type/multianswer/questiontype.php +++ b/question/type/multianswer/questiontype.php @@ -27,7 +27,7 @@ class embedded_cloze_qtype extends default_questiontype { global $QTYPES, $DB; // Get relevant data indexed by positionkey from the multianswers table - if (!$sequence = get_field('question_multianswer', 'sequence', 'question', $question->id)) { + if (!$sequence = $DB->get_field('question_multianswer', 'sequence', array('question' => $question->id))) { notify('Error: Cloze question '.$question->id.' is missing question options!'); return false; } @@ -37,7 +37,7 @@ class embedded_cloze_qtype extends default_questiontype { // 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++;')); - //si une question est manquante l,indice est nul + //si une question est manquante l,indice est nul foreach($sequence as $seq){ $question->options->questions[$seq]= ''; } @@ -49,7 +49,7 @@ class embedded_cloze_qtype extends default_questiontype { // 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? } } @@ -69,7 +69,7 @@ class embedded_cloze_qtype extends default_questiontype { // 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)) { + if (!$oldwrappedids = $DB->get_field('question_multianswer', 'sequence', array('question' => $question->id))) { $oldwrappedids = array(); } else { $oldwrappedids = $DB->get_records_list('question', 'id', explode(',', $oldwrappedids), 'id ASC','id'); @@ -79,21 +79,21 @@ class embedded_cloze_qtype extends default_questiontype { if ($wrapped != ''){ // if we still have some old wrapped question ids, reuse the next of them if (is_array($oldwrappedids) && $oldwrappedid = array_shift($oldwrappedids)) { - - if( $oldqtype = get_field('question', 'qtype', 'id',$oldwrappedid->id)){ + + if( $oldqtype = $DB->get_field('question', 'qtype', array('id' =>$oldwrappedid->id))){ $wrapped->id = $oldwrappedid->id; if($oldqtype != $wrapped->qtype ) { switch ($oldqtype) { case 'multichoice': - delete_records('question_multichoice', 'question', $oldwrappedid); + $DB->delete_records('question_multichoice', array('question' => $oldwrappedid)); $wrapped->id = $oldwrappedid; break; case 'shortanswer': - delete_records('question_shortanswer', 'question', $oldwrappedid); + $DB->delete_records('question_shortanswer', array('question' => $oldwrappedid)); $wrapped->id = $oldwrappedid; break; case 'numerical': - delete_records('question_numerical', 'question', $oldwrappedid); + $DB->delete_records('question_numerical', array('question' => $oldwrappedid)); $wrapped->id = $oldwrappedid; break; default: @@ -115,7 +115,7 @@ class embedded_cloze_qtype extends default_questiontype { } // Delete redundant wrapped questions - if(is_array($oldwrappedids) && count($oldwrappedids)){ + if(is_array($oldwrappedids) && count($oldwrappedids)){ foreach ($oldwrappedids as $id) { delete_question($id) ; } @@ -125,15 +125,15 @@ class embedded_cloze_qtype extends default_questiontype { $multianswer = new stdClass; $multianswer->question = $question->id; $multianswer->sequence = implode(',', $sequence); - if ($oldid = get_field('question_multianswer', 'id', 'question', $question->id)) { + if ($oldid = $DB->get_field('question_multianswer', 'id', array('question' => $question->id))) { $multianswer->id = $oldid; - if (!update_record("question_multianswer", $multianswer)) { + if (!$DB->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)) { + if (!$DB->insert_record("question_multianswer", $multianswer)) { $result->error = "Could not insert cloze question options!"; return $result; } @@ -182,6 +182,7 @@ class embedded_cloze_qtype extends default_questiontype { } function save_session_and_responses(&$question, &$state) { + global $DB; $responses = $state->responses; // encode - (hyphen) and , (comma) to - because they are used as // delimiters @@ -191,7 +192,7 @@ class embedded_cloze_qtype extends default_questiontype { $responses = implode(',', $responses); // Set the legacy answer field - if (!set_field('question_states', 'answer', $responses, 'id', $state->id)) { + if (!$DB->set_field('question_states', 'answer', $responses, array('id' => $state->id))) { return false; } return true; @@ -204,7 +205,8 @@ class embedded_cloze_qtype extends default_questiontype { * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_multianswer", "question", $questionid); + global $DB; + $DB->delete_records("question_multianswer", array("question" => $questionid)); return true; } @@ -282,9 +284,9 @@ class embedded_cloze_qtype extends default_questiontype { $feedbackimg = ''; $feedback = '' ; $correctanswer = ''; - $strfeedbackwrapped = $strfeedback; + $strfeedbackwrapped = $strfeedback; // if($wrapped->qtype == 'numerical' ||$wrapped->qtype == 'shortanswer'){ - $testedstate = clone($state); + $testedstate = clone($state); if ($correctanswers = $QTYPES[$wrapped->qtype]->get_correct_responses($wrapped, $testedstate)) { if ($options->readonly && $options->correct_responses) { $delimiter = ''; @@ -292,7 +294,7 @@ class embedded_cloze_qtype extends default_questiontype { foreach ($correctanswers as $ca) { switch($wrapped->qtype){ case 'numerical': - case 'shortanswer': + case 'shortanswer': $correctanswer .= $delimiter.$ca; break ; case 'multichoice': @@ -300,7 +302,7 @@ class embedded_cloze_qtype extends default_questiontype { $correctanswer .= $delimiter.$answers[$ca]->answer; } break ; - } + } $delimiter = ', '; } } @@ -364,7 +366,7 @@ class embedded_cloze_qtype extends default_questiontype { } } if ($feedback !='' && $popup == ''){ - $strfeedbackwrapped = get_string('correctanswer', 'qtype_multianswer'); + $strfeedbackwrapped = get_string('correctanswer', 'qtype_multianswer'); $feedback = s(str_replace(array("\\", "'"), array("\\\\", "\\'"), $feedback)); $popup = " onmouseover=\"return overlib('$feedback', STICKY, MOUSEOFF, CAPTION, '$strfeedbackwrapped', FGCOLOR, '#FFFFFF');\" ". " onmouseout=\"return nd();\" "; @@ -379,18 +381,18 @@ class embedded_cloze_qtype extends default_questiontype { if (strlen(trim($answer->answer)) > $size ){ $size = strlen(trim($answer->answer)); } - } + } if (strlen(trim($response))> $size ){ $size = strlen(trim($response))+1; } $size = $size + rand(0,$size*0.15); - $size > 60 ? $size = 60 : $size = $size; + $size > 60 ? $size = 60 : $size = $size; $styleinfo = "size=\"$size\""; /** * Uncomment the following lines if you want to limit for small sizes. - * Results may vary with browsers see MDL-3274 + * Results may vary with browsers see MDL-3274 */ - /* + /* if ($size < 2) { $styleinfo = 'style="width: 1.1em;"'; } @@ -404,7 +406,7 @@ class embedded_cloze_qtype extends default_questiontype { $styleinfo = 'style="width: 2.8em;"'; } */ - + echo " "; if (!empty($feedback) && !empty($USER->screenreader)) { @@ -448,7 +450,7 @@ class embedded_cloze_qtype extends default_questiontype { if(! isset($question->options->questions[$positionkey])){ echo $regs[0]; }else { - echo '
        '.get_string('questionnotfound','qtype_multianswer',$positionkey).'
        '; + echo '
        '.get_string('questionnotfound','qtype_multianswer',$positionkey).'
        '; } } } @@ -456,7 +458,7 @@ class embedded_cloze_qtype extends default_questiontype { // Print the final piece of question text: echo $qtextremaining; $this->print_question_submit_buttons($question, $state, $cmoptions, $options); - echo ''; + echo ''; } function grade_responses(&$question, &$state, $cmoptions) { @@ -513,10 +515,10 @@ class embedded_cloze_qtype extends default_questiontype { * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { - + global $DB; $status = true; - $multianswers = get_records("question_multianswer","question",$question,"id"); + $multianswers = $DB->get_records("question_multianswer",array("question" => $question),"id"); //If there are multianswers if ($multianswers) { //Print multianswers header @@ -663,6 +665,7 @@ class embedded_cloze_qtype extends default_questiontype { } function restore_recode_answer($state, $restore) { + global $DB; //The answer is a comma separated list of hypen separated sequence number and answers. We may have to recode the answers $answer_field = ""; $in_first = true; @@ -673,14 +676,14 @@ class embedded_cloze_qtype extends default_questiontype { $seqnum = $exploded[0]; $answer = $exploded[1]; // $sequence is an ordered array of the question ids. - if (!$sequence = get_field('question_multianswer', 'sequence', 'question', $state->question)) { + if (!$sequence = $DB->get_field('question_multianswer', 'sequence', array('question' => $state->question))) { print_error('missingoption', 'question', '', $state->question); } $sequence = explode(',', $sequence); // The id of the current question. $wrappedquestionid = $sequence[$seqnum-1]; // now we can find the question - if (!$wrappedquestion = get_record('question', 'id', $wrappedquestionid)) { + if (!$wrappedquestion = $DB->get_record('question', array('id' => $wrappedquestionid))) { notify("Can't find the subquestion $wrappedquestionid that is used as part $seqnum in cloze question $state->question"); } // For multichoice question we need to recode the answer diff --git a/question/type/multichoice/questiontype.php b/question/type/multichoice/questiontype.php index f154f252ea..a7dfafb89c 100644 --- a/question/type/multichoice/questiontype.php +++ b/question/type/multichoice/questiontype.php @@ -19,15 +19,16 @@ class question_multichoice_qtype extends default_questiontype { } function get_question_options(&$question) { + global $DB; // Get additional information from database // and attach it to the question object - if (!$question->options = get_record('question_multichoice', 'question', - $question->id)) { + if (!$question->options = $DB->get_record('question_multichoice', array('question' => $question->id))) { notify('Error: Missing question options for multichoice question'.$question->id.'!'); return false; } - if (!$question->options->answers = get_records_select('question_answers', 'id IN ('.$question->options->answers.')', 'id')) { + list ($usql, $params) = $DB->get_in_or_equal(explode(',', $question->options->answers)); + if (!$question->options->answers = $DB->get_records_select('question_answers', "id $usql", $params, 'id')) { notify('Error: Missing question answers for multichoice question'.$question->id.'!'); return false; } @@ -36,9 +37,9 @@ class question_multichoice_qtype extends default_questiontype { } function save_question_options($question) { + global $DB; $result = new stdClass; - if (!$oldanswers = get_records("question_answers", "question", - $question->id, "id ASC")) { + if (!$oldanswers = $DB->get_records("question_answers", array("question" => $question->id), "id ASC")) { $oldanswers = array(); } @@ -68,7 +69,7 @@ class question_multichoice_qtype extends default_questiontype { $answer->answer = $dataanswer; $answer->fraction = $question->fraction[$key]; $answer->feedback = $question->feedback[$key]; - if (!update_record("question_answers", $answer)) { + if (!$DB->update_record("question_answers", $answer)) { $result->error = "Could not update quiz answer! (id=$answer->id)"; return $result; } @@ -78,7 +79,7 @@ class question_multichoice_qtype extends default_questiontype { $answer->question = $question->id; $answer->fraction = $question->fraction[$key]; $answer->feedback = $question->feedback[$key]; - if (!$answer->id = insert_record("question_answers", $answer)) { + if (!$answer->id = $DB->insert_record("question_answers", $answer)) { $result->error = "Could not insert quiz answer! "; return $result; } @@ -95,7 +96,7 @@ class question_multichoice_qtype extends default_questiontype { } $update = true; - $options = get_record("question_multichoice", "question", $question->id); + $options = $DB->get_record("question_multichoice", array("question" => $question->id)); if (!$options) { $update = false; $options = new stdClass; @@ -110,12 +111,12 @@ class question_multichoice_qtype extends default_questiontype { $options->partiallycorrectfeedback = trim($question->partiallycorrectfeedback); $options->incorrectfeedback = trim($question->incorrectfeedback); if ($update) { - if (!update_record("question_multichoice", $options)) { + if (!$DB->update_record("question_multichoice", $options)) { $result->error = "Could not update quiz multichoice options! (id=$options->id)"; return $result; } } else { - if (!insert_record("question_multichoice", $options)) { + if (!$DB->insert_record("question_multichoice", $options)) { $result->error = "Could not insert quiz multichoice options!"; return $result; } @@ -124,7 +125,7 @@ class question_multichoice_qtype extends default_questiontype { // delete old answer records if (!empty($oldanswers)) { foreach($oldanswers as $oa) { - delete_records('question_answers', 'id', $oa->id); + $DB->delete_records('question_answers', array('id' => $oa->id)); } } @@ -153,7 +154,8 @@ class question_multichoice_qtype extends default_questiontype { * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_multichoice", "question", $questionid); + global $DB; + $DB->delete_records("question_multichoice", array("question" => $questionid)); return true; } @@ -217,6 +219,7 @@ class question_multichoice_qtype extends default_questiontype { } function save_session_and_responses(&$question, &$state) { + global $DB; // Bundle the answer order and the responses into the legacy answer // field. // The serialized format for multiple choice quetsions @@ -230,8 +233,7 @@ class question_multichoice_qtype extends default_questiontype { $responses .= implode(',', $state->responses); // Set the legacy answer field - if (!set_field('question_states', 'answer', $responses, 'id', - $state->id)) { + if (!$DB->set_field('question_states', 'answer', $responses, array('id' => $state->id))) { return false; } return true; @@ -404,10 +406,11 @@ class question_multichoice_qtype extends default_questiontype { */ function backup($bf,$preferences,$question,$level=6) { + global $DB; $status = true; - $multichoices = get_records("question_multichoice","question",$question,"id"); - //If there are multichoices + $multichoices = $DB->get_records("question_multichoice",array("question"=>$question),"id"); + $multichoices = $DB->get_records("question_multichoice",array("question" => $question),"id"); if ($multichoices) { //Iterate over each multichoice foreach ($multichoices as $multichoice) { @@ -575,7 +578,7 @@ class question_multichoice_qtype extends default_questiontype { $subquestion->correctfeedback = addslashes($correctfeedback); $subquestion->partiallycorrectfeedback = addslashes($partiallycorrectfeedback); $subquestion->incorrectfeedback = addslashes($incorrectfeedback); - if (!update_record('question_multichoice', $multichoice)) { + if (!$DB->update_record('question_multichoice', $multichoice)) { $status = false; } } @@ -646,10 +649,11 @@ class question_multichoice_qtype extends default_questiontype { } function replace_file_links($question, $fromcourseid, $tocourseid, $url, $destination){ + global $DB; parent::replace_file_links($question, $fromcourseid, $tocourseid, $url, $destination); // replace links in the question_match_sub table. // We need to use a separate object, because in load_question_options, $question->options->answers - // is changed from a comma-separated list of ids to an array, so calling update_record on + // is changed from a comma-separated list of ids to an array, so calling $DB->update_record on // $question->options stores 'Array' in that column, breaking the question. $optionschanged = false; $newoptions = new stdClass; @@ -658,7 +662,7 @@ class question_multichoice_qtype extends default_questiontype { $newoptions->partiallycorrectfeedback = question_replace_file_links_in_html($question->options->partiallycorrectfeedback, $fromcourseid, $tocourseid, $url, $destination, $optionschanged); $newoptions->incorrectfeedback = question_replace_file_links_in_html($question->options->incorrectfeedback, $fromcourseid, $tocourseid, $url, $destination, $optionschanged); if ($optionschanged){ - if (!update_record('question_multichoice', addslashes_recursive($newoptions))) { + if (!$DB->update_record('question_multichoice', $newoptions)) { print_error('Couldn\'t update \'question_multichoice\' record '.$newoptions->id); } } @@ -666,7 +670,7 @@ class question_multichoice_qtype extends default_questiontype { foreach ($question->options->answers as $answer) { $answer->answer = question_replace_file_links_in_html($answer->answer, $fromcourseid, $tocourseid, $url, $destination, $answerchanged); if ($answerchanged){ - if (!update_record('question_answers', addslashes_recursive($answer))){ + if (!$DB->update_record('question_answers', $answer)){ print_error('Couldn\'t update \'question_answers\' record '.$answer->id); } } diff --git a/question/type/numerical/questiontype.php b/question/type/numerical/questiontype.php index 96d0c797e1..73e41c09c2 100644 --- a/question/type/numerical/questiontype.php +++ b/question/type/numerical/questiontype.php @@ -31,14 +31,14 @@ class question_numerical_qtype extends question_shortanswer_qtype { // Note: question_numerical is an extension of the answer table rather than // the question table as is usually the case for qtype // specific tables. - global $CFG; - if (!$question->options->answers = get_records_sql( + global $CFG, $DB; + if (!$question->options->answers = $DB->get_records_sql( "SELECT a.*, n.tolerance " . - "FROM {$CFG->prefix}question_answers a, " . - " {$CFG->prefix}question_numerical n " . - "WHERE a.question = $question->id " . + "FROM {question_answers} a, " . + " {question_numerical} n " . + "WHERE a.question = ? " . " AND a.id = n.answer " . - "ORDER BY a.id ASC")) { + "ORDER BY a.id ASC", array($question->id))) { notify('Error: Missing question answer for numerical question ' . $question->id . '!'); return false; } @@ -60,8 +60,8 @@ class question_numerical_qtype extends question_shortanswer_qtype { } function get_numerical_units(&$question) { - if ($units = get_records('question_numerical_units', - 'question', $question->id, 'id ASC')) { + global $DB; + if ($units = $DB->get_records('question_numerical_units', array('question' => $question->id), 'id ASC')) { $units = array_values($units); } else { $units = array(); @@ -88,13 +88,13 @@ class question_numerical_qtype extends question_shortanswer_qtype { * Save the units and the answers associated with this question. */ function save_question_options($question) { - + global $DB; // Get old versions of the objects - if (!$oldanswers = get_records('question_answers', 'question', $question->id, 'id ASC')) { + if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) { $oldanswers = array(); } - if (!$oldoptions = get_records('question_numerical', 'question', $question->id, 'answer ASC')) { + if (!$oldoptions = $DB->get_records('question_numerical', array('question' => $question->id), 'answer ASC')) { $oldoptions = array(); } @@ -108,7 +108,7 @@ class question_numerical_qtype extends question_shortanswer_qtype { // Insert all the new answers foreach ($question->answer as $key => $dataanswer) { - if (!isset( $question->deleteanswer[$key] ) && !( trim($dataanswer) == 0 && $question->fraction[$key]== 0 &&trim($question->feedback[$key])=='')) { + if (!isset( $question->deleteanswer[$key] ) && !( trim($dataanswer) == 0 && $question->fraction[$key]== 0 &&trim($question->feedback[$key])=='')) { $answer = new stdClass; $answer->question = $question->id; if (trim($dataanswer) == '*') { @@ -124,12 +124,12 @@ class question_numerical_qtype extends question_shortanswer_qtype { if ($oldanswer = array_shift($oldanswers)) { // Existing answer, so reuse it $answer->id = $oldanswer->id; - if (! update_record("question_answers", $answer)) { + if (! $DB->update_record("question_answers", $answer)) { $result->error = "Could not update quiz answer! (id=$answer->id)"; return $result; } } else { // This is a completely new answer - if (! $answer->id = insert_record("question_answers", $answer)) { + if (! $answer->id = $DB->insert_record("question_answers", $answer)) { $result->error = "Could not insert quiz answer!"; return $result; } @@ -149,15 +149,15 @@ class question_numerical_qtype extends question_shortanswer_qtype { $result->notice = get_string('invalidnumerictolerance', 'quiz'); } } - + // Save options if (isset($options->id)) { // reusing existing record - if (! update_record('question_numerical', $options)) { + if (! $DB->update_record('question_numerical', $options)) { $result->error = "Could not update quiz numerical options! (id=$options->id)"; return $result; } } else { // new options - if (! insert_record('question_numerical', $options)) { + if (! $DB->insert_record('question_numerical', $options)) { $result->error = "Could not insert quiz numerical options!"; return $result; } @@ -167,14 +167,14 @@ class question_numerical_qtype extends question_shortanswer_qtype { // delete old answer records if (!empty($oldanswers)) { foreach($oldanswers as $oa) { - delete_records('question_answers', 'id', $oa->id); + $DB->delete_records('question_answers', array('id' => $oa->id)); } } // delete old answer records if (!empty($oldoptions)) { foreach($oldoptions as $oo) { - delete_records('question_numerical', 'id', $oo->id); + $DB->delete_records('question_numerical', array('id' => $oo->id)); } } @@ -182,15 +182,16 @@ class question_numerical_qtype extends question_shortanswer_qtype { if (!empty($result->notice)) { return $result; } - + return true; } function save_numerical_units($question) { + global $DB; $result = new stdClass; // Delete the units previously saved for this question. - delete_records('question_numerical_units', 'question', $question->id); + $DB->delete_records('question_numerical_units', array('question' => $question->id)); // Save the new units. $units = array(); @@ -201,7 +202,7 @@ class question_numerical_qtype extends question_shortanswer_qtype { $units[$i]->question = $question->id; $units[$i]->multiplier = $this->apply_unit($question->multiplier[$i], array()); $units[$i]->unit = $question->unit[$i]; - if (! insert_record('question_numerical_units', $units[$i])) { + if (! $DB->insert_record('question_numerical_units', $units[$i])) { $result->error = 'Unable to save unit ' . $units[$i]->unit . ' to the Databse'; return $result; } @@ -220,8 +221,9 @@ class question_numerical_qtype extends question_shortanswer_qtype { * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_numerical", "question", $questionid); - delete_records("question_numerical_units", "question", $questionid); + global $DB; + $DB->delete_records("question_numerical", array("question" => $questionid)); + $DB->delete_records("question_numerical_units", array("question" => $questionid)); return true; } @@ -330,11 +332,11 @@ class question_numerical_qtype extends question_shortanswer_qtype { $tolerance = abs($tolerance); // important - otherwise min and max are swapped // $answer->tolerance 0 or something else if ((float)$answer->tolerance == 0.0 && abs((float)$answer->answer) <= $tolerance ){ - $tolerance = (float) ("1.0e-".ini_get('precision')) * abs((float)$answer->answer) ; //tiny fraction + $tolerance = (float) ("1.0e-".ini_get('precision')) * abs((float)$answer->answer) ; //tiny fraction } else if ((float)$answer->tolerance != 0.0 && abs((float)$answer->tolerance) < abs((float)$answer->answer) && abs((float)$answer->answer) <= $tolerance){ - $tolerance = (1+("1.0e-".ini_get('precision')) )* abs((float) $answer->tolerance) ;//tiny fraction - } - + $tolerance = (1+("1.0e-".ini_get('precision')) )* abs((float) $answer->tolerance) ;//tiny fraction + } + $max = $answer->answer + $tolerance; $min = $answer->answer - $tolerance; break; @@ -371,13 +373,13 @@ class question_numerical_qtype extends question_shortanswer_qtype { $search = array(' ', ','); $replace = array('', '.'); $rawresponse = str_replace($search, $replace, trim($rawresponse)); - + // Apply any unit that is present. if (ereg('^([+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+)?)([^0-9].*)?$', $rawresponse, $responseparts)) { - + if (!empty($responseparts[5])) { - + if (isset($tmpunits[$responseparts[5]])) { // Valid number with unit. return (float)$responseparts[1] / $tmpunits[$responseparts[5]]; @@ -394,7 +396,7 @@ class question_numerical_qtype extends question_shortanswer_qtype { // Invalid number. Must be wrong. return false; } - + /// BACKUP FUNCTIONS //////////////////////////// /** @@ -403,10 +405,11 @@ class question_numerical_qtype extends question_shortanswer_qtype { * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { + global $DB; $status = true; - $numericals = get_records('question_numerical', 'question', $question, 'id ASC'); + $numericals = $DB->get_records('question_numerical', array('question' => $question), 'id ASC'); //If there are numericals if ($numericals) { //Iterate over each numerical diff --git a/question/type/questiontype.php b/question/type/questiontype.php index 8772214912..3e6882e85d 100644 --- a/question/type/questiontype.php +++ b/question/type/questiontype.php @@ -230,7 +230,7 @@ class default_questiontype { * is itself an object, shown next to the form fields. */ function save_question($question, $form, $course) { - global $USER; + global $USER, $DB; // This default implementation is suitable for most // question types. @@ -278,10 +278,10 @@ class default_questiontype { //a question to will get through the form cleaning code for the select box. } // keep existing unique stamp code - $question->stamp = get_field('question', 'stamp', 'id', $question->id); + $question->stamp = $DB->get_field('question', 'stamp', array('id' => $question->id)); $question->modifiedby = $USER->id; $question->timemodified = time(); - if (!update_record('question', $question)) { + if (!$DB->update_record('question', $question)) { print_error('cannotupdatequestion', 'question'); } } else { // Question is a new one @@ -301,7 +301,7 @@ class default_questiontype { $question->modifiedby = $USER->id; $question->timecreated = time(); $question->timemodified = time(); - if (!$question->id = insert_record('question', $question)) { + if (!$question->id = $DB->insert_record('question', $question)) { print_error('cannotinsertquestion', 'question'); } } @@ -331,7 +331,7 @@ class default_questiontype { } // Give the question a unique version stamp determined by question_hash() - if (!set_field('question', 'version', question_hash($question), 'id', $question->id)) { + if (!$DB->set_field('question', 'version', question_hash($question), array('id' => $question->id))) { print_error('cannotupdatequestionver', 'question'); } @@ -347,13 +347,14 @@ class default_questiontype { * it is not a standard question object. */ function save_question_options($question) { + global $DB; $extra_question_fields = $this->extra_question_fields(); if (is_array($extra_question_fields)) { $question_extension_table = array_shift($extra_question_fields); $function = 'update_record'; - $options = get_record($question_extension_table, 'questionid', $question->id); + $options = $DB->get_record($question_extension_table, array('questionid' => $question->id)); if (!$options) { $function = 'insert_record'; $options = new stdClass; @@ -369,7 +370,7 @@ class default_questiontype { $options->$field = $question->$field; } - if (!$function($question_extension_table, $options)) { + if (!$DB->{$function}($question_extension_table, $options)) { $result = new stdClass; $result->error = 'Could not save question options for ' . $this->name() . ' question id ' . $question->id; @@ -416,7 +417,7 @@ class default_questiontype { * specific information (it is passed by reference). */ function get_question_options(&$question) { - global $CFG; + global $CFG, $DB; if (!isset($question->options)) { $question->options = new object; @@ -425,7 +426,7 @@ class default_questiontype { $extra_question_fields = $this->extra_question_fields(); if (is_array($extra_question_fields)) { $question_extension_table = array_shift($extra_question_fields); - $extra_data = get_record($question_extension_table, 'questionid', $question->id, '', '', '', '', implode(', ', $extra_question_fields)); + $extra_data = $DB->get_record($question_extension_table, array('questionid' => $question->id), '', implode(', ', $extra_question_fields)); if ($extra_data) { foreach ($extra_question_fields as $field) { $question->options->$field = $extra_data->$field; @@ -440,10 +441,10 @@ class default_questiontype { $extra_answer_fields = $this->extra_answer_fields(); if (is_array($extra_answer_fields)) { $answer_extension_table = array_shift($extra_answer_fields); - $question->options->answers = get_records_sql(' - SELECT qa.*, qax.' . implode(', qax.', $extra_answer_fields) . ' - FROM ' . $CFG->prefix . 'question_answers qa, ' . $CFG->prefix . '$answer_extension_table qax - WHERE qa.questionid = ' . $question->id . ' AND qax.answerid = qa.id'); + $question->options->answers = $DB->get_records_sql(" + SELECT qa.*, qax." . implode(', qax.', $extra_answer_fields) . " + FROM {question_answers} qa, {$answer_extension_table} qax + WHERE qa.questionid = ? AND qax.answerid = qa.id", array($question->id)); if (!$question->options->answers) { notify("Failed to load question answers from the table $answer_extension_table for questionid " . $question->id); @@ -451,7 +452,7 @@ class default_questiontype { } } else { // Don't check for success or failure because some question types do not use the answers table. - $question->options->answers = get_records('question_answers', 'question', $question->id, 'id ASC'); + $question->options->answers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC'); } return true; @@ -476,23 +477,23 @@ class default_questiontype { * @param object $question The question being deleted */ function delete_question($questionid) { - global $CFG; + global $CFG, $DB; $success = true; $extra_question_fields = $this->extra_question_fields(); if (is_array($extra_question_fields)) { $question_extension_table = array_shift($extra_question_fields); - $success = $success && delete_records($question_extension_table, 'questionid', $questionid); + $success = $success && $DB->delete_records($question_extension_table, array('questionid' => $questionid)); } $extra_answer_fields = $this->extra_answer_fields(); if (is_array($extra_answer_fields)) { $answer_extension_table = array_shift($extra_answer_fields); - $success = $success && delete_records_select($answer_extension_table, - "answerid IN (SELECT qa.id FROM {$CFG->prefix}question_answers qa WHERE qa.question = $questionid)"); + $success = $success && $DB->delete_records_select($answer_extension_table, + "answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)", array($questionid)); } - $success = $success && delete_records('question_answers', 'question', $questionid); + $success = $success && $DB->delete_records('question_answers', array('question' => $questionid)); return $success; } @@ -595,7 +596,7 @@ class default_questiontype { * which is contained in ->responses[''] will not have to save this response, * it will already have been saved to the answer field of the question_states table. * Question types with more response fields should override this method to convert - * the data the ->responses array into a single string field, and save it in the + * the data the ->responses array into a single string field, and save it in the * database. The implementation in the multichoice question type is a good model to follow. * http://cvs.moodle.org/contrib/plugins/question/type/opaque/questiontype.php?view=markup * has a solution that is probably quite generally applicable. @@ -871,14 +872,15 @@ class default_questiontype { * Used by print_question() */ function history($question, $state, $number, $cmoptions, $options) { + global $DB; $history = ''; if(isset($options->history) and $options->history) { if ($options->history == 'all') { // show all states - $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number ASC'); + $states = $DB->get_records_select('question_states', "attempt = ? AND question = ? AND event > '0'", array($state->attempt, $question->id), 'seq_number ASC'); } else { // show only graded states - $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event IN (".QUESTION_EVENTS_GRADED.")", 'seq_number ASC'); + $states = $DB->get_records_select('question_states', "attempt = ? AND question = ? AND event IN (".QUESTION_EVENTS_GRADED.")", 'seq_number ASC', array($state->attempt, $question->id)); } if (count($states) > 1) { $strreviewquestion = get_string('reviewresponse', 'quiz'); @@ -1332,7 +1334,7 @@ class default_questiontype { // get quizzes using the question (using the question_instances table) $quizlist = array(); - if(!$instances = get_records('quiz_question_instances', 'question', $question->id)) { + if(!$instances = $DB->get_records('quiz_question_instances', array('question' => $question->id))) { $instances = array(); } foreach($instances as $instance) { @@ -1367,9 +1369,9 @@ class default_questiontype { // 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'")) { + if($attempts = $DB->get_records_select('quiz_attempts', "quiz = ? AND preview = '0'", array($quiz->id))) { foreach($attempts as $attempt) { - if (record_exists('question_states', 'attempt', $attempt->uniqueid, 'question', $question->id, 'originalquestion', 0)) { + if ($DB->record_exists('question_states', array('attempt' => $attempt->uniqueid, 'question' => $question->id), 'originalquestion', 0)) { $students[$attempt->userid] = 1; } } @@ -1482,7 +1484,7 @@ class default_questiontype { * @return array of files, file name is key and array with one item = question id as value */ function replace_file_links($question, $fromcourseid, $tocourseid, $url, $destination){ - global $CFG; + global $CFG, $DB; $updateqrec = false; /// Question image @@ -1505,7 +1507,7 @@ class default_questiontype { /// If anything has changed, update it in the database. if ($updateqrec){ - if (!update_record('question', addslashes_recursive($question))){ + if (!$DB->update_record('question', $question)){ error ('Couldn\'t update question '.$question->name); } } @@ -1524,7 +1526,7 @@ class default_questiontype { $answer->feedback = question_replace_file_links_in_html($answer->feedback, $fromcourseid, $tocourseid, $url, $destination, $answerchanged); /// If anything has changed, update it in the database. if ($answerchanged){ - if (!update_record('question_answers', addslashes_recursive($answer))){ + if (!$DB->update_record('question_answers', $answer)){ error ('Couldn\'t update question ('.$question->name.') answer '.$answer->id); } } diff --git a/question/type/random/questiontype.php b/question/type/random/questiontype.php index 75ab2da7b4..a4ab63a738 100644 --- a/question/type/random/questiontype.php +++ b/question/type/random/questiontype.php @@ -1,12 +1,12 @@ category); if (isset($question->id) && $formcategory != $question->category) { @@ -53,25 +54,26 @@ class random_qtype extends default_questiontype { } $form->name = ''; $question = parent::save_question($question, $form, $course); - if (!$category = get_record('question_categories', 'id', $question->category)) { + if (!$category = $DB->get_record('question_categories', array('id' => $question->category))) { print_error('cannotretrieveqcat', 'question'); } $question->name = $this->question_name($category); - if (!set_field('question', 'name', addslashes($question->name), 'id', $question->id)) { + if (!$DB->set_field('question', 'name', $question->name, array('id', $question->id))) { print_error('cannotupdaterandomqname', 'question'); } return $question; } function save_question_options($question) { + global $DB; // No options, but we set the parent field to the question's own id. // Setting the parent field has the effect of hiding this question in // various places. - return (set_field('question', 'parent', $question->id, 'id', - $question->id) ? true : false); + return ($DB->set_field('question', 'parent', $question->id, array('id' => $question->id)) ? true : false); } function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) { + global $DB; global $QTYPE_EXCLUDE_FROM_RANDOM; // Choose a random question from the category: // We need to make sure that no question is used more than once in the @@ -94,7 +96,7 @@ class random_qtype extends default_questiontype { } else { $categorylist = $question->category; } - if ($catrandoms = get_records_select('question', + if ($catrandoms = $DB->get_records_select('question', "category IN ($categorylist) AND parent = '0' AND hidden = '0' @@ -112,7 +114,7 @@ class random_qtype extends default_questiontype { if (!ereg("(^|,)$wrappedquestion->id(,|$)", $cmoptions->questionsinuse)) { /// $randomquestion is not in use and will therefore be used /// as the randomquestion here... - $wrappedquestion = get_record('question', 'id', $wrappedquestion->id); + $wrappedquestion = $DB->get_record('question', array('id' => $wrappedquestion->id)); global $QTYPES; $QTYPES[$wrappedquestion->qtype] ->get_question_options($wrappedquestion); @@ -150,7 +152,7 @@ class random_qtype extends default_questiontype { /// From version 1.5 and later the question type random works like all /// the other question types in that it now only needs one response /// record per question. - global $QTYPES; + global $QTYPES, $DB; if (!ereg('^random([0-9]+)-(.*)$', $state->responses[''], $answerregs)) { if (empty($state->responses[''])) { // This is the case if there weren't enough questions available in the category. @@ -160,16 +162,16 @@ class random_qtype extends default_questiontype { return true; } // this must be an old-style state which stores only the id for the wrapped question - if (!$wrappedquestion = get_record('question', 'id', $state->responses[''])) { + if (!$wrappedquestion = $DB->get_record('question', array('id' => $state->responses['']))) { notify("Can not find wrapped question {$state->responses['']}"); } // In the old model the actual response was stored in a separate entry in // the state table and fortunately there was only a single state per question - if (!$state->responses[''] = get_field('question_states', 'answer', 'attempt', $state->attempt, 'question', $wrappedquestion->id)) { + if (!$state->responses[''] = $DB->get_field('question_states', 'answer', array('attempt' => $state->attempt, 'question' => $wrappedquestion->id))) { notify("Wrapped state missing"); } } else { - if (!$wrappedquestion = get_record('question', 'id', $answerregs[1])) { + if (!$wrappedquestion = $DB->get_record('question', array('id' => $answerregs[1]))) { // The teacher must have deleted this question by mistake // Convert it into a description type question with an explanation to the student $wrappedquestion = clone($question); @@ -196,7 +198,7 @@ class random_qtype extends default_questiontype { } function save_session_and_responses(&$question, &$state) { - global $QTYPES; + global $QTYPES, $DB; $wrappedquestion = &$state->options->question; // Trick the wrapped question into pretending to be the random one. @@ -207,7 +209,7 @@ class random_qtype extends default_questiontype { // Read what the wrapped question has just set the answer field to // (if anything) - $response = get_field('question_states', 'answer', 'id', $state->id); + $response = $DB->get_field('question_states', 'answer', array('id' => $state->id)); if(false === $response) { return false; } @@ -216,8 +218,7 @@ class random_qtype extends default_questiontype { $response = "random$realqid-$response"; // ... and save it again. - if (!set_field('question_states', 'answer', addslashes($response), 'id', $state->id)) { - return false; + if (!$DB->set_field('question_states', 'answer', $response, array('id' => $state->id))) { } // Restore the real id @@ -293,7 +294,7 @@ class random_qtype extends default_questiontype { // state of the random question and store the response // in a separate state for the wrapped question - global $QTYPES; + global $QTYPES, $DB; $answer_field = ""; if (ereg('^random([0-9]+)-(.*)$', $state->answer, $answerregs)) { @@ -304,7 +305,7 @@ class random_qtype extends default_questiontype { return($answer_field); } // Get the question type for recursion - if (!$wrappedquestion->qtype = get_field('question', 'qtype', 'id', $wrapped->new_id)) { + if (!$wrappedquestion->qtype = $DB->get_field('question', 'qtype', array('id' => $wrapped->new_id))) { echo 'Could not get qtype while recoding question random-'.$answerregs[1].'
        '; return($answer_field); } diff --git a/question/type/randomsamatch/edit_randomsamatch_form.php b/question/type/randomsamatch/edit_randomsamatch_form.php index d03fcc4ecc..21919fc3f2 100644 --- a/question/type/randomsamatch/edit_randomsamatch_form.php +++ b/question/type/randomsamatch/edit_randomsamatch_form.php @@ -48,24 +48,24 @@ class question_edit_randomsamatch_form extends question_edit_form { } function validation($data, $files) { - global $QTYPES; + global $QTYPES, $DB; $errors = parent::validation($data, $files); if (isset($data['usecurrentcat'])){ $category = $data['category']; }else{ $category = $data['categorymoveto']; } - + $saquestions = $QTYPES['randomsamatch']->get_sa_candidates($category); $numberavailable = count($saquestions); if ($saquestions === false){ $a = new object(); - $a->catname = get_field('question_categories', 'name', 'id', $category); + $a->catname = $DB->get_field('question_categories', 'name', array('id' => $category)); $errors['choose'] = get_string('nosaincategory', 'qtype_randomsamatch', $a); } elseif ($numberavailable < $data['choose']){ $a = new object(); - $a->catname = get_field('question_categories', 'name', 'id', $category); + $a->catname = $DB->get_field('question_categories', 'name', array('id' => $category)); $a->nosaquestions = $numberavailable; $errors['choose'] = get_string('notenoughsaincategory', 'qtype_randomsamatch', $a); } @@ -74,4 +74,4 @@ class question_edit_randomsamatch_form extends question_edit_form { } } -?> \ No newline at end of file +?> diff --git a/question/type/randomsamatch/questiontype.php b/question/type/randomsamatch/questiontype.php index 4700b20349..3350f67baf 100644 --- a/question/type/randomsamatch/questiontype.php +++ b/question/type/randomsamatch/questiontype.php @@ -24,7 +24,8 @@ class question_randomsamatch_qtype extends question_match_qtype { } function get_question_options(&$question) { - if (!$question->options = get_record('question_randomsamatch', 'question', $question->id)) { + global $DB; + if (!$question->options = $DB->get_record('question_randomsamatch', array('question' => $question->id))) { notify('Error: Missing question options for random short answer question '.$question->id.'!'); return false; } @@ -38,6 +39,7 @@ class question_randomsamatch_qtype extends question_match_qtype { } function save_question_options($question) { + global $DB; $options->question = $question->id; $options->choose = $question->choose; @@ -46,15 +48,14 @@ class question_randomsamatch_qtype extends question_match_qtype { return $result; } - if ($existing = get_record("question_randomsamatch", - "question", $options->question)) { + if ($existing = $DB->get_record("question_randomsamatch", array("question" => $options->question))) { $options->id = $existing->id; - if (!update_record("question_randomsamatch", $options)) { + if (!$DB->update_record("question_randomsamatch", $options)) { $result->error = "Could not update quiz randomsamatch options!"; return $result; } } else { - if (!insert_record("question_randomsamatch", $options)) { + if (!$DB->insert_record("question_randomsamatch", $options)) { $result->error = "Could not insert quiz randomsamatch options!"; return $result; } @@ -69,7 +70,8 @@ class question_randomsamatch_qtype extends question_match_qtype { * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_randomsamatch", "question", $questionid); + global $DB; + $DB->delete_records("question_randomsamatch", array("question" => $questionid)); return true; } @@ -170,6 +172,7 @@ class question_randomsamatch_qtype extends question_match_qtype { } function restore_session_and_responses(&$question, &$state) { + global $DB; global $QTYPES; if (empty($state->responses[''])) { $question->questiontext = "Insufficient selection options are @@ -186,8 +189,7 @@ class question_randomsamatch_qtype extends question_match_qtype { $state->responses = array(); foreach ($responses as $response) { $state->responses[$response[0]] = $response[1]; - if (!$wrappedquestion = get_record('question', 'id', - $response[0])) { + if (!$wrappedquestion = $DB->get_record('question', array('id' => $response[0]))) { notify("Couldn't get question (id=$response[0])!"); return false; } @@ -239,12 +241,16 @@ class question_randomsamatch_qtype extends question_match_qtype { } function get_sa_candidates($categorylist, $questionsinuse=0) { - return get_records_select('question', - "qtype = '".'shortanswer'."' " . - "AND category IN ($categorylist) " . + global $DB; + list ($usql, $params) = $DB->get_in_or_equal(explode(',', $categorylist)); + list ($ques_usql, $ques_params) = $DB->get_in_or_equal(explode(',', $questionsinuse), SQL_PARAMS_QM, null, false); + $params = array_merge($params, $ques_params); + return $DB->get_records_select('question', + "qtype = 'shortanswer' " . + "AND category $usql " . "AND parent = '0' " . "AND hidden = '0'" . - "AND id NOT IN ($questionsinuse)"); + "AND id $ques_usql", $params); } function get_all_responses($question, $state) { $answers = array(); @@ -253,7 +259,7 @@ class question_randomsamatch_qtype extends question_match_qtype { if ($answer->questiontext) { foreach($answer->options->answers as $ans ){ $answer->answertext = $ans->answer ; - } + } $r = new stdClass; $r->answer = $answer->questiontext . ": " . $answer->answertext; $r->credit = 1; @@ -266,7 +272,7 @@ class question_randomsamatch_qtype extends question_match_qtype { $result->responses = $answers; return $result; } - + /// BACKUP FUNCTIONS //////////////////////////// /* @@ -275,10 +281,11 @@ class question_randomsamatch_qtype extends question_match_qtype { * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { + global $DB; $status = true; - $randomsamatchs = get_records("question_randomsamatch","question",$question,"id"); + $randomsamatchs = $DB->get_records("question_randomsamatch",array("question" => $question),"id"); //If there are randomsamatchs if ($randomsamatchs) { //Iterate over each randomsamatch @@ -352,7 +359,7 @@ class question_randomsamatch_qtype extends question_match_qtype { if (!$que = backup_getid($restore->backup_unique_code,"question",$question_id)) { echo 'Could not recode randomsamatch question '.$question_id.'
        '; } - + if ($answer_id == 0) { // no response yet $ans->new_id = 0; } else { diff --git a/question/type/shortanswer/questiontype.php b/question/type/shortanswer/questiontype.php index 7ba83ac624..830959519b 100644 --- a/question/type/shortanswer/questiontype.php +++ b/question/type/shortanswer/questiontype.php @@ -23,15 +23,15 @@ class question_shortanswer_qtype extends default_questiontype { } function get_question_options(&$question) { + global $DB; // Get additional information from database // and attach it to the question object - if (!$question->options = get_record('question_shortanswer', 'question', $question->id)) { + if (!$question->options = $DB->get_record('question_shortanswer', array('question' => $question->id))) { notify('Error: Missing question options!'); return false; } - if (!$question->options->answers = get_records('question_answers', 'question', - $question->id, 'id ASC')) { + if (!$question->options->answers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) { notify('Error: Missing question answers for shortanswer question ' . $question->id . '!'); return false; } @@ -39,9 +39,10 @@ class question_shortanswer_qtype extends default_questiontype { } function save_question_options($question) { + global $DB; $result = new stdClass; - if (!$oldanswers = get_records('question_answers', 'question', $question->id, 'id ASC')) { + if (!$oldanswers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) { $oldanswers = array(); } @@ -56,7 +57,7 @@ class question_shortanswer_qtype extends default_questiontype { $answer->answer = trim($dataanswer); $answer->fraction = $question->fraction[$key]; $answer->feedback = $question->feedback[$key]; - if (!update_record("question_answers", $answer)) { + if (!$DB->update_record("question_answers", $answer)) { $result->error = "Could not update quiz answer! (id=$answer->id)"; return $result; } @@ -66,7 +67,7 @@ class question_shortanswer_qtype extends default_questiontype { $answer->question = $question->id; $answer->fraction = $question->fraction[$key]; $answer->feedback = $question->feedback[$key]; - if (!$answer->id = insert_record("question_answers", $answer)) { + if (!$answer->id = $DB->insert_record("question_answers", $answer)) { $result->error = "Could not insert quiz answer!"; return $result; } @@ -78,10 +79,10 @@ class question_shortanswer_qtype extends default_questiontype { } } - if ($options = get_record("question_shortanswer", "question", $question->id)) { + if ($options = $DB->get_record("question_shortanswer", array("question" => $question->id))) { $options->answers = implode(",",$answers); $options->usecase = $question->usecase; - if (!update_record("question_shortanswer", $options)) { + if (!$DB->update_record("question_shortanswer", $options)) { $result->error = "Could not update quiz shortanswer options! (id=$options->id)"; return $result; } @@ -90,7 +91,7 @@ class question_shortanswer_qtype extends default_questiontype { $options->question = $question->id; $options->answers = implode(",",$answers); $options->usecase = $question->usecase; - if (!insert_record("question_shortanswer", $options)) { + if (!$DB->insert_record("question_shortanswer", $options)) { $result->error = "Could not insert quiz shortanswer options!"; return $result; } @@ -99,7 +100,7 @@ class question_shortanswer_qtype extends default_questiontype { // delete old answer records if (!empty($oldanswers)) { foreach($oldanswers as $oa) { - delete_records('question_answers', 'id', $oa->id); + $DB->delete_records('question_answers', array('id' => $oa->id)); } } @@ -120,7 +121,8 @@ class question_shortanswer_qtype extends default_questiontype { * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_shortanswer", "question", $questionid); + global $DB; + $DB->delete_records("question_shortanswer", array("question" => $questionid)); return true; } @@ -246,10 +248,11 @@ class question_shortanswer_qtype extends default_questiontype { * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { + global $DB; $status = true; - $shortanswers = get_records('question_shortanswer', 'question', $question, 'id ASC'); + $shortanswers = $DB->get_records('question_shortanswer', array('question' => $question), 'id ASC'); //If there are shortanswers if ($shortanswers) { //Iterate over each shortanswer diff --git a/question/type/truefalse/questiontype.php b/question/type/truefalse/questiontype.php index 25b5aca7ae..ef01281dab 100644 --- a/question/type/truefalse/questiontype.php +++ b/question/type/truefalse/questiontype.php @@ -16,10 +16,11 @@ class question_truefalse_qtype extends default_questiontype { } function save_question_options($question) { + global $DB; $result = new stdClass; // fetch old answer ids so that we can reuse them - if (!$oldanswers = get_records("question_answers", "question", $question->id, "id ASC")) { + if (!$oldanswers = $DB->get_records("question_answers", array("question" => $question->id), "id ASC")) { $oldanswers = array(); } @@ -28,7 +29,7 @@ class question_truefalse_qtype extends default_questiontype { $true->answer = get_string("true", "quiz"); $true->fraction = $question->correctanswer; $true->feedback = $question->feedbacktrue; - if (!update_record("question_answers", $true)) { + if (!$DB->update_record("question_answers", $true)) { $result->error = "Could not update quiz answer \"true\")!"; return $result; } @@ -38,7 +39,7 @@ class question_truefalse_qtype extends default_questiontype { $true->question = $question->id; $true->fraction = $question->correctanswer; $true->feedback = $question->feedbacktrue; - if (!$true->id = insert_record("question_answers", $true)) { + if (!$true->id = $DB->insert_record("question_answers", $true)) { $result->error = "Could not insert quiz answer \"true\")!"; return $result; } @@ -49,7 +50,7 @@ class question_truefalse_qtype extends default_questiontype { $false->answer = get_string("false", "quiz"); $false->fraction = 1 - (int)$question->correctanswer; $false->feedback = $question->feedbackfalse; - if (!update_record("question_answers", $false)) { + if (!$DB->update_record("question_answers", $false)) { $result->error = "Could not insert quiz answer \"false\")!"; return $result; } @@ -59,7 +60,7 @@ class question_truefalse_qtype extends default_questiontype { $false->question = $question->id; $false->fraction = 1 - (int)$question->correctanswer; $false->feedback = $question->feedbackfalse; - if (!$false->id = insert_record("question_answers", $false)) { + if (!$false->id = $DB->insert_record("question_answers", $false)) { $result->error = "Could not insert quiz answer \"false\")!"; return $result; } @@ -68,17 +69,17 @@ class question_truefalse_qtype extends default_questiontype { // delete any leftover old answer records (there couldn't really be any, but who knows) if (!empty($oldanswers)) { foreach($oldanswers as $oa) { - delete_records('question_answers', 'id', $oa->id); + $DB->delete_records('question_answers', array('id' => $oa->id)); } } // Save question options in question_truefalse table - if ($options = get_record("question_truefalse", "question", $question->id)) { + if ($options = $DB->get_record("question_truefalse", array("question" => $question->id))) { // No need to do anything, since the answer IDs won't have changed // But we'll do it anyway, just for robustness $options->trueanswer = $true->id; $options->falseanswer = $false->id; - if (!update_record("question_truefalse", $options)) { + if (!$DB->update_record("question_truefalse", $options)) { $result->error = "Could not update quiz truefalse options! (id=$options->id)"; return $result; } @@ -87,7 +88,7 @@ class question_truefalse_qtype extends default_questiontype { $options->question = $question->id; $options->trueanswer = $true->id; $options->falseanswer = $false->id; - if (!insert_record("question_truefalse", $options)) { + if (!$DB->insert_record("question_truefalse", $options)) { $result->error = "Could not insert quiz truefalse options!"; return $result; } @@ -99,14 +100,15 @@ class question_truefalse_qtype extends default_questiontype { * Loads the question type specific options for the question. */ function get_question_options(&$question) { + global $DB; // Get additional information from database // and attach it to the question object - if (!$question->options = get_record('question_truefalse', 'question', $question->id)) { + if (!$question->options = $DB->get_record('question_truefalse', array('question' => $question->id))) { notify('Error: Missing question options!'); return false; } // Load the answers - if (!$question->options->answers = get_records('question_answers', 'question', $question->id, 'id ASC')) { + if (!$question->options->answers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC')) { notify('Error: Missing question answers for truefalse question ' . $question->id . '!'); return false; } @@ -121,7 +123,8 @@ class question_truefalse_qtype extends default_questiontype { * @param object $question The question being deleted */ function delete_question($questionid) { - delete_records("question_truefalse", "question", $questionid); + global $DB; + $DB->delete_records("question_truefalse", array("question" => $questionid)); return true; } @@ -251,10 +254,11 @@ class question_truefalse_qtype extends default_questiontype { * This is used in question/backuplib.php */ function backup($bf,$preferences,$question,$level=6) { + global $DB; $status = true; - $truefalses = get_records("question_truefalse","question",$question,"id"); + $truefalses = $DB->get_records("question_truefalse",array("question" => $question),"id"); //If there are truefalses if ($truefalses) { //Iterate over each truefalse diff --git a/question/upgrade.php b/question/upgrade.php index d7d6c03b37..ab51ad7c9e 100644 --- a/question/upgrade.php +++ b/question/upgrade.php @@ -19,9 +19,8 @@ * that is what this update does. */ function question_fix_random_question_parents() { - global $CFG; - return execute_sql('UPDATE ' . $CFG->prefix . 'question SET parent = id ' . - "WHERE qtype = 'random' AND parent <> id"); + global $CFG, $DB; + return $DB->execute("UPDATE {question} SET parent = id WHERE qtype = 'random' AND parent <> id"); } ?>