Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Defines the base class for question import and export formats.
19
 *
20
 * @package    moodlecore
21
 * @subpackage questionbank
22
 * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
 
27
defined('MOODLE_INTERNAL') || die();
28
 
29
 
30
/**
31
 * Base class for question import and export formats.
32
 *
33
 * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
34
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35
 */
36
class qformat_default {
37
 
38
    public $displayerrors = true;
39
    public $category = null;
40
    public $questions = array();
41
    public $course = null;
42
    public $filename = '';
43
    public $realfilename = '';
44
    public $matchgrades = 'error';
45
    public $catfromfile = 0;
46
    public $contextfromfile = 0;
47
    public $cattofile = 0;
48
    public $contexttofile = 0;
49
    public $questionids = array();
50
    public $importerrors = 0;
51
    public $stoponerror = true;
52
    public $translator = null;
53
    public $canaccessbackupdata = true;
54
    protected $importcontext = null;
55
    /** @var bool $displayprogress Whether to display progress. */
56
    public $displayprogress = true;
57
    /** @var context[] */
58
    public $contexts;
59
 
60
    // functions to indicate import/export functionality
61
    // override to return true if implemented
62
 
63
    /** @return bool whether this plugin provides import functionality. */
64
    public function provide_import() {
65
        return false;
66
    }
67
 
68
    /** @return bool whether this plugin provides export functionality. */
69
    public function provide_export() {
70
        return false;
71
    }
72
 
73
    /** The string mime-type of the files that this plugin reads or writes. */
74
    public function mime_type() {
75
        return mimeinfo('type', $this->export_file_extension());
76
    }
77
 
78
    /**
79
     * @return string the file extension (including .) that is normally used for
80
     * files handled by this plugin.
81
     */
82
    public function export_file_extension() {
83
        return '.txt';
84
    }
85
 
86
    /**
87
     * Check if the given file is capable of being imported by this plugin.
88
     *
89
     * Note that expensive or detailed integrity checks on the file should
90
     * not be performed by this method. Simple file type or magic-number tests
91
     * would be suitable.
92
     *
93
     * @param stored_file $file the file to check
94
     * @return bool whether this plugin can import the file
95
     */
96
    public function can_import_file($file) {
97
        return ($file->get_mimetype() == $this->mime_type());
98
    }
99
 
100
    /**
101
     * Validate the given file.
102
     *
103
     * For more expensive or detailed integrity checks.
104
     *
105
     * @param stored_file $file the file to check
106
     * @return string the error message that occurred while validating the given file
107
     */
108
    public function validate_file(stored_file $file): string {
109
        return '';
110
    }
111
 
112
    /**
113
     * Check if the given file has the required utf8 encoding.
114
     *
115
     * @param stored_file $file the file to check
116
     * @return string the error message if the file encoding is not UTF-8
117
     */
118
    protected function validate_is_utf8_file(stored_file $file): string {
119
        if (!mb_check_encoding($file->get_content(), "UTF-8")) {
120
            return get_string('importwrongfileencoding', 'question',  $this->get_name());
121
        }
122
        return '';
123
    }
124
 
125
    /**
126
     * Return the localized pluginname string for the question format.
127
     *
128
     * @return string the pluginname string for the question format
129
     */
130
    protected function get_name(): string {
131
        return get_string('pluginname', get_class($this));
132
    }
133
 
134
    // Accessor methods
135
 
136
    /**
137
     * set the category
138
     * @param object category the category object
139
     */
140
    public function setCategory($category) {
141
        if (count($this->questions)) {
142
            debugging('You shouldn\'t call setCategory after setQuestions');
143
        }
1441 ariadna 144
        $context = context::instance_by_id($category->contextid);
145
        if ($context->contextlevel !== CONTEXT_MODULE) {
146
            throw new \core\exception\moodle_exception('Invalid contextlevel for target category, must be CONTEXT_MODULE');
147
        }
1 efrain 148
        $this->category = $category;
1441 ariadna 149
        $this->importcontext = $context;
1 efrain 150
    }
151
 
152
    /**
153
     * Set the specific questions to export. Should not include questions with
154
     * parents (sub questions of cloze question type).
155
     * Only used for question export.
156
     * @param array of question objects
157
     */
158
    public function setQuestions($questions) {
159
        if ($this->category !== null) {
160
            debugging('You shouldn\'t call setQuestions after setCategory');
161
        }
162
        $this->questions = $questions;
163
    }
164
 
165
    /**
166
     * set the course class variable
167
     * @param course object Moodle course variable
168
     */
169
    public function setCourse($course) {
170
        $this->course = $course;
171
    }
172
 
173
    /**
174
     * set an array of contexts.
175
     * @param context[] $contexts
176
     */
177
    public function setContexts($contexts) {
178
        $this->contexts = $contexts;
179
        $this->translator = new core_question\local\bank\context_to_string_translator($this->contexts);
180
    }
181
 
182
    /**
183
     * set the filename
184
     * @param string filename name of file to import/export
185
     */
186
    public function setFilename($filename) {
187
        $this->filename = $filename;
188
    }
189
 
190
    /**
191
     * set the "real" filename
192
     * (this is what the user typed, regardless of wha happened next)
193
     * @param string realfilename name of file as typed by user
194
     */
195
    public function setRealfilename($realfilename) {
196
        $this->realfilename = $realfilename;
197
    }
198
 
199
    /**
200
     * set matchgrades
201
     * @param string matchgrades error or nearest for grades
202
     */
203
    public function setMatchgrades($matchgrades) {
204
        $this->matchgrades = $matchgrades;
205
    }
206
 
207
    /**
208
     * set catfromfile
209
     * @param bool catfromfile allow categories embedded in import file
210
     */
211
    public function setCatfromfile($catfromfile) {
212
        $this->catfromfile = $catfromfile;
213
    }
214
 
215
    /**
216
     * set contextfromfile
217
     * @param bool $contextfromfile allow contexts embedded in import file
218
     */
219
    public function setContextfromfile($contextfromfile) {
220
        $this->contextfromfile = $contextfromfile;
221
    }
222
 
223
    /**
224
     * set cattofile
225
     * @param bool cattofile exports categories within export file
226
     */
227
    public function setCattofile($cattofile) {
228
        $this->cattofile = $cattofile;
229
    }
230
 
231
    /**
232
     * set contexttofile
233
     * @param bool cattofile exports categories within export file
234
     */
235
    public function setContexttofile($contexttofile) {
236
        $this->contexttofile = $contexttofile;
237
    }
238
 
239
    /**
240
     * set stoponerror
241
     * @param bool stoponerror stops database write if any errors reported
242
     */
243
    public function setStoponerror($stoponerror) {
244
        $this->stoponerror = $stoponerror;
245
    }
246
 
247
    /**
248
     * @param bool $canaccess Whether the current use can access the backup data folder. Determines
249
     * where export files are saved.
250
     */
251
    public function set_can_access_backupdata($canaccess) {
252
        $this->canaccessbackupdata = $canaccess;
253
    }
254
 
255
    /**
256
     * Change whether to display progress messages.
257
     * There is normally no need to use this function as the
258
     * default for $displayprogress is true.
259
     * Set to false for unit tests.
260
     * @param bool $displayprogress
261
     */
262
    public function set_display_progress($displayprogress) {
263
        $this->displayprogress = $displayprogress;
264
    }
265
 
266
    /***********************
267
     * IMPORTING FUNCTIONS
268
     ***********************/
269
 
270
    /**
271
     * Handle parsing error
272
     */
273
    protected function error($message, $text='', $questionname='') {
274
        $importerrorquestion = get_string('importerrorquestion', 'question');
275
 
276
        echo "<div class=\"importerror\">\n";
277
        echo "<strong>{$importerrorquestion} {$questionname}</strong>";
278
        if (!empty($text)) {
279
            $text = s($text);
280
            echo "<blockquote>{$text}</blockquote>\n";
281
        }
282
        echo "<strong>{$message}</strong>\n";
283
        echo "</div>";
284
 
285
        $this->importerrors++;
286
    }
287
 
288
    /**
289
     * Import for questiontype plugins
290
     * Do not override.
291
     * @param data mixed The segment of data containing the question
292
     * @param question object processed (so far) by standard import code if appropriate
293
     * @param extra mixed any additional format specific data that may be passed by the format
294
     * @param qtypehint hint about a question type from format
295
     * @return object question object suitable for save_options() or false if cannot handle
296
     */
297
    public function try_importing_using_qtypes($data, $question = null, $extra = null,
298
            $qtypehint = '') {
299
 
300
        // work out what format we are using
301
        $formatname = substr(get_class($this), strlen('qformat_'));
302
        $methodname = "import_from_{$formatname}";
303
 
304
        //first try importing using a hint from format
305
        if (!empty($qtypehint)) {
306
            $qtype = question_bank::get_qtype($qtypehint, false);
307
            if (is_object($qtype) && method_exists($qtype, $methodname)) {
308
                $question = $qtype->$methodname($data, $question, $this, $extra);
309
                if ($question) {
310
                    return $question;
311
                }
312
            }
313
        }
314
 
315
        // loop through installed questiontypes checking for
316
        // function to handle this question
317
        foreach (question_bank::get_all_qtypes() as $qtype) {
318
            if (method_exists($qtype, $methodname)) {
1441 ariadna 319
                if ($importedquestion = $qtype->$methodname($data, $question, $this, $extra)) {
320
                    return $importedquestion;
1 efrain 321
                }
322
            }
323
        }
324
        return false;
325
    }
326
 
327
    /**
328
     * Perform any required pre-processing
329
     * @return bool success
330
     */
331
    public function importpreprocess() {
332
        return true;
333
    }
334
 
335
    /**
336
     * Process the file
337
     * This method should not normally be overidden
338
     * @return bool success
339
     */
340
    public function importprocess() {
341
        global $USER, $DB, $OUTPUT;
342
 
343
        // Raise time and memory, as importing can be quite intensive.
344
        core_php_time_limit::raise();
345
        raise_memory_limit(MEMORY_EXTRA);
346
 
347
        // STAGE 1: Parse the file
348
        if ($this->displayprogress) {
349
            echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess');
350
        }
351
 
352
        if (! $lines = $this->readdata($this->filename)) {
353
            echo $OUTPUT->notification(get_string('cannotread', 'question'));
354
            return false;
355
        }
356
 
357
        if (!$questions = $this->readquestions($lines)) {   // Extract all the questions
358
            echo $OUTPUT->notification(get_string('noquestionsinfile', 'question'));
359
            return false;
360
        }
361
 
362
        // STAGE 2: Write data to database
363
        if ($this->displayprogress) {
364
            echo $OUTPUT->notification(get_string('importingquestions', 'question',
365
                    $this->count_questions($questions)), 'notifysuccess');
366
        }
367
 
368
        // check for errors before we continue
369
        if ($this->stoponerror and ($this->importerrors>0)) {
370
            echo $OUTPUT->notification(get_string('importparseerror', 'question'));
371
            return false;
372
        }
373
 
374
        // get list of valid answer grades
375
        $gradeoptionsfull = question_bank::fraction_options_full();
376
 
377
        // check answer grades are valid
378
        // (now need to do this here because of 'stop on error': MDL-10689)
379
        $gradeerrors = 0;
380
        $goodquestions = array();
381
        foreach ($questions as $question) {
382
            if (!empty($question->fraction) and (is_array($question->fraction))) {
383
                $fractions = $question->fraction;
384
                $invalidfractions = array();
385
                foreach ($fractions as $key => $fraction) {
386
                    $newfraction = match_grade_options($gradeoptionsfull, $fraction,
387
                            $this->matchgrades);
388
                    if ($newfraction === false) {
389
                        $invalidfractions[] = $fraction;
390
                    } else {
391
                        $fractions[$key] = $newfraction;
392
                    }
393
                }
394
                if ($invalidfractions) {
395
                    $a = ['grades' => implode(', ', $invalidfractions), 'question' => $question->name];
396
                    echo $OUTPUT->notification(get_string('invalidgradequestion', 'question', $a));
397
                    ++$gradeerrors;
398
                    continue;
399
                } else {
400
                    $question->fraction = $fractions;
401
                }
402
            }
403
            $goodquestions[] = $question;
404
        }
405
        $questions = $goodquestions;
406
 
407
        // check for errors before we continue
408
        if ($this->stoponerror && $gradeerrors > 0) {
409
            echo $OUTPUT->notification(get_string('importparseerror', 'question'));
410
            return false;
411
        }
412
 
413
        // count number of questions processed
414
        $count = 0;
415
 
416
        foreach ($questions as $question) {   // Process and store each question
417
            $transaction = $DB->start_delegated_transaction();
418
 
419
            // reset the php timeout
420
            core_php_time_limit::raise();
421
 
422
            // check for category modifiers
423
            if ($question->qtype == 'category') {
424
                if ($this->catfromfile) {
425
                    // find/create category object
426
                    $catpath = $question->category;
427
                    $newcategory = $this->create_category_path($catpath, $question);
428
                    if (!empty($newcategory)) {
429
                        $this->category = $newcategory;
430
                    }
431
                }
432
                $transaction->allow_commit();
433
                continue;
434
            }
435
            $question->context = $this->importcontext;
436
 
437
            $count++;
438
 
439
            if ($this->displayprogress) {
440
                echo "<hr /><p><b>{$count}</b>. " . $this->format_question_text($question) . "</p>";
441
            }
442
 
443
            $question->category = $this->category->id;
444
            $question->stamp = make_unique_id_code();  // Set the unique code (not to be changed)
445
 
446
            $question->createdby = $USER->id;
447
            $question->timecreated = time();
448
            $question->modifiedby = $USER->id;
449
            $question->timemodified = time();
450
            if (isset($question->idnumber)) {
451
                if ((string) $question->idnumber === '') {
452
                    // Id number not really set. Get rid of it.
453
                    unset($question->idnumber);
454
                } else {
455
                    if ($DB->record_exists('question_bank_entries',
456
                            ['idnumber' => $question->idnumber, 'questioncategoryid' => $question->category])) {
457
                        // We cannot have duplicate idnumbers in a category. Just remove it.
458
                        unset($question->idnumber);
459
                    }
460
                }
461
            }
462
 
463
            $fileoptions = array(
464
                    'subdirs' => true,
465
                    'maxfiles' => -1,
466
                    'maxbytes' => 0,
467
                );
468
 
469
            $question->id = $DB->insert_record('question', $question);
470
            // Create a bank entry for each question imported.
471
            $questionbankentry = new \stdClass();
472
            $questionbankentry->questioncategoryid = $question->category;
473
            $questionbankentry->idnumber = $question->idnumber ?? null;
474
            $questionbankentry->ownerid = $question->createdby;
475
            $questionbankentry->id = $DB->insert_record('question_bank_entries', $questionbankentry);
476
            // Create a version for each question imported.
477
            $questionversion = new \stdClass();
478
            $questionversion->questionbankentryid = $questionbankentry->id;
479
            $questionversion->questionid = $question->id;
480
            $questionversion->version = 1;
481
            $questionversion->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
482
            $questionversion->id = $DB->insert_record('question_versions', $questionversion);
483
 
484
            if (isset($question->questiontextitemid)) {
485
                $question->questiontext = file_save_draft_area_files($question->questiontextitemid,
486
                        $this->importcontext->id, 'question', 'questiontext', $question->id,
487
                        $fileoptions, $question->questiontext);
1441 ariadna 488
                file_clear_draft_area($question->questiontextitemid);
1 efrain 489
            } else if (isset($question->questiontextfiles)) {
490
                foreach ($question->questiontextfiles as $file) {
491
                    question_bank::get_qtype($question->qtype)->import_file(
492
                            $this->importcontext, 'question', 'questiontext', $question->id, $file);
493
                }
494
            }
495
            if (isset($question->generalfeedbackitemid)) {
496
                $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid,
497
                        $this->importcontext->id, 'question', 'generalfeedback', $question->id,
498
                        $fileoptions, $question->generalfeedback);
1441 ariadna 499
                file_clear_draft_area($question->generalfeedbackitemid);
1 efrain 500
            } else if (isset($question->generalfeedbackfiles)) {
501
                foreach ($question->generalfeedbackfiles as $file) {
502
                    question_bank::get_qtype($question->qtype)->import_file(
503
                            $this->importcontext, 'question', 'generalfeedback', $question->id, $file);
504
                }
505
            }
506
            $DB->update_record('question', $question);
507
 
508
            $this->questionids[] = $question->id;
509
 
510
            // Now to save all the answers and type-specific options
511
 
512
            $result = question_bank::get_qtype($question->qtype)->save_question_options($question);
513
            $event = \core\event\question_created::create_from_question_instance($question, $this->importcontext);
514
            $event->trigger();
515
 
516
            if (core_tag_tag::is_enabled('core_question', 'question')) {
1441 ariadna 517
                // Course tags on question now deprecated so merge them into the question tags.
518
                $mergedtags = array_merge($question->coursetags ?? [], $question->tags ?? []);
519
                core_tag_tag::set_item_tags('core_question',
520
                    'question',
521
                    $question->id,
522
                    $question->context,
523
                    $mergedtags
524
                );
1 efrain 525
            }
526
 
527
            if (!empty($result->error)) {
528
                echo $OUTPUT->notification($result->error);
529
                // Can't use $transaction->rollback(); since it requires an exception,
530
                // and I don't want to rewrite this code to change the error handling now.
531
                $DB->force_transaction_rollback();
532
                return false;
533
            }
534
 
535
            $transaction->allow_commit();
536
 
537
            if (!empty($result->notice)) {
538
                echo $OUTPUT->notification($result->notice);
539
                return true;
540
            }
541
 
542
        }
543
        return true;
544
    }
