Proyectos de Subversion Moodle

Rev

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