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];
}
}
set_error_handler('SimpleTestErrorHandler');
}
}
-?>
\ No newline at end of file
+?>
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;
$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;
// 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;
$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);
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 {
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);
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'),
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'];
*
* 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);
/**
* 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);
* Displays the user interface
*
*/
- function display_user_interface() {
+ public function display_user_interface() {
/// Interface for editing existing categories
$this->output_edit_lists();
/**
* Outputs a table to allow entry of a new category
*/
- function output_new_table() {
+ public function output_new_table() {
$this->catform->display();
}
* $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));
* @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;
- 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');
* @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)) {
* @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;
}
*
* @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;
$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)) {
* 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');
}
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));
}
}
$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
* 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){
$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?'.
}
}
- 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){
class question_category_edit_form extends moodleform {
function definition() {
- global $CFG;
+ global $CFG, $DB;
$mform =& $this->_form;
$contexts = $this->_customdata['contexts'];
$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'));
$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;
$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){
$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){
}
//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){
}
$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++;
$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');
}
$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);
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;
*/
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();
}
// 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) {
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) {
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);
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;
}
// 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 "<p style=\"text-align:center;\">";
print_string("noquestions", "quiz");
echo "</p>";
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 "<p style=\"text-align:center;\">";
print_string("noquestions", "quiz");
}
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);
}
}
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;
// 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');
}
// 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());
* @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
$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).'<br />';
+ $questionnames .= $DB->get_field('question', 'name', array('id' => $key)).'<br />';
}
}
if (!$questionlist) { // no questions were selected
* @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.
$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 {
* 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 {
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);
// 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');
}
// 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)) {
* @return boolean success
*/
function importprocess() {
- global $USER;
+ global $USER, $DB;
// reset the timer in case file upload was slow
@set_time_limit();
$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');
}
}
// 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;
* @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;
$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);
$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;
* @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;
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}";
}
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
$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
$question->questiontext = addslashes(trim($qrec[2]));
$question->name = preg_replace("/<br />/", "", $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;
notify("Misformatted Record. Question Skipped.");
break;
}
- if ($question) {
- $questions[] = $question;
+ if ($question) {
+ $questions[] = $question;
}
}
$count = 0;
$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;
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;
}
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;
}
}
}
//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;
}
}
require_once("$CFG->libdir/xmlize.php");
class qformat_examview extends qformat_default {
-
- var $qtypes = array(
+
+ public $qtypes = array(
'tf' => TRUEFALSE,
'mc' => MULTICHOICE,
'yn' => TRUEFALSE,
'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
$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 );
}
}
$text = strip_tags($text);
return $text;
}
-
+
function parse_matching_groups($matching_groups)
{
if (empty($matching_groups)) {
$this->matching_questions[$groupname] = $newgroup;
}
}
-
+
function parse_ma($qrec, $groupname)
{
$match_group = $this->matching_questions[$groupname];
$this->matching_questions[$groupname] = $match_group;
return NULL;
}
-
+
function process_matches(&$questions)
{
if (empty($this->matching_questions)) {
$questions[] = $question;
}
}
-
+
function cleanUnicode($text) {
return str_replace('’', "'", $text);
}
$questions = array();
$currentquestion = array();
-
+
$text = implode($lines, ' ');
$text = $this->cleanUnicode($text);
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)) {
$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);
$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 );
}
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;
}
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) {
$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)) {
}
}
return $question;
- }
-
+ }
+
}
// end class
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';
}
function writetext( $raw ) {
- // generates <text></text> tags, processing raw text therein
-
- // for now, don't allow any additional tags in text
+ // generates <text></text> 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 "<text>$raw</text>\n";
}
-
+
/**
* flattens $object['media'], copies $object['media'] to $path, and sets $object['mediamimetype']
* @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'])) {
}
}
return true;
-}
+}
/**
* copies all files needed by the questions to the given $path, and flattens the file names
*
* @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;
}
}
}
-
+
return empty($errors) ? true : $errors;
}
*
* @param string $filename the directory name which will hold the exported files
* @return boolean - or errors out
- */
+ */
function exportprocess() {
global $CFG;
$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("<br />", $result));
}
-
+
$manifestquestions = $this->objects_to_array($questions);
$manifestid = str_replace(array(':', '/'), array('-','_'), "question_category_{$this->category->id}---{$CFG->wwwroot}");
$smarty->assign('externalfiles', 1);
// iterate through questions
foreach($questions as $question) {
-
+
// results are first written into string (and then to a file)
$count++;
echo "<hr /><p><b>$count</b>. ".stripslashes($question->questiontext)."</p>";
$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);
print_error('cannotwriteto', 'question', '', $filepath);
}
fclose($fh);
-
+
}
// zip files into single export file
// remove the temporary directory
remove_dir( $path );
-
+
return true;
}
-
+
/**
* exports a quiz (as opposed to exporting a category of questions)
*
* @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);
}
}
-
+
/**
* This function is called to export a quiz (as opposed to exporting a category of questions)
* @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;
$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
return true;
}
-
-
+
+
/**
* Prepares questions for quiz export
* @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
$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) {
$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;
}
/**
* 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) {
$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);
$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
*
*
* @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) {
* @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 = '<a><br><b><h1><h2><h3><h4><i><img><li><ol><strong><table><tr><td><th><u><ul><object>'; // all other tags will be stripped from question text
$smarty =& $this->init_smarty();
$assesmentitemid = $this->get_assesment_item_id($question);
$smarty->assign('assessmentitemidentifier', $assesmentitemid);
$smarty->assign('assessmentitemtitle', $question->name);
$smarty->assign('courselevelexport', $courselevel);
-
+
if ($question->qtype == MULTIANSWER) {
$question->questiontext = strip_tags($question->questiontext, $allowedtags . '<intro>');
$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:
$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) {
else {
$correctresponse = '';
}
-
+
$smarty->assign('correctresponse', $correctresponse);
$smarty->assign('answers', $answers);
$expout = $smarty->fetch('choice.tpl');
$correctresponses = $this->get_correct_answers($answers);
$correctcount = count($correctresponses);
-
+
$smarty->assign('responsedeclarationcardinality', $correctcount > 1 ? 'multiple' : 'single');
$smarty->assign('correctresponses', $correctresponses);
$smarty->assign('answers', $answers);
if (!empty($shuffleanswers)) {
$answers = $this->shuffle_things($answers);
}
-
+
$correctresponses = $this->get_correct_answers($answers);
$correctcount = count($correctresponses);
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:
$subquestions = $this->shuffle_things($subquestions);
}
$setcount = count($subquestions);
-
+
$smarty->assign('setcount', $setcount);
$smarty->assign('matchsets', $subquestions);
$expout = $smarty->fetch('match.tpl');
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');
$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;
*
* @param object $question
* @return string containing a qti assesment item id
- */
+ */
function get_assesment_item_id($question) {
return "question{$question->id}";
}
*
* @param array $answers
* @return array (0-indexed) containing the answers whose grade fraction > 0
- */
+ */
function get_correct_answers($answers)
{
$correctanswers = array();
* gets a new Smarty object, with the template and compile directories set
*
* @return object a smarty object
- */
+ */
function & init_smarty() {
global $CFG;
*
* @param array $objectarray
* @return array - an array of answer arrays
- */
+ */
function objects_to_array($objectarray)
{
$arrayarray = array();
}
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);
}
return $this->objects_to_array($answers);
}
-
+
/**
* gets an array with text and question arrays for the given cloze question
*
* @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. '<i><br>')
* @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];
// 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 <intro>...</intro> section, if any, and returns the text
*
*
* @param string $&text
* @return string the intro text, if there was an intro tag. '' otherwise.
- */
+ */
function get_cloze_intro(&$text) {
if (preg_match('/(.*)?\<intro>(.+)?\<\/intro>(.*)/s', $text, $matches)) {
$text = $matches[1] . $matches[3];
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) {
$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:
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:
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:
*
* @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) {
}
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);
}
$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');
}
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)) {
$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));
- 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;
$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!");
}
// 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);
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);
}
// 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);
}
//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) {
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;
}
}
$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);
}
// 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);
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;
}
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
$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++;
$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.
}
// 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;
}
$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;
}
// 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;
}
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
} 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));
}
$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();
* @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;
}
$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) {
}
$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)) {
} 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) {
}
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 ;
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
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');
}
}
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);
}
}
}
// 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 "<pre>"; print_r($datasetdefs[$defid]->items);
for ($numberadded =$maxnumber+1 ; $numberadded <= $maxnumber+$numbertoadd ; $numberadded++){
$datasetitem->value = '';
}
//pp echo "<pre>"; 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
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 ;
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');
}
} 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]);
}
}
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 = '';
$virtualqtype->get_tolerance_interval($calculated);
if ($calculated->min === '') {
// This should mean that something is wrong
- $stranswers .= " -$calculated->answer".'<br/><br/>';
+ $stranswers .= " -$calculated->answer".'<br/><br/>';
} else {
$stranswers .= $formula.' = '.$calculated->answer.'<br/>' ;
$stranswers .= $strmin. $delimiter.$calculated->min.'---';
// 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);
}
}
if (!$selected) {
- if ($mandatory){
+ if ($mandatory){
$selected = LITERAL . "-0-$name"; // Default
}else {
$selected = "0"; // Default
- }
+ }
}
return array($options, $selected);
}
$unit = $unit->unit;
} else {
$unit = '';
- }
+ }
foreach ($question->options->answers as $answer) {
if (((int) $answer->fraction) === 1) {
$answernumerical = qtype_calculated_calculate_answer(
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');
$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 ="<table width=\"100%\" border=\"1\"><tr><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\" >$namestr</th><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$rangeofvaluestr</th><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$itemscountstr</th><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$questionusingstr</th></tr>";
+
+ $text ="<table width=\"100%\" border=\"1\"><tr><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\" >$namestr</th><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$rangeofvaluestr</th><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$itemscountstr</th><th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$questionusingstr</th></tr>";
foreach ($datasetdefs as $datasetdef){
list($distribution, $min, $max,$dec) = explode(':', $datasetdef->options, 4);
$text .="<tr><td valign=\"top\" align=\"center\"> $datasetdef->name </td><td align=\"center\" valign=\"top\"> $min <strong>-</strong> $max </td><td align=\"right\" valign=\"top\">$datasetdef->itemcount </td><td align=\"left\">";
} else {
$qu->name = '';
}
- $text .=" $qu->name <br/>";
- }
+ $text .=" $qu->name <br/>";
+ }
$text .="</td></tr>";
}
$text .="</table>";
}else{
- $text .=get_string('nosharedwildcard', 'qtype_calculated');
+ $text .=get_string('nosharedwildcard', 'qtype_calculated');
}
return $text ;
- }
+ }
/// BACKUP FUNCTIONS ////////////////////////////
* 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
class question_dataset_dependent_questiontype extends default_questiontype {
- var $virtualqtype = false;
+ public $virtualqtype = false;
function name() {
return 'datasetdependent';
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);
}
}
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;
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 {
}
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;
}
}
function save_dataset_definitions($form) {
+ global $DB;
// Save datasets
$datasetdefinitions = $this->get_dataset_definitions($form->id, $form->dataset);
$tmpdatasets = array_flip($form->dataset);
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
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);
}
// 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;
}
}
$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]);
// 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));
}
}
}
* 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
$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
$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);
}
// 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;
}
}
$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]);
// 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));
}
}
}
// 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;'));
$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";
}
// 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])
*
* @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];
}
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);
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]");
$mform->addElement('hidden', 'wizard', 'datasetitems');
$mform->setType('wizard', PARAM_ALPHA);
-
+
$mform->addElement('hidden', 'returnurl');
$mform->setType('returnurl', PARAM_LOCALURL);
$mform->setDefault('returnurl', 0);
}
-?>
\ No newline at end of file
+?>
*
* @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){
* 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";
$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');
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));
}
}
}
}
-?>
\ No newline at end of file
+?>
}
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;
$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!";
}
}
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();
}
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;
}
$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;
}
// 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;
}
$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;
}
* @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;
}
}
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.
$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;
}
}
function save_session_and_responses(&$question, &$state) {
+ global $DB;
$subquestions = &$state->options->subquestions;
// Prepare an array to help when disambiguating equal answers.
$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;
* 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));
}
function restore_map($old_question_id,$new_question_id,$info,$restore) {
-
+ global $DB;
$status = true;
//Get the matchs array
//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')) {
$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;
}
}
}
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)){
$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);
}
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();
// 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;
if ($subquestion != ''){
$countsubquestions++;
}
- }
+ }
} else {
$countsubquestions =0;
}
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);
}
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) {
}
$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);
}
}
}
}
-
+
// 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
}
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));
}
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);
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;
}
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);
}
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');
}
}
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;
}
// 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]= '';
}
// 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?
}
}
// 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');
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:
}
// Delete redundant wrapped questions
- if(is_array($oldwrappedids) && count($oldwrappedids)){
+ if(is_array($oldwrappedids) && count($oldwrappedids)){
foreach ($oldwrappedids as $id) {
delete_question($id) ;
}
$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;
}
}
function save_session_and_responses(&$question, &$state) {
+ global $DB;
$responses = $state->responses;
// encode - (hyphen) and , (comma) to - because they are used as
// delimiters
$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;
* @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;
}
$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 = '';
foreach ($correctanswers as $ca) {
switch($wrapped->qtype){
case 'numerical':
- case 'shortanswer':
+ case 'shortanswer':
$correctanswer .= $delimiter.$ca;
break ;
case 'multichoice':
$correctanswer .= $delimiter.$answers[$ca]->answer;
}
break ;
- }
+ }
$delimiter = ', ';
}
}
}
}
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();\" ";
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;"';
}
$styleinfo = 'style="width: 2.8em;"';
}
*/
-
+
echo "<input $style $readonly $popup name=\"$inputname\"";
echo " type=\"text\" value=\"".s($response, true)."\" ".$styleinfo." /> ";
if (!empty($feedback) && !empty($USER->screenreader)) {
if(! isset($question->options->questions[$positionkey])){
echo $regs[0];
}else {
- echo '<div class="error" >'.get_string('questionnotfound','qtype_multianswer',$positionkey).'</div>';
+ echo '<div class="error" >'.get_string('questionnotfound','qtype_multianswer',$positionkey).'</div>';
}
}
}
// Print the final piece of question text:
echo $qtextremaining;
$this->print_question_submit_buttons($question, $state, $cmoptions, $options);
- echo '</div>';
+ echo '</div>';
}
function grade_responses(&$question, &$state, $cmoptions) {
* 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
}
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;
$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
}
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;
}
}
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();
}
$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;
}
$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;
}
}
$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;
$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;
}
// 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));
}
}
* @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;
}
}
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
$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;
*/
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) {
$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;
}
}
}
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;
$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);
}
}
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);
}
}
// 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;
}
}
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();
* 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();
}
// 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) == '*') {
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;
}
$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;
}
// 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));
}
}
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();
$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;
}
* @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;
}
$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;
$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]];
// Invalid number. Must be wrong.
return false;
}
-
+
/// BACKUP FUNCTIONS ////////////////////////////
/**
* 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
* 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.
//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
$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');
}
}
}
// 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');
}
* 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;
$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;
* 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;
$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;
$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);
}
} 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;
* @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;
}
* 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.
* 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');
// 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) {
// 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;
}
}
* @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
/// 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);
}
}
$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);
}
}
<?php // $Id$
/**
* Class for the random question type.
- *
- * The random question type does not have any options. When the question is
+ *
+ * The random question type does not have any options. When the question is
* attempted, it picks a question at random from the category it is in (and
* optionally its subcategories). For details see create_session_and_responses.
* Then all other method calls as delegated to that other question.
- *
+ *
* @package questionbank
* @subpackage questiontypes
*/
}
function save_question($question, $form, $course) {
+ global $DB;
// If the category is changing, set things up as default_questiontype::save_question expects.
list($formcategory, $unused) = explode(',', $form->category);
if (isset($question->id) && $formcategory != $question->category) {
}
$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
} 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'
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);
/// 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.
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);
}
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.
// 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;
}
$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
// 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)) {
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].'<br />';
return($answer_field);
}
}
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);
}
}
}
-?>
\ No newline at end of file
+?>
}
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;
}
}
function save_question_options($question) {
+ global $DB;
$options->question = $question->id;
$options->choose = $question->choose;
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;
}
* @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;
}
}
function restore_session_and_responses(&$question, &$state) {
+ global $DB;
global $QTYPES;
if (empty($state->responses[''])) {
$question->questiontext = "Insufficient selection options are
$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;
}
}
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();
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;
$result->responses = $answers;
return $result;
}
-
+
/// BACKUP FUNCTIONS ////////////////////////////
/*
* 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
if (!$que = backup_getid($restore->backup_unique_code,"question",$question_id)) {
echo 'Could not recode randomsamatch question '.$question_id.'<br />';
}
-
+
if ($answer_id == 0) { // no response yet
$ans->new_id = 0;
} else {
}
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;
}
}
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();
}
$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;
}
$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;
}
}
}
- 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;
}
$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;
}
// 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));
}
}
* @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;
}
* 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
}
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();
}
$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;
}
$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;
}
$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;
}
$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;
}
// 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;
}
$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;
}
* 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;
}
* @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;
}
* 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
* 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");
}
?>