545
 
546
    /**
547
     * Count all non-category questions in the questions array.
548
     *
549
     * @param array questions An array of question objects.
550
     * @return int The count.
551
     *
552
     */
553
    protected function count_questions($questions) {
554
        $count = 0;
555
        if (!is_array($questions)) {
556
            return $count;
557
        }
558
        foreach ($questions as $question) {
559
            if (!is_object($question) || !isset($question->qtype) ||
560
                    ($question->qtype == 'category')) {
561
                continue;
562
            }
563
            $count++;
564
        }
565
        return $count;
566
    }
567
 
568
    /**
569
     * find and/or create the category described by a delimited list
570
     * e.g. $course$/tom/dick/harry or tom/dick/harry
571
     *
572
     * removes any context string no matter whether $getcontext is set
573
     * but if $getcontext is set then ignore the context and use selected category context.
574
     *
575
     * @param string catpath delimited category path
576
     * @param object $lastcategoryinfo Contains category information
577
     * @return mixed category object or null if fails
578
     */
579
    protected function create_category_path($catpath, $lastcategoryinfo = null) {
580
        global $DB;
581
        $catnames = $this->split_category_path($catpath);
582
        $parent = 0;
583
        $category = null;
584
 
585
        // check for context id in path, it might not be there in pre 1.9 exports
586
        $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches);
