Merge branch 'MDL-67070-master' of git://github.com/andrewnicols/moodle
[moodle.git] / question / type / random / classes / task / remove_unused_questions.php
CommitLineData
2fbd8e9e
TH
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 * A scheduled task to remove unneeded random questions.
19 *
20 * @package qtype_random
21 * @category task
22 * @copyright 2018 Bo Pierce <email.bO.pierce@gmail.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26namespace qtype_random\task;
27
28defined('MOODLE_INTERNAL') || die();
29
30
31/**
32 * A scheduled task to remove unneeded random questions.
33 *
34 * @copyright 2018 Bo Pierce <email.bO.pierce@gmail.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37class remove_unused_questions extends \core\task\scheduled_task {
38
39 public function get_name() {
40 return get_string('taskunusedrandomscleanup', 'qtype_random');
41 }
42
43 public function execute() {
44 global $DB, $CFG;
45 require_once($CFG->libdir . '/questionlib.php');
46
47 // Find potentially unused random questions (up to 10000).
48 // Note, because we call question_delete_question below,
49 // the question will not actually be deleted if something else
50 // is using them, but nothing else in Moodle core uses qtype_random,
51 // and not many third-party plugins do.
52 $unusedrandomids = $DB->get_records_sql("
53 SELECT q.id, 1
54 FROM {question} q
55 LEFT JOIN {quiz_slots} qslots ON q.id = qslots.questionid
56 WHERE qslots.questionid IS NULL
57 AND q.qtype = ? AND hidden = ?", ['random', 0], 0, 10000);
58
59 $count = 0;
60 foreach ($unusedrandomids as $unusedrandomid => $notused) {
61 question_delete_question($unusedrandomid);
62 // In case the question was not actually deleted (because it was in use somehow
63 // mark it as hidden so the query above will not return it again.
64 $DB->set_field('question', 'hidden', 1, ['id' => $unusedrandomid]);
65 $count += 1;
66 }
67 mtrace('Cleaned up ' . $count . ' unused random questions.');
68 }
69}