forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestionlib.php
3011 lines (2711 loc) · 112 KB
/
questionlib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Code for handling and processing questions
*
* This is code that is module independent, i.e., can be used by any module that
* uses questions, like quiz, lesson, ..
* This script also loads the questiontype classes
* Code for handling the editing of questions is in {@link question/editlib.php}
*
* TODO: separate those functions which form part of the API
* from the helper functions.
*
* Major Contributors
* - Alex Smith, Julian Sedding and Gustav Delius {@link http://maths.york.ac.uk/serving_maths}
*
* @package moodlecore
* @subpackage question
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/// CONSTANTS ///////////////////////////////////
/**#@+
* The different types of events that can create question states
*/
define('QUESTION_EVENTOPEN', '0'); // The state was created by Moodle
define('QUESTION_EVENTNAVIGATE', '1'); // The responses were saved because the student navigated to another page (this is not currently used)
define('QUESTION_EVENTSAVE', '2'); // The student has requested that the responses should be saved but not submitted or validated
define('QUESTION_EVENTGRADE', '3'); // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle.
define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously
define('QUESTION_EVENTVALIDATE', '5'); // The student has requested a validation. This causes the responses to be saved as well, but not graded.
define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle.
define('QUESTION_EVENTSUBMIT', '7'); // The student response has been submitted but it has not yet been marked
define('QUESTION_EVENTCLOSE', '8'); // The response has been submitted and the session has been closed, either because the student requested it or because Moodle did it (e.g. because of a timelimit). The responses have not been graded.
define('QUESTION_EVENTMANUALGRADE', '9'); // Grade was entered by teacher
define('QUESTION_EVENTS_GRADED', QUESTION_EVENTGRADE.','.
QUESTION_EVENTCLOSEANDGRADE.','.
QUESTION_EVENTMANUALGRADE);
define('QUESTION_EVENTS_CLOSED', QUESTION_EVENTCLOSE.','.
QUESTION_EVENTCLOSEANDGRADE.','.
QUESTION_EVENTMANUALGRADE);
define('QUESTION_EVENTS_CLOSED_OR_GRADED', QUESTION_EVENTGRADE.','.
QUESTION_EVENTS_CLOSED);
/**#@-*/
/**#@+
* The core question types.
*/
define("SHORTANSWER", "shortanswer");
define("TRUEFALSE", "truefalse");
define("MULTICHOICE", "multichoice");
define("RANDOM", "random");
define("MATCH", "match");
define("RANDOMSAMATCH", "randomsamatch");
define("DESCRIPTION", "description");
define("NUMERICAL", "numerical");
define("MULTIANSWER", "multianswer");
define("CALCULATED", "calculated");
define("ESSAY", "essay");
/**#@-*/
/**
* Constant determines the number of answer boxes supplied in the editing
* form for multiple choice and similar question types.
*/
define("QUESTION_NUMANS", "10");
/**
* Constant determines the number of answer boxes supplied in the editing
* form for multiple choice and similar question types to start with, with
* the option of adding QUESTION_NUMANS_ADD more answers.
*/
define("QUESTION_NUMANS_START", 3);
/**
* Constant determines the number of answer boxes to add in the editing
* form for multiple choice and similar question types when the user presses
* 'add form fields button'.
*/
define("QUESTION_NUMANS_ADD", 3);
/**
* The options used when popping up a question preview window in Javascript.
*/
define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=true&resizable=true&width=700&height=540');
/**#@+
* Option flags for ->optionflags
* The options are read out via bitwise operation using these constants
*/
/**
* Whether the questions is to be run in adaptive mode. If this is not set then
* a question closes immediately after the first submission of responses. This
* is how question is Moodle always worked before version 1.5
*/
define('QUESTION_ADAPTIVE', 1);
/**#@-*/
/**#@+
* Options used in forms that move files.
*/
define('QUESTION_FILENOTHINGSELECTED', 0);
define('QUESTION_FILEDONOTHING', 1);
define('QUESTION_FILECOPY', 2);
define('QUESTION_FILEMOVE', 3);
define('QUESTION_FILEMOVELINKSONLY', 4);
/**#@-*/
/**#@+
* Options for whether flags are shown/editable when rendering questions.
*/
define('QUESTION_FLAGSHIDDEN', 0);
define('QUESTION_FLAGSSHOWN', 1);
define('QUESTION_FLAGSEDITABLE', 2);
/**#@-*/
/**
* GLOBAL VARAIBLES
* @global array $QTYPES
* @name $QTYPES
*/
global $QTYPES;
/**
* Array holding question type objects. Initialised via calls to
* question_register_questiontype as the question type classes are included.
*/
$QTYPES = array();
/**
* Add a new question type to the various global arrays above.
*
* @global object
* @param object $qtype An instance of the new question type class.
*/
function question_register_questiontype($qtype) {
global $QTYPES;
$name = $qtype->name();
$QTYPES[$name] = $qtype;
}
require_once("$CFG->dirroot/question/type/questiontype.php");
// Load the questiontype.php file for each question type
// These files in turn call question_register_questiontype()
// with a new instance of each qtype class.
$qtypenames = get_plugin_list('qtype');
foreach($qtypenames as $qtypename => $qdir) {
// Instanciates all plug-in question types
$qtypefilepath= "$qdir/questiontype.php";
// echo "Loading $qtypename<br/>"; // Uncomment for debugging
if (is_readable($qtypefilepath)) {
require_once($qtypefilepath);
}
}
/**
* An array of question type names translated to the user's language, suitable for use when
* creating a drop-down menu of options.
*
* Long-time Moodle programmers will realise that this replaces the old $QTYPE_MENU array.
* The array returned will only hold the names of all the question types that the user should
* be able to create directly. Some internal question types like random questions are excluded.
*
* @global object
* @return array an array of question type names translated to the user's language.
*/
function question_type_menu() {
global $QTYPES;
static $menuoptions = null;
if (is_null($menuoptions)) {
$config = get_config('question');
$menuoptions = array();
foreach ($QTYPES as $name => $qtype) {
// Get the name if this qtype is enabled.
$menuname = $qtype->menu_name();
$enabledvar = $name . '_disabled';
if ($menuname && !isset($config->$enabledvar)) {
$menuoptions[$name] = $menuname;
}
}
$menuoptions = question_sort_qtype_array($menuoptions, $config);
}
return $menuoptions;
}
/**
* Sort an array of question type names according to the question type sort order stored in
* config_plugins. Entries for which there is no xxx_sortorder defined will go
* at the end, sorted according to asort($inarray, SORT_LOCALE_STRING).
* @param $inarray an array $qtype => $QTYPES[$qtype]->local_name().
* @param $config get_config('question'), if you happen to have it around, to save one DB query.
* @return array the sorted version of $inarray.
*/
function question_sort_qtype_array($inarray, $config = null) {
if (is_null($config)) {
$config = get_config('question');
}
$sortorder = array();
foreach ($inarray as $name => $notused) {
$sortvar = $name . '_sortorder';
if (isset($config->$sortvar)) {
$sortorder[$config->$sortvar] = $name;
}
}
ksort($sortorder);
$outarray = array();
foreach ($sortorder as $name) {
$outarray[$name] = $inarray[$name];
unset($inarray[$name]);
}
asort($inarray, SORT_LOCALE_STRING);
return array_merge($outarray, $inarray);
}
/**
* Move one question type in a list of question types. If you try to move one element
* off of the end, nothing will change.
*
* @param array $sortedqtypes An array $qtype => anything.
* @param string $tomove one of the keys from $sortedqtypes
* @param integer $direction +1 or -1
* @return array an array $index => $qtype, with $index from 0 to n in order, and
* the $qtypes in the same order as $sortedqtypes, except that $tomove will
* have been moved one place.
*/
function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
$neworder = array_keys($sortedqtypes);
// Find the element to move.
$key = array_search($tomove, $neworder);
if ($key === false) {
return $neworder;
}
// Work out the other index.
$otherkey = $key + $direction;
if (!isset($neworder[$otherkey])) {
return $neworder;
}
// Do the swap.
$swap = $neworder[$otherkey];
$neworder[$otherkey] = $neworder[$key];
$neworder[$key] = $swap;
return $neworder;
}
/**
* Save a new question type order to the config_plugins table.
* @global object
* @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
* @param $config get_config('question'), if you happen to have it around, to save one DB query.
*/
function question_save_qtype_order($neworder, $config = null) {
global $DB;
if (is_null($config)) {
$config = get_config('question');
}
foreach ($neworder as $index => $qtype) {
$sortvar = $qtype . '_sortorder';
if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
set_config($sortvar, $index + 1, 'question');
}
}
}
/// OTHER CLASSES /////////////////////////////////////////////////////////
/**
* This holds the options that are set by the course module
*
* @package moodlecore
* @subpackage question
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cmoptions {
/**
* Whether a new attempt should be based on the previous one. If true
* then a new attempt will start in a state where all responses are set
* to the last responses from the previous attempt.
*/
var $attemptonlast = false;
/**
* Various option flags. The flags are accessed via bitwise operations
* using the constants defined in the CONSTANTS section above.
*/
var $optionflags = QUESTION_ADAPTIVE;
/**
* Determines whether in the calculation of the score for a question
* penalties for earlier wrong responses within the same attempt will
* be subtracted.
*/
var $penaltyscheme = true;
/**
* The maximum time the user is allowed to answer the questions withing
* an attempt. This is measured in minutes so needs to be multiplied by
* 60 before compared to timestamps. If set to 0 no timelimit will be applied
*/
var $timelimit = 0;
/**
* Timestamp for the closing time. Responses submitted after this time will
* be saved but no credit will be given for them.
*/
var $timeclose = 9999999999;
/**
* The id of the course from withing which the question is currently being used
*/
var $course = SITEID;
/**
* Whether the answers in a multiple choice question should be randomly
* shuffled when a new attempt is started.
*/
var $shuffleanswers = true;
/**
* The number of decimals to be shown when scores are printed
*/
var $decimalpoints = 2;
}
/// FUNCTIONS //////////////////////////////////////////////////////
/**
* Returns an array of names of activity modules that use this question
*
* @global object
* @global object
* @param object $questionid
* @return array of strings
*/
function question_list_instances($questionid) {
global $CFG, $DB;
$instances = array();
$modules = $DB->get_records('modules');
foreach ($modules as $module) {
$fullmod = $CFG->dirroot . '/mod/' . $module->name;
if (file_exists($fullmod . '/lib.php')) {
include_once($fullmod . '/lib.php');
$fn = $module->name.'_question_list_instances';
if (function_exists($fn)) {
$instances = $instances + $fn($questionid);
}
}
}
return $instances;
}
/**
* Determine whether there arey any questions belonging to this context, that is whether any of its
* question categories contain any questions. This will return true even if all the questions are
* hidden.
*
* @global object
* @param mixed $context either a context object, or a context id.
* @return boolean whether any of the question categories beloning to this context have
* any questions in them.
*/
function question_context_has_any_questions($context) {
global $DB;
if (is_object($context)) {
$contextid = $context->id;
} else if (is_numeric($context)) {
$contextid = $context;
} else {
print_error('invalidcontextinhasanyquestions', 'question');
}
return $DB->record_exists_sql("SELECT *
FROM {question} q
JOIN {question_categories} qc ON qc.id = q.category
WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
}
/**
* Returns list of 'allowed' grades for grade selection
* formatted suitably for dropdown box function
* @return object ->gradeoptionsfull full array ->gradeoptions +ve only
*/
function get_grade_options() {
// define basic array of grades. This list comprises all fractions of the form:
// a. p/q for q <= 6, 0 <= p <= q
// b. p/10 for 0 <= p <= 10
// c. 1/q for 1 <= q <= 10
// d. 1/20
$grades = array(
1.0000000,
0.9000000,
0.8333333,
0.8000000,
0.7500000,
0.7000000,
0.6666667,
0.6000000,
0.5000000,
0.4000000,
0.3333333,
0.3000000,
0.2500000,
0.2000000,
0.1666667,
0.1428571,
0.1250000,
0.1111111,
0.1000000,
0.0500000,
0.0000000);
// iterate through grades generating full range of options
$gradeoptionsfull = array();
$gradeoptions = array();
foreach ($grades as $grade) {
$percentage = 100 * $grade;
$neggrade = -$grade;
$gradeoptions["$grade"] = "$percentage %";
$gradeoptionsfull["$grade"] = "$percentage %";
$gradeoptionsfull["$neggrade"] = -$percentage." %";
}
$gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
// sort lists
arsort($gradeoptions, SORT_NUMERIC);
arsort($gradeoptionsfull, SORT_NUMERIC);
// construct return object
$grades = new stdClass;
$grades->gradeoptions = $gradeoptions;
$grades->gradeoptionsfull = $gradeoptionsfull;
return $grades;
}
/**
* match grade options
* if no match return error or match nearest
* @param array $gradeoptionsfull list of valid options
* @param int $grade grade to be tested
* @param string $matchgrades 'error' or 'nearest'
* @return mixed either 'fixed' value or false if erro
*/
function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
// if we just need an error...
if ($matchgrades=='error') {
foreach($gradeoptionsfull as $value => $option) {
// slightly fuzzy test, never check floats for equality :-)
if (abs($grade-$value)<0.00001) {
return $grade;
}
}
// didn't find a match so that's an error
return false;
}
// work out nearest value
else if ($matchgrades=='nearest') {
$hownear = array();
foreach($gradeoptionsfull as $value => $option) {
if ($grade==$value) {
return $grade;
}
$hownear[ $value ] = abs( $grade - $value );
}
// reverse sort list of deltas and grab the last (smallest)
asort( $hownear, SORT_NUMERIC );
reset( $hownear );
return key( $hownear );
}
else {
return false;
}
}
/**
* Tests whether a category is in use by any activity module
*
* @global object
* @return boolean
* @param integer $categoryid
* @param boolean $recursive Whether to examine category children recursively
*/
function question_category_isused($categoryid, $recursive = false) {
global $DB;
//Look at each question in the category
if ($questions = $DB->get_records('question', array('category'=>$categoryid), '', 'id,qtype')) {
foreach ($questions as $question) {
if (count(question_list_instances($question->id))) {
return true;
}
}
}
//Look under child categories recursively
if ($recursive) {
if ($children = $DB->get_records('question_categories', array('parent'=>$categoryid))) {
foreach ($children as $child) {
if (question_category_isused($child->id, $recursive)) {
return true;
}
}
}
}
return false;
}
/**
* Deletes all data associated to an attempt from the database
*
* @global object
* @global object
* @param integer $attemptid The id of the attempt being deleted
*/
function delete_attempt($attemptid) {
global $QTYPES, $DB;
$states = $DB->get_records('question_states', array('attempt'=>$attemptid));
if ($states) {
$stateslist = implode(',', array_keys($states));
// delete question-type specific data
foreach ($QTYPES as $qtype) {
$qtype->delete_states($stateslist);
}
}
// delete entries from all other question tables
// It is important that this is done only after calling the questiontype functions
$DB->delete_records("question_states", array("attempt"=>$attemptid));
$DB->delete_records("question_sessions", array("attemptid"=>$attemptid));
$DB->delete_records("question_attempts", array("id"=>$attemptid));
}
/**
* Deletes question and all associated data from the database
*
* It will not delete a question if it is used by an activity module
*
* @global object
* @global object
* @param object $question The question being deleted
*/
function delete_question($questionid) {
global $QTYPES, $DB;
if (!$question = $DB->get_record('question', array('id'=>$questionid))) {
// In some situations, for example if this was a child of a
// Cloze question that was previously deleted, the question may already
// have gone. In this case, just do nothing.
return;
}
// Do not delete a question if it is used by an activity module
if (count(question_list_instances($questionid))) {
return;
}
// delete questiontype-specific data
question_require_capability_on($question, 'edit');
if ($question) {
if (isset($QTYPES[$question->qtype])) {
$QTYPES[$question->qtype]->delete_question($questionid);
}
} else {
echo "Question with id $questionid does not exist.<br />";
}
if ($states = $DB->get_records('question_states', array('question'=>$questionid))) {
$stateslist = implode(',', array_keys($states));
// delete questiontype-specific data
foreach ($QTYPES as $qtype) {
$qtype->delete_states($stateslist);
}
}
// delete entries from all other question tables
// It is important that this is done only after calling the questiontype functions
$DB->delete_records("question_answers", array("question"=>$questionid));
$DB->delete_records("question_states", array("question"=>$questionid));
$DB->delete_records("question_sessions", array("questionid"=>$questionid));
// Now recursively delete all child questions
if ($children = $DB->get_records('question', array('parent' => $questionid), '', 'id,qtype')) {
foreach ($children as $child) {
if ($child->id != $questionid) {
delete_question($child->id);
}
}
}
// Finally delete the question record itself
$DB->delete_records('question', array('id'=>$questionid));
return;
}
/**
* All question categories and their questions are deleted for this course.
*
* @global object
* @param object $mod an object representing the activity
* @param boolean $feedback to specify if the process must output a summary of its work
* @return boolean
*/
function question_delete_course($course, $feedback=true) {
global $DB, $OUTPUT;
//To store feedback to be showed at the end of the process
$feedbackdata = array();
//Cache some strings
$strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$categoriescourse = $DB->get_records('question_categories', array('contextid'=>$coursecontext->id), 'parent', 'id, parent, name');
if ($categoriescourse) {
//Sort categories following their tree (parent-child) relationships
//this will make the feedback more readable
$categoriescourse = sort_categories_by_tree($categoriescourse);
foreach ($categoriescourse as $category) {
//Delete it completely (questions and category itself)
//deleting questions
if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) {
foreach ($questions as $question) {
delete_question($question->id);
}
$DB->delete_records("question", array("category"=>$category->id));
}
//delete the category
$DB->delete_records('question_categories', array('id'=>$category->id));
//Fill feedback
$feedbackdata[] = array($category->name, $strcatdeleted);
}
//Inform about changes performed if feedback is enabled
if ($feedback) {
$table = new html_table();
$table->head = array(get_string('category','quiz'), get_string('action'));
$table->data = $feedbackdata;
echo html_writer::table($table);
}
}
return true;
}
/**
* Category is about to be deleted,
* 1/ All question categories and their questions are deleted for this course category.
* 2/ All questions are moved to new category
*
* @global object
* @param object $category course category object
* @param object $newcategory empty means everything deleted, otherwise id of category where content moved
* @param boolean $feedback to specify if the process must output a summary of its work
* @return boolean
*/
function question_delete_course_category($category, $newcategory, $feedback=true) {
global $DB, $OUTPUT;
$context = get_context_instance(CONTEXT_COURSECAT, $category->id);
if (empty($newcategory)) {
$feedbackdata = array(); // To store feedback to be showed at the end of the process
$rescueqcategory = null; // See the code around the call to question_save_from_deletion.
$strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
// Loop over question categories.
if ($categories = $DB->get_records('question_categories', array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
foreach ($categories as $category) {
// Deal with any questions in the category.
if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) {
// Try to delete each question.
foreach ($questions as $question) {
delete_question($question->id);
}
// Check to see if there were any questions that were kept because they are
// still in use somehow, even though quizzes in courses in this category will
// already have been deteted. This could happen, for example, if questions are
// added to a course, and then that course is moved to another category (MDL-14802).
$questionids = $DB->get_records_menu('question', array('category'=>$category->id), '', 'id,1');
if (!empty($questionids)) {
if (!$rescueqcategory = question_save_from_deletion(implode(',', array_keys($questionids)),
get_parent_contextid($context), print_context_name($context), $rescueqcategory)) {
return false;
}
$feedbackdata[] = array($category->name, get_string('questionsmovedto', 'question', $rescueqcategory->name));
}
}
// Now delete the category.
if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
return false;
}
$feedbackdata[] = array($category->name, $strcatdeleted);
} // End loop over categories.
}
// Output feedback if requested.
if ($feedback and $feedbackdata) {
$table = new html_table();
$table->head = array(get_string('questioncategory','question'), get_string('action'));
$table->data = $feedbackdata;
echo html_writer::table($table);
}
} else {
// Move question categories ot the new context.
if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) {
return false;
}
if (!$DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid'=>$context->id))) {
return false;
}
if ($feedback) {
$a = new stdClass;
$a->oldplace = print_context_name($context);
$a->newplace = print_context_name($newcontext);
echo $OUTPUT->notification(get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
}
}
return true;
}
/**
* Enter description here...
*
* @global object
* @param string $questionids list of questionids
* @param object $newcontext the context to create the saved category in.
* @param string $oldplace a textual description of the think being deleted, e.g. from get_context_name
* @param object $newcategory
* @return mixed false on
*/
function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
global $DB;
// Make a category in the parent context to move the questions to.
if (is_null($newcategory)) {
$newcategory = new object();
$newcategory->parent = 0;
$newcategory->contextid = $newcontextid;
$newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
$newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
$newcategory->sortorder = 999;
$newcategory->stamp = make_unique_id_code();
$newcategory->id = $DB->insert_record('question_categories', $newcategory);
}
// Move any remaining questions to the 'saved' category.
if (!question_move_questions_to_category($questionids, $newcategory->id)) {
return false;
}
return $newcategory;
}
/**
* All question categories and their questions are deleted for this activity.
*
* @global object
* @param object $cm the course module object representing the activity
* @param boolean $feedback to specify if the process must output a summary of its work
* @return boolean
*/
function question_delete_activity($cm, $feedback=true) {
global $DB, $OUTPUT;
//To store feedback to be showed at the end of the process
$feedbackdata = array();
//Cache some strings
$strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
$modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
if ($categoriesmods = $DB->get_records('question_categories', array('contextid'=>$modcontext->id), 'parent', 'id, parent, name')){
//Sort categories following their tree (parent-child) relationships
//this will make the feedback more readable
$categoriesmods = sort_categories_by_tree($categoriesmods);
foreach ($categoriesmods as $category) {
//Delete it completely (questions and category itself)
//deleting questions
if ($questions = $DB->get_records('question', array('category' => $category->id), '', 'id,qtype')) {
foreach ($questions as $question) {
delete_question($question->id);
}
$DB->delete_records("question", array("category"=>$category->id));
}
//delete the category
$DB->delete_records('question_categories', array('id'=>$category->id));
//Fill feedback
$feedbackdata[] = array($category->name, $strcatdeleted);
}
//Inform about changes performed if feedback is enabled
if ($feedback) {
$table = new html_table();
$table->head = array(get_string('category','quiz'), get_string('action'));
$table->data = $feedbackdata;
echo html_writer::table($table);
}
}
return true;
}
/**
* This function should be considered private to the question bank, it is called from
* question/editlib.php question/contextmoveq.php and a few similar places to to the work of
* acutally moving questions and associated data. However, callers of this function also have to
* do other work, which is why you should not call this method directly from outside the questionbank.
*
* @global object
* @param string $questionids a comma-separated list of question ids.
* @param integer $newcategory the id of the category to move to.
*/
function question_move_questions_to_category($questionids, $newcategory) {
global $DB;
$result = true;
// Move the questions themselves.
$result = $result && $DB->set_field_select('question', 'category', $newcategory, "id IN ($questionids)");
// Move any subquestions belonging to them.
$result = $result && $DB->set_field_select('question', 'category', $newcategory, "parent IN ($questionids)");
// TODO Deal with datasets.
return $result;
}
/**
* @global object
* @global object
* @param array $row tab objects
* @param question_edit_contexts $contexts object representing contexts available from this context
* @param string $querystring to append to urls
* */
function questionbank_navigation_tabs(&$row, $contexts, array $params) {
global $CFG, $QUESTION_EDITTABCAPS;
$tabs = array(
'questions' =>array(new moodle_url('/question/edit.php', $params), get_string('questions', 'quiz'), get_string('editquestions', 'quiz')),
'categories' =>array(new moodle_url('/question/category.php', $params), get_string('categories', 'quiz'), get_string('editqcats', 'quiz')),
'import' =>array(new moodle_url('/question/import.php', $params), get_string('import', 'quiz'), get_string('importquestions', 'quiz')),
'export' =>array(new moodle_url('/question/export.php', $params), get_string('export', 'quiz'), get_string('exportquestions', 'quiz')));
foreach ($tabs as $tabname => $tabparams){
if ($contexts->have_one_edit_tab_cap($tabname)) {
$row[] = new tabobject($tabname, $tabparams[0], $tabparams[1], $tabparams[2]);
}
}
}
/**
* Given a list of ids, load the basic information about a set of questions from the questions table.
* The $join and $extrafields arguments can be used together to pull in extra data.
* See, for example, the usage in mod/quiz/attemptlib.php, and
* read the code below to see how the SQL is assembled. Throws exceptions on error.
*
* @global object
* @global object
* @param array $questionids array of question ids.
* @param string $extrafields extra SQL code to be added to the query.
* @param string $join extra SQL code to be added to the query.
* @param array $extraparams values for any placeholders in $join.
* You are strongly recommended to use named placeholder.
*
* @return array partially complete question objects. You need to call get_question_options
* on them before they can be properly used.
*/
function question_preload_questions($questionids, $extrafields = '', $join = '', $extraparams = array()) {
global $CFG, $DB;
if (empty($questionids)) {
return array();
}
if ($join) {
$join = ' JOIN '.$join;
}
if ($extrafields) {
$extrafields = ', ' . $extrafields;
}
list($questionidcondition, $params) = $DB->get_in_or_equal(
$questionids, SQL_PARAMS_NAMED, 'qid0000');
$sql = 'SELECT q.*' . $extrafields . ' FROM {question} q' . $join .
' WHERE q.id ' . $questionidcondition;
// Load the questions
if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
return 'Could not load questions.';
}
foreach ($questions as $question) {
$question->_partiallyloaded = true;
}
// Note, a possible optimisation here would be to not load the TEXT fields
// (that is, questiontext and generalfeedback) here, and instead load them in
// question_load_questions. That would add one DB query, but reduce the amount
// of data transferred most of the time. I am not going to do this optimisation
// until it is shown to be worthwhile.
return $questions;
}
/**
* Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
* together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
* read the code below to see how the SQL is assembled. Throws exceptions on error.
*
* @param array $questionids array of question ids.
* @param string $extrafields extra SQL code to be added to the query.
* @param string $join extra SQL code to be added to the query.
* @param array $extraparams values for any placeholders in $join.
* You are strongly recommended to use named placeholder.
*
* @return array question objects.
*/
function question_load_questions($questionids, $extrafields = '', $join = '') {
$questions = question_preload_questions($questionids, $extrafields, $join);
// Load the question type specific information
if (!get_question_options($questions)) {
return 'Could not load the question options';
}
return $questions;
}
/**
* Private function to factor common code out of get_question_options().
*
* @global object
* @global object
* @param object $question the question to tidy.
* @param boolean $loadtags load the question tags from the tags table. Optional, default false.
* @return boolean true if successful, else false.
*/
function _tidy_question(&$question, $loadtags = false) {
global $CFG, $QTYPES;
if (!array_key_exists($question->qtype, $QTYPES)) {
$question->qtype = 'missingtype';
$question->questiontext = '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext;
}
$question->name_prefix = question_make_name_prefix($question->id);
if ($success = $QTYPES[$question->qtype]->get_question_options($question)) {
if (isset($question->_partiallyloaded)) {
unset($question->_partiallyloaded);
}
}
if ($loadtags && !empty($CFG->usetags)) {
require_once($CFG->dirroot . '/tag/lib.php');
$question->tags = tag_get_tags_array('question', $question->id);
}
return $success;
}
/**
* Updates the question objects with question type specific
* information by calling {@link get_question_options()}
*
* Can be called either with an array of question objects or with a single
* question object.
*