587
        if ($matchcount == 1) {
588
            $contextid = $this->translator->string_to_context($matches[1]);
589
            array_shift($catnames);
590
        } else {
591
            $contextid = false;
592
        }
593
 
594
        // Before 3.5, question categories could be created at top level.
595
        // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
596
        if (isset($catnames[0]) && (($catnames[0] != 'top') || (count($catnames) < 3))) {
597
            array_unshift($catnames, 'top');
598
        }
599
 
600
        if ($this->contextfromfile && $contextid !== false) {
601
            $context = context::instance_by_id($contextid);
602
            require_capability('moodle/question:add', $context);
603
        } else {
604
            $context = context::instance_by_id($this->category->contextid);
605
        }
1441 ariadna 606
 
607
        // If the file had categories in a deprecated context then the categories need to be applied to a default system type
608
        // mod_qbank instance on the course instead.
609
        if ($context->contextlevel !== CONTEXT_MODULE) {
610
            $qbank = \core_question\local\bank\question_bank_helper::get_default_open_instance_system_type($this->course, true);
611
            $context = context_module::instance($qbank->id);
612
        }
613
 
1 efrain 614
        $this->importcontext = $context;
615
 
616
        // Now create any categories that need to be created.
617
        foreach ($catnames as $key => $catname) {
618
            if ($parent == 0) {
619
                $category = question_get_top_category($context->id, true);
620
                $parent = $category->id;
621
            } else if ($category = $DB->get_record('question_categories',
622
                    array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) {
623
                // If this category is now the last one in the path we are processing ...
624
                if ($key == (count($catnames) - 1) && $lastcategoryinfo) {
625
                    // Do nothing unless the child category appears before the parent category
626
                    // in the imported xml file. Because the parent was created without info being available
627
                    // at that time, this allows the info to be added from the xml data.
628
                    if (isset($lastcategoryinfo->info) && $lastcategoryinfo->info !== ''
629
                            && $category->info === '') {
630
                        $category->info = $lastcategoryinfo->info;
631
                        if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
632
                            $category->infoformat = $lastcategoryinfo->infoformat;
633
                        }
634
                    }
635
                    // Same for idnumber.
636
                    if (isset($lastcategoryinfo->idnumber) && $lastcategoryinfo->idnumber !== ''
637
                            && $category->idnumber === '') {
638
                        $category->idnumber = $lastcategoryinfo->idnumber;
639
                    }
640
                    $DB->update_record('question_categories', $category);
641
                }
642
                $parent = $category->id;
643
            } else {
644
                if ($catname == 'top') {
645
                    // Should not happen, but if it does just move on.
646
                    // Occurs when there has been some import/export that has created
647
                    // multiple nested 'top' categories (due to old bug solved by MDL-63165).
648
                    // This basically silently cleans up old errors. Not throwing an exception here.
649
                    continue;
650
                }
651
                require_capability('moodle/question:managecategory', $context);
652
                // Create the new category. This will create all the categories in the catpath,
653
                // though only the final category will have any info added if available.
654
                $category = new stdClass();
655
                $category->contextid = $context->id;
656
                $category->name = $catname;
657
                $category->info = '';
658
                // Only add info (category description) for the final category in the catpath.
659
                if ($key == (count($catnames) - 1) && $lastcategoryinfo) {
660
                    if (isset($lastcategoryinfo->info) && $lastcategoryinfo->info !== '') {
661
                        $category->info = $lastcategoryinfo->info;
662
                        if (isset($lastcategoryinfo->infoformat) && $lastcategoryinfo->infoformat !== '') {
663
                            $category->infoformat = $lastcategoryinfo->infoformat;
664
                        }
665
                    }
666
                    // Same for idnumber.
667
                    if (isset($lastcategoryinfo->idnumber) && $lastcategoryinfo->idnumber !== '') {
668
                        $category->idnumber = $lastcategoryinfo->idnumber;
669
                    }
670
                }
671
                $category->parent = $parent;
672
                $category->sortorder = 999;
673
                $category->stamp = make_unique_id_code();
674
                $category->id = $DB->insert_record('question_categories', $category);
675
                $parent = $category->id;
676
                $event = \core\event\question_category_created::create_from_question_category_instance($category, $context);
677
                $event->trigger();
678
            }
679
        }
