/** * All question categories and their questions are deleted for this context id. * * @param object $contextid The contextid to delete question categories from * @return array Feedback from deletes (if any) */ function question_delete_context($contextid) { global $DB; //To store feedback to be showed at the end of the process $feedbackdata = array(); //Cache some strings $strcatdeleted = get_string('unusedcategorydeleted', 'question'); $fields = 'id, parent, name, contextid'; if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) { //Sort categories following their tree (parent-child) relationships //this will make the feedback more readable $categories = sort_categories_by_tree($categories); foreach ($categories as $category) { question_category_delete_safe($category); //Fill feedback $feedbackdata[] = array($category->name, $strcatdeleted); } } return $feedbackdata; }
/** * This function tests the question_category_delete_safe function. */ public function test_question_category_delete_safe() { global $DB; $this->resetAfterTest(true); $this->setAdminUser(); list($category, $course, $quiz, $qcat, $questions) = $this->setup_quiz_and_questions(); question_category_delete_safe($qcat); // Verify category deleted. $criteria = array('id' => $qcat->id); $this->assertEquals(0, $DB->count_records('question_categories', $criteria)); // Verify questions deleted or moved. $criteria = array('category' => $qcat->id); $this->assertEquals(0, $DB->count_records('question', $criteria)); // Verify question not deleted. $criteria = array('id' => $questions[0]->id); $this->assertEquals(1, $DB->count_records('question', $criteria)); }
} cli_heading('Checking for orphaned categories'); $sql = 'SELECT qc.id, qc.contextid, qc.name FROM {question_categories} qc LEFT JOIN {context} c ON qc.contextid = c.id WHERE c.id IS NULL'; $categories = $DB->get_recordset_sql($sql); $i = 0; foreach ($categories as $category) { $i += 1; echo "Found orphaned category: {$category->name}\n"; if (!empty($options['fix'])) { echo "Cleaning..."; // One transaction per category. $transaction = $DB->start_delegated_transaction(); question_category_delete_safe($category); $transaction->allow_commit(); echo " Done!\n"; } } if ($i > 0 && !empty($options['fix'])) { echo "Found and removed {$i} orphaned question categories\n"; } else { if ($i > 0) { echo "Found {$i} orphaned question categories. To fix, run:\n"; echo "\$sudo -u www-data /usr/bin/php admin/cli/fix_orphaned_question_categories.php --fix\n"; } else { echo "No orphaned question categories found.\n"; } } $categories->close();