680
        return $category;
681
    }
682
 
683
    /**
684
     * Return complete file within an array, one item per line
685
     * @param string filename name of file
686
     * @return mixed contents array or false on failure
687
     */
688
    protected function readdata($filename) {
689
        if (is_readable($filename)) {
690
            $filearray = file($filename);
691
 
692
            // If the first line of the file starts with a UTF-8 BOM, remove it.
693
            $filearray[0] = core_text::trim_utf8_bom($filearray[0]);
694
 
695
            // Check for Macintosh OS line returns (ie file on one line), and fix.
696
            if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) {
697
                return explode("\r", $filearray[0]);
698
            } else {
699
                return $filearray;
700
            }
701
        }
702
        return false;
703
    }
704
 
705
    /**
706
     * Parses an array of lines into an array of questions,
707
     * where each item is a question object as defined by
708
     * readquestion().   Questions are defined as anything
709
     * between blank lines.
710
     *
711
     * NOTE this method used to take $context as a second argument. However, at
712
     * the point where this method was called, it was impossible to know what
713
     * context the quetsions were going to be saved into, so the value could be
714
     * wrong. Also, none of the standard question formats were using this argument,
715
     * so it was removed. See MDL-32220.
716
     *
717
     * If your format does not use blank lines as a delimiter
718
     * then you will need to override this method. Even then
719
     * try to use readquestion for each question
720
     * @param array lines array of lines from readdata
721
     * @return array array of question objects
722
     */
723
    protected function readquestions($lines) {
724
 
725
        $questions = array();
726
        $currentquestion = array();
727
 
728
        foreach ($lines as $line) {
729
            $line = trim($line);
730
            if (empty($line)) {
731
                if (!empty($currentquestion)) {
732
                    if ($question = $this->readquestion($currentquestion)) {
733
                        $questions[] = $question;
734
                    }
735
                    $currentquestion = array();
736
                }
737
            } else {
738
                $currentquestion[] = $line;
739
            }
740
        }
741
 
742
        if (!empty($currentquestion)) {  // There may be a final question
743
            if ($question = $this->readquestion($currentquestion)) {
744
                $questions[] = $question;
745
            }
746
        }
747
 
748
        return $questions;
749
    }
750
 
751
    /**
752
     * return an "empty" question
753
     * Somewhere to specify question parameters that are not handled
754
     * by import but are required db fields.
755
     * This should not be overridden.
756
     * @return object default question
757
     */
758
    protected function defaultquestion() {
759
        global $CFG;
760
        static $defaultshuffleanswers = null;
761
        if (is_null($defaultshuffleanswers)) {
762
            $defaultshuffleanswers = get_config('quiz', 'shuffleanswers');
763
        }
764
 
765
        $question = new stdClass();
766
        $question->shuffleanswers = $defaultshuffleanswers;
767
        $question->defaultmark = 1;
768
        $question->image = '';
769
        $question->usecase = 0;
770
        $question->multiplier = array();
771
        $question->questiontextformat = FORMAT_MOODLE;
772
        $question->generalfeedback = '';
773
        $question->generalfeedbackformat = FORMAT_MOODLE;
774
        $question->answernumbering = 'abc';
775
        $question->penalty = 0.3333333;
776
        $question->length = 1;
777
 
778
        // this option in case the questiontypes class wants
779
        // to know where the data came from
780
        $question->export_process = true;
781
        $question->import_process = true;
782
 
783
        $this->add_blank_combined_feedback($question);
784
 
785
        return $question;
786
    }
787
 
788
    /**
789
     * Construct a reasonable default question name, based on the start of the question text.
790
     * @param string $questiontext the question text.
791
     * @param string $default default question name to use if the constructed one comes out blank.
792
     * @return string a reasonable question name.
793
     */
794
    public function create_default_question_name($questiontext, $default) {
795
        $name = $this->clean_question_name(shorten_text($questiontext, 80));
796
        if ($name) {
797
            return $name;
798
        } else {
799
            return $default;
800
        }
801
    }
802
 
803
    /**
804
     * Ensure that a question name does not contain anything nasty, and will fit in the DB field.
805
     * @param string $name the raw question name.
806
     * @return string a safe question name.
807
     */
808
    public function clean_question_name($name) {
809
        $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does.
810
        $name = trim($name);
811
        $trimlength = 251;
812
        while (core_text::strlen($name) > 255 && $trimlength > 0) {
813
            $name = shorten_text($name, $trimlength);
814
            $trimlength -= 10;
815
        }
816
        return $name;
817
    }
818
 
819
    /**
820
     * Add a blank combined feedback to a question object.
821
     * @param object question
822
     * @return object question
823
     */
824
    protected function add_blank_combined_feedback($question) {
825
        $question->correctfeedback = [
826
            'text' => '',
827
            'format' => $question->questiontextformat,
828
            'files' => []
829
        ];
830
        $question->partiallycorrectfeedback = [
831
            'text' => '',
832
            'format' => $question->questiontextformat,
833
            'files' => []
834
        ];
835
        $question->incorrectfeedback = [
836
            'text' => '',
837
            'format' => $question->questiontextformat,
838
            'files' => []
839
        ];
840
        return $question;
841
    }
842
 
843
    /**
844
     * Given the data known to define a question in
845
     * this format, this function converts it into a question
846
     * object suitable for processing and insertion into Moodle.
847
     *
848
     * If your format does not use blank lines to delimit questions
849
     * (e.g. an XML format) you must override 'readquestions' too
850
     * @param $lines mixed data that represents question
851
     * @return object question object
852
     */
853
    protected function readquestion($lines) {
854
        // We should never get there unless the qformat plugin is broken.
855
        throw new coding_exception('Question format plugin is missing important code: readquestion.');
856
 
857
        return null;
858
    }
859
 
860
    /**
861
     * Override if any post-processing is required
862
     * @return bool success
863
     */
864
    public function importpostprocess() {
865
        return true;
866
    }
867
 
868
    /*******************
869
     * EXPORT FUNCTIONS
870
     *******************/
871
 
872
    /**
873
     * Provide export functionality for plugin questiontypes
874
     * Do not override
875
     * @param name questiontype name
876
     * @param question object data to export
877
     * @param extra mixed any addition format specific data needed
878
     * @return string the data to append to export or false if error (or unhandled)
879
     */
880
    protected function try_exporting_using_qtypes($name, $question, $extra=null) {
881
        // work out the name of format in use
882
        $formatname = substr(get_class($this), strlen('qformat_'));
883
        $methodname = "export_to_{$formatname}";
884
 
885
        $qtype = question_bank::get_qtype($name, false);
886
        if (method_exists($qtype, $methodname)) {
887
            return $qtype->$methodname($question, $this, $extra);
888
        }
889
        return false;
890
    }
891
 
892
    /**
893
     * Do any pre-processing that may be required
894
     * @param bool success
895
     */
896
    public function exportpreprocess() {
897
        return true;
898
    }
899
 
900
    /**
901
     * Enable any processing to be done on the content
902
     * just prior to the file being saved
903
     * default is to do nothing
904
     * @param string output text
905
     * @param string processed output text
906
     */
907
    protected function presave_process($content) {
908
        return $content;
909
    }
910
 
911
    /**
912
     * Perform the export.
913
     * For most types this should not need to be overrided.
914
     *
915
     * @param   bool    $checkcapabilities Whether to check capabilities when exporting the questions.
916
     * @return  string  The content of the export.
917
     */
918
    public function exportprocess($checkcapabilities = true) {
919
        global $CFG, $DB;
920
 
921
        // Raise time and memory, as exporting can be quite intensive.
922
        core_php_time_limit::raise();
923
        raise_memory_limit(MEMORY_EXTRA);
924
 
925
        // Get the parents (from database) for this category.
926
        $parents = [];
927
        if ($this->category) {
928
            $parents = question_categorylist_parents($this->category->id);
929
        }
930
 
931
        // get the questions (from database) in this category
932
        // only get q's with no parents (no cloze subquestions specifically)
933
        if ($this->category) {
934
            // Export only the latest version of a question.
935
            $questions = get_questions_category($this->category, true, true, true, true);
936
        } else {
937
            $questions = $this->questions;
938
        }
939
 
940
        $count = 0;
941
 
942
        // results are first written into string (and then to a file)
943
        // so create/initialize the string here
944
        $expout = '';
945
 
946
        // track which category questions are in
947
        // if it changes we will record the category change in the output
948
        // file if selected. 0 means that it will get printed before the 1st question
949
        $trackcategory = 0;
950
 
951
        // Array of categories written to file.
952
        $writtencategories = [];
953
 
954
        foreach ($questions as $question) {
955
            // used by file api
956
            $questionbankentry = question_bank::load_question($question->id);
957
            $qcategory = $questionbankentry->category;
958
            $contextid = $DB->get_field('question_categories', 'contextid', ['id' => $qcategory]);
959
            $question->contextid = $contextid;
960
            $question->idnumber = $questionbankentry->idnumber;
1441 ariadna 961
 
962
            // Do not export hidden questions.
963
            if ($question->status === \core_question\local\bank\question_version_status::QUESTION_STATUS_HIDDEN) {
964
                continue;
965
            }
966
 
1 efrain 967
            if ($question->status === \core_question\local\bank\question_version_status::QUESTION_STATUS_READY) {
968
                $question->status = 0;
969
            } else {
970
                $question->status = 1;
971
            }
972
 
973
            // do not export random questions
974
            if ($question->qtype == 'random') {
975
                continue;
976
            }
977
 
978
            // check if we need to record category change
979
            if ($this->cattofile) {
980
                $addnewcat = false;
981
                if ($question->category != $trackcategory) {
982
                    $addnewcat = true;
983
                    $trackcategory = $question->category;
984
                }
985
                $trackcategoryparents = question_categorylist_parents($trackcategory);
986
                // Check if we need to record empty parents categories.
987
                foreach ($trackcategoryparents as $trackcategoryparent) {
988
                    // If parent wasn't written.
989
                    if (!in_array($trackcategoryparent, $writtencategories)) {
990
                        // If parent is empty.
991
                        if (!count($DB->get_records('question_bank_entries', ['questioncategoryid' => $trackcategoryparent]))) {
992
                            $categoryname = $this->get_category_path($trackcategoryparent, $this->contexttofile);
993
                            $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategoryparent),
994
                                'name, info, infoformat, idnumber', MUST_EXIST);
995
                            if ($categoryinfo->name != 'top') {
996
                                // Create 'dummy' question for parent category.
997
                                $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
998
                                $expout .= $this->writequestion($dummyquestion) . "\n";
999
                                $writtencategories[] = $trackcategoryparent;
1000
                            }
1001
                        }
1002
                    }
1003
                }
1004
                if ($addnewcat && !in_array($trackcategory, $writtencategories)) {
1005
                    $categoryname = $this->get_category_path($trackcategory, $this->contexttofile);
1006
                    $categoryinfo = $DB->get_record('question_categories', array('id' => $trackcategory),
1007
                            'info, infoformat, idnumber', MUST_EXIST);
1008
                    // Create 'dummy' question for category.
1009
                    $dummyquestion = $this->create_dummy_question_representing_category($categoryname, $categoryinfo);
1010
                    $expout .= $this->writequestion($dummyquestion) . "\n";
1011
                    $writtencategories[] = $trackcategory;
1012
                }
1013
            }
1014
 
1015
            // Add the question to result.
1016
            if (!$checkcapabilities || question_has_capability_on($question, 'view')) {
1017
                $expquestion = $this->writequestion($question, $contextid);
1018
                // Don't add anything if witequestion returned nothing.
1019
                // This will permit qformat plugins to exclude some questions.
1020
                if ($expquestion !== null) {
1021
                    $expout .= $expquestion . "\n";
1022
                    $count++;
1023
                }
1024
            }
1025
        }
1026
 
1441 ariadna 1027
        // Did we actually process anything? Then continue path for following error checks.
1 efrain 1028
        if ($count==0) {
1441 ariadna 1029
            $contextid = $DB->get_field('question_categories', 'contextid', ['id' => $this->category->id]);
1030
            $context = context::instance_by_id($contextid);
1031
            $continuepath = "{$CFG->wwwroot}/question/bank/exportquestions/export.php?cmid={$context->instanceid}";
1 efrain 1032
            throw new \moodle_exception('noquestions', 'question', $continuepath);
1033
        }
1034
 
1035
        // final pre-process on exported data
1036
        $expout = $this->presave_process($expout);
1037
        return $expout;
1038
    }
1039
 
1040
    /**
1041
     * Create 'dummy' question for category export.
1042
     * @param string $categoryname the name of the category
1043
     * @param object $categoryinfo description of the category
1044
     * @return stdClass 'dummy' question for category
1045
     */
1046
    protected function create_dummy_question_representing_category(string $categoryname, $categoryinfo) {
1047
        $dummyquestion = new stdClass();
1048
        $dummyquestion->qtype = 'category';
1049
        $dummyquestion->category = $categoryname;
1050
        $dummyquestion->id = 0;
1051
        $dummyquestion->questiontextformat = '';
1052
        $dummyquestion->contextid = 0;
1053
        $dummyquestion->info = $categoryinfo->info;
1054
        $dummyquestion->infoformat = $categoryinfo->infoformat;
1055
        $dummyquestion->idnumber = $categoryinfo->idnumber;
1056
        $dummyquestion->name = 'Switch category to ' . $categoryname;
1057
        return $dummyquestion;
1058
    }
1059
 
1060
    /**
1061
     * get the category as a path (e.g., tom/dick/harry)
1062
     * @param int id the id of the most nested catgory
1063
     * @return string the path
1064
     */
1065
    protected function get_category_path($id, $includecontext = true) {
1066
        global $DB;
1067
 
1068
        if (!$category = $DB->get_record('question_categories', array('id' => $id))) {
1069
            throw new \moodle_exception('cannotfindcategory', 'error', '', $id);
1070
        }
1071
        $contextstring = $this->translator->context_to_string($category->contextid);
1072
 
1073
        $pathsections = array();
1074
        do {
1075
            $pathsections[] = $category->name;
1076
            $id = $category->parent;
1077
        } while ($category = $DB->get_record('question_categories', array('id' => $id)));
1078
 
1079
        if ($includecontext) {
1080
            $pathsections[] = '$' . $contextstring . '$';
1081
        }
1082
 
1083
        $path = $this->assemble_category_path(array_reverse($pathsections));
1084
 
1085
        return $path;
1086
    }
1087
 
1088
    /**
1089
     * Convert a list of category names, possibly preceeded by one of the
1090
     * context tokens like $course$, into a string representation of the
1091
     * category path.
1092
     *
1093
     * Names are separated by / delimiters. And /s in the name are replaced by //.
1094
     *
1095
     * To reverse the process and split the paths into names, use
1096
     * {@link split_category_path()}.
1097
     *
1098
     * @param array $names
1099
     * @return string
1100
     */
1101
    protected function assemble_category_path($names) {
1102
        $escapednames = array();
1103
        foreach ($names as $name) {
1104
            $escapedname = str_replace('/', '//', $name);
1105
            if (substr($escapedname, 0, 1) == '/') {
1106
                $escapedname = ' ' . $escapedname;
1107
            }
1108
            if (substr($escapedname, -1) == '/') {
1109
                $escapedname = $escapedname . ' ';
1110
            }
1111
            $escapednames[] = $escapedname;
1112
        }
1113
        return implode('/', $escapednames);
1114
    }
1115
 
1116
    /**
1117
     * Convert a string, as returned by {@link assemble_category_path()},
1118
     * back into an array of category names.
1119
     *
1120
     * Each category name is cleaned by a call to clean_param(, PARAM_TEXT),
1121
     * which matches the cleaning in question/bank/managecategories/category_form.php.
1122
     *
1123
     * @param string $path
1124
     * @return array of category names.
1125
     */
1126
    protected function split_category_path($path) {
1127
        $rawnames = preg_split('~(?<!/)/(?!/)~', $path);
1128
        $names = array();
1129
        foreach ($rawnames as $rawname) {
1130
            $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT);
1131
        }
1132
        return $names;
1133
    }
1134
 
1135
    /**
1136
     * Do an post-processing that may be required
1137
     * @return bool success
1138
     */
1139
    protected function exportpostprocess() {
1140
        return true;
1141
    }
1142
 
1143
    /**
1144
     * convert a single question object into text output in the given
1145
     * format.
1146
     * This must be overriden
1147
     * @param object question question object
1148
     * @return mixed question export text or null if not implemented
1149
     */
1150
    protected function writequestion($question) {
1151
        // if not overidden, then this is an error.
1152
        throw new coding_exception('Question format plugin is missing important code: writequestion.');
1153
        return null;
1154
    }
1155
 
1156
    /**
1157
     * Convert the question text to plain text, so it can safely be displayed
1158
     * during import to let the user see roughly what is going on.
1159
     */
1160
    protected function format_question_text($question) {
1161
        return s(question_utils::to_plain_text($question->questiontext,
1162
                $question->questiontextformat));
1163
    }
1164
}
1165
 
1166
class qformat_based_on_xml extends qformat_default {
1167
 
1168
    /**
1169
     * A lot of imported files contain unwanted entities.
1170
     * This method tries to clean up all known problems.
1171
     * @param string str string to correct
1172
     * @return string the corrected string
1173
     */
1174
    public function cleaninput($str) {
1175
 
1176
        $html_code_list = array(
1177
            "&#039;" => "'",
1178
            "&#8217;" => "'",
1179
            "&#8220;" => "\"",
1180
            "&#8221;" => "\"",
1181
            "&#8211;" => "-",
1182
            "&#8212;" => "-",
1183
        );
1184
        $str = strtr($str, $html_code_list);
1185
        // Use core_text entities_to_utf8 function to convert only numerical entities.
1186
        $str = core_text::entities_to_utf8($str, false);
1187
        return $str;
1188
    }
1189
 
1190
    /**
1191
     * Return the array moodle is expecting
1192
     * for an HTML text. No processing is done on $text.
1193
     * qformat classes that want to process $text
1194
     * for instance to import external images files
1195
     * and recode urls in $text must overwrite this method.
1196
     * @param array $text some HTML text string
1197
     * @return array with keys text, format and files.
1198
     */
1199
    public function text_field($text) {
1200
        return array(
1201
            'text' => trim($text),
1202
            'format' => FORMAT_HTML,
1203
            'files' => array(),
1204
        );
1205
    }
1206
 
1207
    /**
1208
     * Return the value of a node, given a path to the node
1209
     * if it doesn't exist return the default value.
1210
     * @param array xml data to read
1211
     * @param array path path to node expressed as array
1212
     * @param mixed default
1213
     * @param bool istext process as text
1214
     * @param string error if set value must exist, return false and issue message if not
1215
     * @return mixed value
1216
     */
1217
    public function getpath($xml, $path, $default, $istext=false, $error='') {
1218
        foreach ($path as $index) {
1219
            if (!isset($xml[$index])) {
1220
                if (!empty($error)) {
1221
                    $this->error($error);
1222
                    return false;
1223
                } else {
1224
                    return $default;
1225
                }
1226
            }
1227
 
1228
            $xml = $xml[$index];
1229
        }
1230
 
1231
        if ($istext) {
1232
            if (!is_string($xml)) {
1233
                $this->error(get_string('invalidxml', 'qformat_xml'));
1234
            }
1235
            $xml = trim($xml);
1236
        }
1237
 
1238
        return $xml;
1239
    }
1240
}