public function execute() { global $DB; foreach ($this->arguments as $argument) { try { $course = $DB->get_record('course', array('id' => $argument)); } catch (Exception $e) { print get_class($e) . " thrown within the exception handler. Message: " . $e->getMessage() . " on line " . $e->getLine(); } if ($course instanceof \stdClass) { delete_course($course); } else { print "Course not found\n"; } } fix_course_sortorder(); }
public function tearDown() { global $DB; if ($course = $DB->get_record('course', array('shortname' => 'simpletest'))) { delete_course($course, false); } }
/** * Test observer for course delete event. */ public function test_course_deleted() { global $DB; $this->setAdminUser(); $this->resetAfterTest(true); $user = $this->getDataGenerator()->create_user(); $course1 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $monitorgenerator = $this->getDataGenerator()->get_plugin_generator('tool_monitor'); $rule = new stdClass(); $rule->userid = $user->id; $rule->courseid = $course1->id; $rule->plugin = 'test'; $sub = new stdClass(); $sub->courseid = $course1->id; $sub->userid = $user->id; // Add 10 rules for this course with subscriptions. for ($i = 0; $i < 10; $i++) { $createdrule = $monitorgenerator->create_rule($rule); $sub->ruleid = $createdrule->id; $monitorgenerator->create_subscription($sub); } // Add 10 random rules for course 2. $rule->courseid = $course2->id; for ($i = 0; $i < 10; $i++) { $createdrule = $monitorgenerator->create_rule($rule); $sub->courseid = $rule->courseid; $sub->ruleid = $createdrule->id; $monitorgenerator->create_subscription($sub); } // Verify data before course delete. $totalrules = \tool_monitor\rule_manager::get_rules_by_plugin('test'); $this->assertCount(20, $totalrules); $courserules = \tool_monitor\rule_manager::get_rules_by_courseid($course1->id); $this->assertCount(10, $courserules); $totalsubs = $DB->get_records('tool_monitor_subscriptions'); $this->assertCount(20, $totalsubs); $coursesubs = \tool_monitor\subscription_manager::get_user_subscriptions_for_course($course1->id, 0, 0, $user->id); $this->assertCount(10, $coursesubs); // Let us delete the course now. delete_course($course1->id, false); // Verify data after course delete. $totalrules = \tool_monitor\rule_manager::get_rules_by_plugin('test'); $this->assertCount(10, $totalrules); $courserules = \tool_monitor\rule_manager::get_rules_by_courseid($course1->id); $this->assertCount(0, $courserules); // Making sure all rules are deleted. $totalsubs = $DB->get_records('tool_monitor_subscriptions'); $this->assertCount(10, $totalsubs); $coursesubs = \tool_monitor\subscription_manager::get_user_subscriptions_for_course($course1->id, 0, 0, $user->id); $this->assertCount(0, $coursesubs); // Making sure all subscriptions are deleted. }
public function test_hook_course_deleted() { $this->resetAfterTest(); $dg = $this->getDataGenerator(); $ccg = $dg->get_plugin_generator('core_competency'); $u1 = $dg->create_user(); $framework = $ccg->create_framework(); $comp1 = $ccg->create_competency(['competencyframeworkid' => $framework->get_id()]); $comp2 = $ccg->create_competency(['competencyframeworkid' => $framework->get_id()]); $c1 = $dg->create_course(); $cc1a = $ccg->create_course_competency(['competencyid' => $comp1->get_id(), 'courseid' => $c1->id]); $cc1b = $ccg->create_course_competency(['competencyid' => $comp2->get_id(), 'courseid' => $c1->id]); $assign1a = $dg->create_module('assign', ['course' => $c1]); $assign1b = $dg->create_module('assign', ['course' => $c1]); $cmc1a = $ccg->create_course_module_competency(['competencyid' => $comp1->get_id(), 'cmid' => $assign1a->cmid]); $cmc1b = $ccg->create_course_module_competency(['competencyid' => $comp1->get_id(), 'cmid' => $assign1b->cmid]); $ucc1a = $ccg->create_user_competency_course(['competencyid' => $comp1->get_id(), 'courseid' => $c1->id, 'userid' => $u1->id]); $ucc1b = $ccg->create_user_competency_course(['competencyid' => $comp2->get_id(), 'courseid' => $c1->id, 'userid' => $u1->id]); $c2 = $dg->create_course(); $cc2a = $ccg->create_course_competency(['competencyid' => $comp1->get_id(), 'courseid' => $c2->id]); $cc2b = $ccg->create_course_competency(['competencyid' => $comp2->get_id(), 'courseid' => $c2->id]); $assign2a = $dg->create_module('assign', ['course' => $c2]); $assign2b = $dg->create_module('assign', ['course' => $c2]); $cmc2a = $ccg->create_course_module_competency(['competencyid' => $comp1->get_id(), 'cmid' => $assign2a->cmid]); $cmc2b = $ccg->create_course_module_competency(['competencyid' => $comp1->get_id(), 'cmid' => $assign2b->cmid]); $ucc2a = $ccg->create_user_competency_course(['competencyid' => $comp1->get_id(), 'courseid' => $c2->id, 'userid' => $u1->id]); $ucc2b = $ccg->create_user_competency_course(['competencyid' => $comp2->get_id(), 'courseid' => $c2->id, 'userid' => $u1->id]); delete_course($c1, false); $this->assertEquals(0, course_competency::count_records(['courseid' => $c1->id])); $this->assertEquals(2, course_competency::count_records(['courseid' => $c2->id])); $this->assertEquals(0, course_module_competency::count_records(['cmid' => $assign1a->cmid])); $this->assertEquals(0, course_module_competency::count_records(['cmid' => $assign1b->cmid])); $this->assertEquals(1, course_module_competency::count_records(['cmid' => $assign2a->cmid])); $this->assertEquals(1, course_module_competency::count_records(['cmid' => $assign2b->cmid])); $this->assertEquals(0, user_competency_course::count_records(['courseid' => $c1->id, 'userid' => $u1->id])); $this->assertEquals(2, user_competency_course::count_records(['courseid' => $c2->id, 'userid' => $u1->id])); }
function restore($material, $action, $backup_id, $from_course_id = 0) { global $moduleFactory; require_once AT_INCLUDE_PATH . 'classes/pclzip.lib.php'; require_once AT_INCLUDE_PATH . '../mods/_core/file_manager/filemanager.inc.php'; if (!$from_course_id) { $from_course_id = $this->course_id; } // 1. get backup row/information $my_backup = $this->getRow($backup_id, $from_course_id); @mkdir(AT_CONTENT_DIR . 'import/' . $this->course_id); $this->import_dir = AT_CONTENT_DIR . 'import/' . $this->course_id . '/'; // 2. extract the backup $archive = new PclZip(AT_BACKUP_DIR . $from_course_id . '/' . $my_backup['system_file_name'] . '.zip'); if ($archive->extract(PCLZIP_OPT_PATH, $this->import_dir, PCLZIP_CB_PRE_EXTRACT, 'preImportCallBack') == 0) { die("Error : " . $archive->errorInfo(true)); } // 3. get the course's max_quota. if backup is too big AND we want to import files then abort/return FALSE /* get the course's max_quota */ // $this->getFilesSize(); // 4. figure out version number $this->version = $this->getVersion(); if (!$this->version) { clr_dir($this->import_dir); global $msg; $msg->addError('BACKUP_RESTORE'); header('Location: ' . $_SERVER['PHP_SELF']); exit; //exit('version not found. backups < 1.3 are not supported.'); } if (version_compare($this->version, VERSION, '>') == 1) { clr_dir($this->import_dir); global $msg; $msg->addError('BACKUP_UNSUPPORTED_GREATER_VERSION'); header('Location: ' . $_SERVER['PHP_SELF']); exit; } if (version_compare($this_version, '1.5.3', '<')) { if (file_exists($this->import_dir . 'resource_categories.csv')) { @rename($this->import_dir . 'resource_categories.csv', $this->import_dir . 'links_categories.csv'); } if (file_exists($this->import_dir . 'resource_links.csv')) { @rename($this->import_dir . 'resource_links.csv', $this->import_dir . 'links.csv'); } } // 5. if override is set then delete the content if ($action == 'overwrite') { require_once AT_INCLUDE_PATH . '../mods/_core/properties/lib/delete_course.inc.php'; delete_course($this->course_id, $material); $_SESSION['s_cid'] = 0; } // else: appending content if ($material === TRUE) { // restore the entire backup (used when creating a new course) $module_list = $moduleFactory->getModules(AT_MODULE_ENABLED | AT_MODULE_CORE); $_POST['material'] = $module_list; } foreach ($_POST['material'] as $module_name => $garbage) { // restore course properties, ONLY BANNER FOR NOW. if ($module_name == 'properties' && file_exists($this->import_dir . "properties.csv")) { global $db; $fp = @fopen($this->import_dir . "properties.csv", 'rb'); if (($row = @fgetcsv($fp, 70000)) !== false) { //hack for http://www.atutor.ca/atutor/mantis/view.php?id=3839 $row[0] = preg_replace('/\\\\r\\\\n/', "\r\n", $row[0]); $sql = "UPDATE " . TABLE_PREFIX . "courses \n\t\t\t\t\t SET banner = '" . mysql_real_escape_string($row[0]) . "' \n\t\t\t\t\t WHERE course_id = " . $this->course_id; $result = mysql_query($sql, $db) or die(mysql_error()); } } // restore modules $module = $moduleFactory->getModule($module_name); $module->restore($this->course_id, $this->version, $this->import_dir); } clr_dir($this->import_dir); }
/** * Delete course which is created by restore process */ public function cleanup() { global $DB; $courseid = $this->controller->get_courseid(); if ($this->is_temporary_course_created($courseid) && ($course = $DB->get_record('course', array('id' => $courseid)))) { $course->deletesource = 'restore'; delete_course($course, false); } }
/** * Test the cleanup task. */ public function test_cleanup_task() { global $DB; // Set the expiry to 1 week. set_config('categorybinexpiry', WEEKSECS, 'tool_recyclebin'); delete_course($this->course, false); $recyclebin = new \tool_recyclebin\category_bin($this->course->category); // Set deleted date to the distant past. foreach ($recyclebin->get_items() as $item) { $item->timecreated = time() - WEEKSECS; $DB->update_record('tool_recyclebin_category', $item); } // Create another course to delete. $course = $this->getDataGenerator()->create_course(); delete_course($course, false); // Should now be two courses in the recycle bin. $this->assertEquals(2, count($recyclebin->get_items())); // Execute cleanup task. $this->expectOutputRegex("/\\[tool_recyclebin\\] Deleting item '\\d+' from the category recycle bin/"); $task = new \tool_recyclebin\task\cleanup_category_bin(); $task->execute(); // Task should only have deleted the course where we updated the time. $courses = $recyclebin->get_items(); $this->assertEquals(1, count($courses)); $course = reset($courses); $this->assertEquals('Test course 2', $course->fullname); }
<?php $cid = isset($_POST['cid']) ? $_POST['cid'] : ''; $course = course_load($cid); if (isset($_POST['submit'])) { if (course_is_empty($_POST['id'])) { delete_course($_POST['id']); sleep(1); header('location: ' . currentURL() . '?p=course'); print 'Course deleted. Click <a href="?p=course">here</a> to view created courses'; } else { print '<span style="color: red;">This course contains ' . count_posts_from_cid($_POST['id']) . ' post' . (count_posts_from_cid($_POST['id']) == 0 || count_posts_from_cid($_POST['id']) == 1 ? '' : 's') . '. Please delete all the posts before deleting the course</span>'; } } ?> <h3>Do you want to delete the course "<?php print $course['Course_Name']; ?> "?</h3> <form method="post" action=""> <input type="hidden" name="id" value="<?php print $cid; ?> "/> <input type="submit" name="submit" value="Delete" /> <a class="button" href="?p=course">Cancel</a> </form>
/** * Delete course which is created by restore process */ public function cleanup() { $courseid = $this->controller->get_courseid(); if ($this->is_temporary_course_created($courseid)) { delete_course($courseid, false); } }
/** * Recursively delete category including all subcategories and courses * * Function {@link coursecat::can_delete_full()} MUST be called prior * to calling this function because there is no capability check * inside this function * * @param boolean $showfeedback display some notices * @return array return deleted courses * @throws moodle_exception */ public function delete_full($showfeedback = true) { global $CFG, $DB; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->libdir . '/questionlib.php'; require_once $CFG->dirroot . '/cohort/lib.php'; $deletedcourses = array(); // Get children. Note, we don't want to use cache here because it would be rebuilt too often. $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC'); foreach ($children as $record) { $coursecat = new coursecat($record); $deletedcourses += $coursecat->delete_full($showfeedback); } if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) { foreach ($courses as $course) { if (!delete_course($course, false)) { throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname); } $deletedcourses[] = $course; } } // Move or delete cohorts in this context. cohort_delete_category($this); // Now delete anything that may depend on course category context. grade_course_category_delete($this->id, 0, $showfeedback); if (!question_delete_course_category($this, 0, $showfeedback)) { throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name()); } // Finally delete the category and it's context. $DB->delete_records('course_categories', array('id' => $this->id)); $coursecatcontext = context_coursecat::instance($this->id); $coursecatcontext->delete(); cache_helper::purge_by_event('changesincoursecat'); // Trigger a course category deleted event. /* @var \core\event\course_category_deleted $event */ $event = \core\event\course_category_deleted::create(array('objectid' => $this->id, 'context' => $coursecatcontext, 'other' => array('name' => $this->name))); $event->set_coursecat($this); $event->trigger(); // If we deleted $CFG->defaultrequestcategory, make it point somewhere else. if ($this->id == $CFG->defaultrequestcategory) { set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0))); } return $deletedcourses; }
/** * Process the course data in the xml * * @param $groupnode * @param $xpath * @throws Exception * @throws coding_exception * @throws dml_missing_record_exception */ private function process_course_group_node($groupnode, $xpath) { global $DB, $CFG; $course = new stdClass(); if ($groupnode->getAttribute("recstatus") != 3) { $shortdesc = $xpath->evaluate("description/short", $groupnode)->item(0); if ($shortdesc) { $course->shortname = $shortdesc->nodeValue; } $longdesc = $xpath->evaluate("description/long", $groupnode)->item(0); if ($longdesc) { $course->fullname = $longdesc->nodeValue; } $idnumber = $xpath->evaluate("sourcedid/id", $groupnode)->item(0); if ($idnumber) { $course->idnumber = htmlspecialchars_decode($idnumber->nodeValue); } $course->format = 'topics'; $course->visible = 0; $course->timecreated = time(); $course->startdate = time(); $course->sortorder = 0; $parentgroup = $xpath->evaluate("relationship/sourcedid/id", $groupnode)->item(0); if ($parentgroup) { $parentid = $DB->get_field_select('course_categories', 'id', 'description=\'' . htmlspecialchars_decode($parentgroup->nodeValue) . '\''); if ($parentid) { $course->category = $parentid; } else { $course->category = 4; } } else { $course->category = 4; } $settings = $xpath->evaluate("extension/settings", $groupnode); foreach ($settings as $setting) { $key = $xpath->evaluate("setting", $setting)->item(0)->nodeValue; $val = $xpath->evaluate("value", $setting)->item(0)->nodeValue; $course->{$key} = $val; } if (!$DB->get_field('course', 'id', array('idnumber' => $course->idnumber))) { // New Course. if (!isset($course->numsections)) { $course->numsections = 10; } $courseid = $DB->insert_record('course', $course); // Setup the blocks. $course = $DB->get_record('course', array('id' => $courseid)); blocks_add_default_course_blocks($course); $section = new stdClass(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->summaryformat = FORMAT_HTML; $section->id = $DB->insert_record("course_sections", $section); $enrol = enrol_get_plugin('manual'); if ($audroleid = $DB->get_field('role', 'id', array('shortname' => 'auditor'))) { $enrol->add_instance($course, array('roleid' => $audroleid)); } else { $enrol->add_instance($course); } $coursemanagement = new stdClass(); // Get the start and end date for the course. $begin = $xpath->evaluate("timeframe/begin", $groupnode)->item(0); if ($begin) { $coursemanagement->startdate = $begin->nodeValue; } $end = $xpath->evaluate("timeframe/end", $groupnode)->item(0); if ($end) { $coursemanagement->enddate = $end->nodeValue; } if (isset($coursemanagement->startdate) && $coursemanagement->startdate > 0 && isset($coursemanagement->enddate) && $coursemanagement->enddate > 0) { // The course validly has both start and end dates. $coursemanagement->courseid = $course->id; $coursemanagement->timemodified = time(); $DB->insert_record("eclass_course_management", $coursemanagement); } else { if (isset($coursemanagement->startdate) || isset($coursemanagement->enddate)) { // Something isn't right with the start or end date. throw new Exception('UAIMS: Course Creation without valid start or end date'); } } // No else needed. No actions required if the course is validly lacking both start and end dates. } else { // Update existing Course, if corresponding eclass_course_management exist. Otherwise, create a // corresponding eclass_course_management entry. $ecourse = $DB->get_record('course', array('idnumber' => $course->idnumber), '*', MUST_EXIST); $enableqrtoggle = $this->get_config('enableqrvisibilitytoggle'); // Disable or enable QR toggling. if (!isset($enableqrtoggle) || !$enableqrtoggle) { unset($course->visible); } else { // Otherwise update the startend dates in the eclass_course_management table from uaims documents. $coursemanagement = $DB->get_record('eclass_course_management', array('courseid' => $ecourse->id), $fields = 'id', $strictness = IGNORE_MISSING); // Get the start and end date for the course. $begin = $xpath->evaluate("timeframe/begin", $groupnode)->item(0); $end = $xpath->evaluate("timeframe/end", $groupnode)->item(0); // To avoid errors when course is created outside of uaims (doesn't have eclass_course_management entry), // create and set appropriate attributes of $coursemanagement that matches eclass_course_management // database schema (or atleast NOT NULL fields). $coursemanagementexist = $coursemanagement != false; if (!$coursemanagementexist) { $enrol = enrol_get_plugin('manual'); if ($audroleid = $DB->get_field('role', 'id', array('shortname' => 'auditor'))) { $enrol->add_instance($ecourse, array('roleid' => $audroleid)); } else { $enrol->add_instance($ecourse); } $coursemanagement = new stdClass(); // The test process_imsdoc_test::test_process_imsdoc_should_update_course_with_minimal_imsdoc // implies that one of the requirement of this module is to ignore updates/insert in the case where // course exist, yet no start/end date. (Note this differ from the case where the course don't exist // in which case the requirements of this module requires it to throw an exception. if ($begin and $end) { // Set appropriate eclass_course_management row attributes and finally insert it to db. $coursemanagement->courseid = $ecourse->id; $coursemanagement->startdate = $begin->nodeValue; $coursemanagement->enddate = $end->nodeValue; $coursemanagement->timemodified = time(); $DB->insert_record("eclass_course_management", $coursemanagement); } } else { // Since corresponding eclass_course_management entry exist, only we don't need all parameters // to be present. Either/both $begin/$end dates is/are sufficient. if ($begin) { $coursemanagement->startdate = $begin->nodeValue; } if ($end) { $coursemanagement->enddate = $end->nodeValue; } if (isset($coursemanagement->startdate) || isset($coursemanagement->enddate)) { // If one of them is there then do the update. if ($coursemanagement->startdate || $coursemanagement->enddate) { $coursemanagement->timemodified = time(); $DB->update_record("eclass_course_management", $coursemanagement); } } } } // The $course var should never have an 'id' attribute, but lets make sure. if (isset($course->id)) { unset($course->id); } $ecourse = $this->extend($ecourse, $course); $DB->update_record('course', $ecourse); $classname = context_helper::get_class_for_level(CONTEXT_COURSE); $context = $classname::instance($ecourse->id, IGNORE_MISSING); $classname = context_helper::get_class_for_level(CONTEXT_COURSECAT); $newparent = $classname::instance($ecourse->category, IGNORE_MISSING); $context->update_moved($newparent); if (!($instanceid = $DB->get_field('enrol', 'id', array('enrol' => 'manual', 'courseid' => $ecourse->id)))) { $enrol = enrol_get_plugin('manual'); if ($audroleid = $DB->get_field('role', 'id', array('shortname' => 'auditor'))) { $enrol->add_instance($ecourse, array('roleid' => $audroleid)); } else { $enrol->add_instance(${$ecourse}); } } } } else { $idnumber = $xpath->evaluate("sourcedid/id", $groupnode)->item(0); if ($idnumber) { $idnumber = htmlspecialchars_decode($idnumber->nodeValue); $course = $DB->get_record('course', array('idnumber' => $idnumber)); delete_course($course, false); } } }
/** * Delete courses * * @param array $courseids A list of course ids * @since Moodle 2.2 */ public static function delete_courses($courseids) { global $CFG, $DB; require_once $CFG->dirroot . "/course/lib.php"; // Parameter validation. $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids' => $courseids)); $warnings = array(); foreach ($params['courseids'] as $courseid) { $course = $DB->get_record('course', array('id' => $courseid)); if ($course === false) { $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => 'unknowncourseidnumber', 'message' => 'Unknown course ID ' . $courseid); continue; } // Check if the context is valid. $coursecontext = context_course::instance($course->id); self::validate_context($coursecontext); // Check if the current user has permission. if (!can_delete_course($courseid)) { $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => 'cannotdeletecourse', 'message' => 'You do not have the permission to delete this course' . $courseid); continue; } if (delete_course($course, false) === false) { $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => 'cannotdeletecategorycourse', 'message' => 'Course ' . $courseid . ' failed to be deleted'); continue; } } fix_course_sortorder(); return array('warnings' => $warnings); }
public function test_sync() { global $CFG, $DB; $this->resetAfterTest(true); $metalplugin = enrol_get_plugin('meta'); $manplugin = enrol_get_plugin('manual'); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $user3 = $this->getDataGenerator()->create_user(); $user4 = $this->getDataGenerator()->create_user(); $user5 = $this->getDataGenerator()->create_user(); $course1 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $course3 = $this->getDataGenerator()->create_course(); $course4 = $this->getDataGenerator()->create_course(); $manual1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual3 = $DB->get_record('enrol', array('courseid' => $course3->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual4 = $DB->get_record('enrol', array('courseid' => $course4->id, 'enrol' => 'manual'), '*', MUST_EXIST); $student = $DB->get_record('role', array('shortname' => 'student')); $teacher = $DB->get_record('role', array('shortname' => 'teacher')); $manager = $DB->get_record('role', array('shortname' => 'manager')); $this->disable_plugin(); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->getDataGenerator()->enrol_user($user2->id, $course1->id, $student->id); $this->getDataGenerator()->enrol_user($user3->id, $course1->id, 0); $this->getDataGenerator()->enrol_user($user4->id, $course1->id, $teacher->id); $this->getDataGenerator()->enrol_user($user5->id, $course1->id, $manager->id); $this->getDataGenerator()->enrol_user($user1->id, $course2->id, $student->id); $this->getDataGenerator()->enrol_user($user2->id, $course2->id, $teacher->id); $this->assertEquals(7, $DB->count_records('user_enrolments')); $this->assertEquals(6, $DB->count_records('role_assignments')); set_config('syncall', 0, 'enrol_meta'); set_config('nosyncroleids', $manager->id, 'enrol_meta'); require_once $CFG->dirroot . '/enrol/meta/locallib.php'; enrol_meta_sync(null, false); $this->assertEquals(7, $DB->count_records('user_enrolments')); $this->assertEquals(6, $DB->count_records('role_assignments')); $this->enable_plugin(); enrol_meta_sync(null, false); $this->assertEquals(7, $DB->count_records('user_enrolments')); $this->assertEquals(6, $DB->count_records('role_assignments')); // Disable the plugin to prevent add_instance from calling enrol_meta_sync. $this->disable_plugin(); $e1 = $metalplugin->add_instance($course3, array('customint1' => $course1->id)); $e2 = $metalplugin->add_instance($course3, array('customint1' => $course2->id)); $e3 = $metalplugin->add_instance($course4, array('customint1' => $course2->id)); $enrol1 = $DB->get_record('enrol', array('id' => $e1)); $enrol2 = $DB->get_record('enrol', array('id' => $e2)); $enrol3 = $DB->get_record('enrol', array('id' => $e3)); $this->enable_plugin(); enrol_meta_sync($course4->id, false); $this->assertEquals(9, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol3, $teacher)); enrol_meta_sync(null, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(13, $DB->count_records('role_assignments')); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol1, $student)); $this->assertFalse($this->is_meta_enrolled($user3, $enrol1)); $this->assertTrue($this->is_meta_enrolled($user4, $enrol1, $teacher)); $this->assertFalse($this->is_meta_enrolled($user5, $enrol1)); $this->assertTrue($this->is_meta_enrolled($user1, $enrol2, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol2, $teacher)); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol3, $teacher)); set_config('syncall', 1, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(16, $DB->count_records('user_enrolments')); $this->assertEquals(13, $DB->count_records('role_assignments')); $this->assertTrue($this->is_meta_enrolled($user3, $enrol1, false)); $this->assertTrue($this->is_meta_enrolled($user5, $enrol1, false)); $this->assertEquals(16, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->disable_plugin(); $manplugin->unenrol_user($manual1, $user1->id); $manplugin->unenrol_user($manual2, $user1->id); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(11, $DB->count_records('role_assignments')); $this->assertEquals(14, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->enable_plugin(); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND, 'enrol_meta'); enrol_meta_sync($course4->id, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(11, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, $student)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol3->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); enrol_meta_sync(null, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(11, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol1->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol2, $student)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol2->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES, 'enrol_meta'); enrol_meta_sync($course4->id, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, false)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol3->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); enrol_meta_sync(null, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol1->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol2, false)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol2->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL, 'enrol_meta'); enrol_meta_sync($course4->id, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol3)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); $this->assertFalse($this->is_meta_enrolled($user1, $enrol2)); // Now try sync triggered by events. set_config('syncall', 1, 'enrol_meta'); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 0); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); set_config('syncall', 0, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(9, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(9, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 0); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); role_assign($teacher->id, $user1->id, context_course::instance($course1->id)->id); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $teacher)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $teacher)); role_unassign($teacher->id, $user1->id, context_course::instance($course1->id)->id); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(9, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(9, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); set_config('syncall', 1, 'enrol_meta'); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->update_user_enrol($manual1, $user1->id, ENROL_USER_SUSPENDED); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(9, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(9, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); set_config('syncall', 1, 'enrol_meta'); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); enrol_meta_sync(null, false); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); delete_course($course1, false); $this->assertEquals(3, $DB->count_records('user_enrolments')); $this->assertEquals(3, $DB->count_records('role_assignments')); $this->assertEquals(3, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); enrol_meta_sync(null, false); $this->assertEquals(3, $DB->count_records('user_enrolments')); $this->assertEquals(3, $DB->count_records('role_assignments')); $this->assertEquals(3, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); delete_course($course2, false); $this->assertEquals(0, $DB->count_records('user_enrolments')); $this->assertEquals(0, $DB->count_records('role_assignments')); $this->assertEquals(0, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); enrol_meta_sync(null, false); $this->assertEquals(0, $DB->count_records('user_enrolments')); $this->assertEquals(0, $DB->count_records('role_assignments')); $this->assertEquals(0, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); delete_course($course3, false); delete_course($course4, false); }
/** * There is no api involved so the best we can do is test legacy data by triggering event manually. */ public function test_course_viewed() { $user = $this->getDataGenerator()->create_user(); $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); // First try with no optional parameters. $eventparams = array(); $eventparams['context'] = $context; $event = \core\event\course_viewed::create($eventparams); // Trigger and capture the event. $sink = $this->redirectEvents(); $event->trigger(); $events = $sink->get_events(); $event = reset($events); $this->assertInstanceOf('\\core\\event\\course_viewed', $event); $this->assertEquals(context_course::instance($course->id), $event->get_context()); $expected = array($course->id, 'course', 'view', 'view.php?id=' . $course->id, $course->id); $this->assertEventLegacyLogData($expected, $event); $this->assertEventContextNotUsed($event); // Now try with optional parameters. $sectionid = 34; $eventparams = array(); $eventparams['context'] = $context; $eventparams['other'] = array('coursesectionid' => $sectionid); $event = \core\event\course_viewed::create($eventparams); // Trigger and capture the event. $sink = $this->redirectEvents(); $event->trigger(); $loggeddata = $event->get_data(); $events = $sink->get_events(); $event = reset($events); $this->assertInstanceOf('\\core\\event\\course_viewed', $event); $this->assertEquals(context_course::instance($course->id), $event->get_context()); $expected = array($course->id, 'course', 'view section', 'view.php?id=' . $course->id . '&section=' . $sectionid, $sectionid); $this->assertEventLegacyLogData($expected, $event); $this->assertEventContextNotUsed($event); delete_course($course->id, false); $restored = \core\event\base::restore($loggeddata, array('origin' => 'web', 'ip' => '127.0.0.1')); $this->assertInstanceOf('\\core\\event\\course_viewed', $restored); $this->assertNull($restored->get_url()); }
/** * Recursively delete category including all subcategories and courses * * Function {@link coursecat::can_delete_full()} MUST be called prior * to calling this function because there is no capability check * inside this function * * @param boolean $showfeedback display some notices * @return array return deleted courses */ public function delete_full($showfeedback = true) { global $CFG, $DB; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->libdir . '/questionlib.php'; require_once $CFG->dirroot . '/cohort/lib.php'; $deletedcourses = array(); // Get children. Note, we don't want to use cache here because // it would be rebuilt too often $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC'); foreach ($children as $record) { $coursecat = new coursecat($record); $deletedcourses += $coursecat->delete_full($showfeedback); } if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) { foreach ($courses as $course) { if (!delete_course($course, false)) { throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname); } $deletedcourses[] = $course; } } // move or delete cohorts in this context cohort_delete_category($this); // now delete anything that may depend on course category context grade_course_category_delete($this->id, 0, $showfeedback); if (!question_delete_course_category($this, 0, $showfeedback)) { throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name()); } // finally delete the category and it's context $DB->delete_records('course_categories', array('id' => $this->id)); delete_context(CONTEXT_COURSECAT, $this->id); add_to_log(SITEID, "category", "delete", "index.php", "{$this->name} (ID {$this->id})"); cache_helper::purge_by_event('changesincoursecat'); events_trigger('course_category_deleted', $this); // If we deleted $CFG->defaultrequestcategory, make it point somewhere else. if ($this->id == $CFG->defaultrequestcategory) { set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0))); } return $deletedcourses; }
function test_delete_all_for_context() { global $DB; $this->resetAfterTest(true); $this->setAdminUser(); $course = $this->getDataGenerator()->create_course(); $user = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->create_repository_type('flickr_public'); $this->getDataGenerator()->create_repository_type('filesystem'); $coursecontext = context_course::instance($course->id); $usercontext = context_user::instance($user->id); // Creating course instances. $repo = $this->getDataGenerator()->create_repository('flickr_public', array('contextid' => $coursecontext->id)); $courserepo1 = repository::get_repository_by_id($repo->id, $coursecontext); $this->assertEquals(1, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); $repo = $this->getDataGenerator()->create_repository('filesystem', array('contextid' => $coursecontext->id)); $courserepo2 = repository::get_repository_by_id($repo->id, $coursecontext); $this->assertEquals(2, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); // Creating user instances. $repo = $this->getDataGenerator()->create_repository('flickr_public', array('contextid' => $usercontext->id)); $userrepo1 = repository::get_repository_by_id($repo->id, $usercontext); $this->assertEquals(1, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); $repo = $this->getDataGenerator()->create_repository('filesystem', array('contextid' => $usercontext->id)); $userrepo2 = repository::get_repository_by_id($repo->id, $usercontext); $this->assertEquals(2, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); // Simulation of course deletion. repository::delete_all_for_context($coursecontext->id); $this->assertEquals(0, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); $this->assertEquals(0, $DB->count_records('repository_instances', array('id' => $courserepo1->id))); $this->assertEquals(0, $DB->count_records('repository_instances', array('id' => $courserepo2->id))); $this->assertEquals(0, $DB->count_records('repository_instance_config', array('instanceid' => $courserepo1->id))); $this->assertEquals(0, $DB->count_records('repository_instance_config', array('instanceid' => $courserepo2->id))); // Simulation of user deletion. repository::delete_all_for_context($usercontext->id); $this->assertEquals(0, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); $this->assertEquals(0, $DB->count_records('repository_instances', array('id' => $userrepo1->id))); $this->assertEquals(0, $DB->count_records('repository_instances', array('id' => $userrepo2->id))); $this->assertEquals(0, $DB->count_records('repository_instance_config', array('instanceid' => $userrepo1->id))); $this->assertEquals(0, $DB->count_records('repository_instance_config', array('instanceid' => $userrepo2->id))); // Checking deletion upon course context deletion. $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $repo = $this->getDataGenerator()->create_repository('flickr_public', array('contextid' => $coursecontext->id)); $courserepo = repository::get_repository_by_id($repo->id, $coursecontext); $this->assertEquals(1, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); $coursecontext->delete(); $this->assertEquals(0, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); // Checking deletion upon user context deletion. $user = $this->getDataGenerator()->create_user(); $usercontext = context_user::instance($user->id); $repo = $this->getDataGenerator()->create_repository('flickr_public', array('contextid' => $usercontext->id)); $userrepo = repository::get_repository_by_id($repo->id, $usercontext); $this->assertEquals(1, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); $usercontext->delete(); $this->assertEquals(0, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); // Checking deletion upon course deletion. $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $repo = $this->getDataGenerator()->create_repository('flickr_public', array('contextid' => $coursecontext->id)); $courserepo = repository::get_repository_by_id($repo->id, $coursecontext); $this->assertEquals(1, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); delete_course($course, false); $this->assertEquals(0, $DB->count_records('repository_instances', array('contextid' => $coursecontext->id))); // Checking deletion upon user deletion. $user = $this->getDataGenerator()->create_user(); $usercontext = context_user::instance($user->id); $repo = $this->getDataGenerator()->create_repository('flickr_public', array('contextid' => $usercontext->id)); $userrepo = repository::get_repository_by_id($repo->id, $usercontext); $this->assertEquals(1, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); delete_user($user); $this->assertEquals(0, $DB->count_records('repository_instances', array('contextid' => $usercontext->id))); }
/** * delete course data and content * * @return boolean success */ public function delete() { return delete_course($this->courseId, $this->sourceCourseId); }
/** * Restore an item from the recycle bin. * * @param \stdClass $item The item database record * @throws \moodle_exception */ public function restore_item($item) { global $CFG, $OUTPUT, $PAGE; require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; require_once $CFG->dirroot . '/course/lib.php'; $user = get_admin(); // Grab the course category context. $context = \context_coursecat::instance($this->_categoryid); // Get the backup file. $fs = get_file_storage(); $files = $fs->get_area_files($context->id, 'tool_recyclebin', TOOL_RECYCLEBIN_COURSECAT_BIN_FILEAREA, $item->id, 'itemid, filepath, filename', false); if (empty($files)) { throw new \moodle_exception('Invalid recycle bin item!'); } if (count($files) > 1) { throw new \moodle_exception('Too many files found!'); } // Get the backup file. $file = reset($files); // Get a temp directory name and create it. $tempdir = \restore_controller::get_tempdir_name($context->id, $user->id); $fulltempdir = make_temp_directory('/backup/' . $tempdir); // Extract the backup to tmpdir. $fb = get_file_packer('application/vnd.moodle.backup'); $fb->extract_to_pathname($file, $fulltempdir); // Build a course. $course = new \stdClass(); $course->category = $this->_categoryid; $course->shortname = $item->shortname; $course->fullname = $item->fullname; $course->summary = ''; // Create a new course. $course = create_course($course); if (!$course) { throw new \moodle_exception("Could not create course to restore into."); } // Define the import. $controller = new \restore_controller($tempdir, $course->id, \backup::INTERACTIVE_NO, \backup::MODE_GENERAL, $user->id, \backup::TARGET_NEW_COURSE); // Prechecks. if (!$controller->execute_precheck()) { $results = $controller->get_precheck_results(); // Check if errors have been found. if (!empty($results['errors'])) { // Delete the temporary file we created. fulldelete($fulltempdir); // Delete the course we created. delete_course($course, false); echo $OUTPUT->header(); $backuprenderer = $PAGE->get_renderer('core', 'backup'); echo $backuprenderer->precheck_notices($results); echo $OUTPUT->continue_button(new \moodle_url('/course/index.php', array('categoryid' => $this->_categoryid))); echo $OUTPUT->footer(); exit; } } // Run the import. $controller->execute_plan(); // Have finished with the controller, let's destroy it, freeing mem and resources. $controller->destroy(); // Fire event. $event = \tool_recyclebin\event\category_bin_item_restored::create(array('objectid' => $item->id, 'context' => $context)); $event->add_record_snapshot('tool_recyclebin_category', $item); $event->trigger(); // Cleanup. fulldelete($fulltempdir); $this->delete_item($item); }
$tool_content .= action_bar(array( array('title' => $langBack, 'url' => "listcours.php", 'icon' => 'fa-reply', 'level' => 'primary-label'))); } else { $tool_content .= action_bar(array( array('title' => $langBack, 'url' => "index.php", 'icon' => 'fa-reply', 'level' => 'primary-label'))); } // Delete course if (isset($_GET['delete']) && $course_id) { delete_course($course_id); $tool_content .= "<div class='alert alert-success'>" . $langCourseDelSuccess . "</div>"; } // Display confirmatiom message for course deletion else { if (!Database::get()->querySingle("SELECT * FROM course WHERE id = ?d", $course_id)) { $tool_content .= "<p class='right'><a href='index.php'>$langBack</a></p>"; draw($tool_content, 3); exit(); } $tool_content .= "<div class='alert alert-danger'>" . $langCourseDelConfirm2 . " <em>" . q(course_id_to_title($course_id)) . "</em>; <br><br><i>" . $langNoticeDel . "</i><br> </div>"; $tool_content .= "<ul class='list-group'> <li class='list-group-item'><a href='" . $_SERVER['SCRIPT_NAME'] . "?c=" . q($course_id) . "&delete=yes'><b>$langYes</b></a></li> <li class='list-group-item'><a href='listcours.php'><b>$langNo</b></a></li>
/** * Execute scheduled task * * @return boolean */ public function execute() { global $CFG, $DB; require_once $CFG->libdir . '/moodlelib.php'; require_once $CFG->libdir . '/filestorage/zip_packer.php'; require_once $CFG->dirroot . '/backup/util/includes/restore_includes.php'; // Get plugin config $local_sandbox_config = get_config('local_sandbox'); // Counter for restored courses $count = 0; // Do only when sandbox directory is configured if ($local_sandbox_config->coursebackupsdirectory != '') { // Do only when sandbox directory exists if (is_dir($local_sandbox_config->coursebackupsdirectory)) { // Open directory and get all .mbz files if ($handle = @opendir($local_sandbox_config->coursebackupsdirectory)) { while (false !== ($file = readdir($handle))) { if (substr($file, -4) == '.mbz' && $file != '.' && $file != '..') { // Get course shortname from filename $shortname = substr($file, 0, -4); echo "\n\t" . get_string('nowprocessing', 'local_sandbox', $shortname) . "\n"; // Get existing course information if ($oldcourse = $DB->get_record('course', array('shortname' => $shortname))) { $oldcourseid = $oldcourse->id; $categoryid = $oldcourse->category; $fullname = $oldcourse->fullname; } else { // Output error message for cron listing echo "\n\t" . get_string('skippingnocourse', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingnocourse', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Delete existing course if (!delete_course($oldcourseid, false)) { // Output error message for cron listing echo "\n\t" . get_string('skippingdeletionfailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingdeletionfailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Unzip course backup file to temp directory $filepacker = get_file_packer('application/vnd.moodle.backup'); check_dir_exists($CFG->dataroot . '/temp/backup'); if (!$filepacker->extract_to_pathname($local_sandbox_config->coursebackupsdirectory . '/' . $file, $CFG->dataroot . '/temp/backup/' . $shortname)) { // Output error message for cron listing echo "\n\t" . get_string('skippingunzipfailed', 'local_sandbox', $file) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingunzipfailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Create new course if (!($newcourseid = \restore_dbops::create_new_course($shortname, $shortname, $categoryid))) { // Output error message for cron listing echo "\n\t" . get_string('skippingcreatefailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingcreatefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Get admin user for restore $admin = get_admin(); $restoreuser = $admin->id; // Restore course backup file into new course if ($controller = new \restore_controller($shortname, $newcourseid, \backup::INTERACTIVE_NO, \backup::MODE_SAMESITE, $restoreuser, \backup::TARGET_NEW_COURSE)) { $controller->get_logger()->set_next(new \output_indented_logger(\backup::LOG_INFO, false, true)); $controller->execute_precheck(); $controller->execute_plan(); } else { // Output error message for cron listing echo "\n\t" . get_string('skippingrestorefailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingrestorefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } // Adjust course start date if ($local_sandbox_config->adjustcoursestartdate == true) { if (!$DB->update_record('course', (object) array('id' => $newcourseid, 'startdate' => time()))) { // Output error message for cron listing echo "\n\t" . get_string('skippingadjuststartdatefailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingadjuststartdatefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } } // Set shortname and fullname back if ($DB->update_record('course', (object) array('id' => $newcourseid, 'shortname' => $shortname, 'fullname' => $fullname))) { // Output info message for cron listing echo "\n\t" . get_string('successrestored', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('successrestored', 'local_sandbox', $shortname), SANDBOX_LEVEL_NOTICE); // Log the event $logevent = \local_sandbox\event\course_restored::create(array('objectid' => $newcourseid, 'context' => \context_course::instance($newcourseid))); $logevent->trigger(); // Fire course_updated event $course = $DB->get_record('course', array('id' => $newcourseid)); $ccevent = \core\event\course_created::create(array('objectid' => $course->id, 'context' => \context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname))); $ccevent->trigger(); // Count successfully restored course $count++; } else { // Output error message for cron listing echo "\n\t" . get_string('skippingdbupdatedfailed', 'local_sandbox', $shortname) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('skippingdbupdatefailed', 'local_sandbox', $shortname), SANDBOX_LEVEL_WARNING); continue; } } } closedir($handle); // Output info message for cron listing echo "\n\t" . get_string('noticerestorecount', 'local_sandbox', $count) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('noticerestorecount', 'local_sandbox', $count), SANDBOX_LEVEL_NOTICE); return true; } else { // Output error message for cron listing echo "\n\t" . get_string('errordirectorynotreadable', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('errordirectorynotreadable', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory), SANDBOX_LEVEL_ERROR); return false; } } else { // Output error message for cron listing echo "\n\t" . get_string('errordirectorynotexist', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory) . "\n"; // Inform admin local_sandbox_inform_admin(get_string('errordirectorynotexist', 'local_sandbox', $local_sandbox_config->coursebackupsdirectory), SANDBOX_LEVEL_ERROR); return false; } } else { // Output info message for cron listing echo "\n\t" . get_string('noticedirectorynotconfigured', 'local_sandbox') . "\n"; // Inform admin local_sandbox_inform_admin(get_string('noticedirectorynotconfigured', 'local_sandbox'), SANDBOX_LEVEL_NOTICE); return true; } }
/** * Test that triggering a course_deleted event works as expected. */ public function test_course_deleted_event() { $this->resetAfterTest(); // Create the course. $course = $this->getDataGenerator()->create_course(); // Save the course context before we delete the course. $coursecontext = context_course::instance($course->id); // Catch the update event. $sink = $this->redirectEvents(); // Call delete_course() which will trigger the course_deleted event and the course_content_deleted // event. This function prints out data to the screen, which we do not want during a PHPUnit test, // so use ob_start and ob_end_clean to prevent this. ob_start(); delete_course($course); ob_end_clean(); // Capture the event. $events = $sink->get_events(); $sink->close(); // Validate the event. $event = array_pop($events); $this->assertInstanceOf('\\core\\event\\course_deleted', $event); $this->assertEquals('course', $event->objecttable); $this->assertEquals($course->id, $event->objectid); $this->assertEquals($coursecontext->id, $event->contextid); $this->assertEquals($course, $event->get_record_snapshot('course', $course->id)); $this->assertEquals('course_deleted', $event->get_legacy_eventname()); $eventdata = $event->get_data(); $this->assertSame($course->idnumber, $eventdata['other']['idnumber']); $this->assertSame($course->fullname, $eventdata['other']['fullname']); $this->assertSame($course->shortname, $eventdata['other']['shortname']); // The legacy data also passed the context in the course object and substitutes timemodified with the current date. $expectedlegacy = clone $course; $expectedlegacy->context = $coursecontext; $expectedlegacy->timemodified = $event->timecreated; $this->assertEventLegacyData($expectedlegacy, $event); // Validate legacy log data. $expectedlog = array(SITEID, 'course', 'delete', 'view.php?id=' . $course->id, $course->fullname . '(ID ' . $course->id . ')'); $this->assertEventLegacyLogData($expectedlog, $event); $this->assertEventContextNotUsed($event); }
$stradministration = get_string("administration"); $strcategories = get_string("categories"); if (!($course = get_record("course", "id", $id))) { error("Course ID was incorrect (can't find it)"); } $category = get_record("course_categories", "id", $course->category); if (!$delete) { $strdeletecheck = get_string("deletecheck", "", $course->shortname); $strdeletecoursecheck = get_string("deletecoursecheck"); print_header("{$site->shortname}: {$strdeletecheck}", $site->fullname, "<a href=\"../{$CFG->admin}/index.php\">{$stradministration}</a> -> " . "<a href=\"index.php\">{$strcategories}</a> -> " . "<a href=\"category.php?id={$course->category}\">{$category->name}</a> -> " . "{$strdeletecheck}"); notice_yesno("{$strdeletecoursecheck}<br /><br />" . format_string($course->fullname) . " (" . format_string($course->shortname) . ")", "delete.php?id={$course->id}&delete=" . md5($course->timemodified) . "&sesskey={$USER->sesskey}", "category.php?id={$course->category}"); print_footer($course); exit; } if ($delete != md5($course->timemodified)) { error("The check variable was wrong - try again"); } if (!confirm_sesskey()) { error(get_string('confirmsesskeybad', 'error')); } // OK checks done, delete the course now. add_to_log(SITEID, "course", "delete", "view.php?id={$course->id}", "{$course->fullname} (ID {$course->id})"); $strdeletingcourse = get_string("deletingcourse", "", format_string($course->shortname)); print_header("{$site->shortname}: {$strdeletingcourse}", $site->fullname, "<a href=\"../{$CFG->admin}/index.php\">{$stradministration}</a> -> " . "<a href=\"index.php\">{$strcategories}</a> -> " . "<a href=\"category.php?id={$course->category}\">{$category->name}</a> -> " . "{$strdeletingcourse}"); print_heading($strdeletingcourse); delete_course($course->id); fix_course_sortorder(); //update course count in catagories print_heading(get_string("deletedcourse", "", format_string($course->shortname))); print_continue("category.php?id={$course->category}"); print_footer();
print_box_end(); } /// Editing functions if ($creatorediting) { /// Move a specified course to a new category if (!empty($deletecourses) and $data = data_submitted() and confirm_sesskey()) { // Some courses are being moved // user must have category update in both cats to perform this require_capability('moodle/category:update', $context); //require_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $moveto)); $courses = array(); foreach ($data as $key => $value) { if (preg_match('/^c\\d+$/', $key)) { $course = get_record("course", "id", substr($key, 1)); if (!empty($course)) { delete_course($course->id, false); // MDL-9983 events_trigger('course_deleted', $course); } } } fix_course_sortorder(); //update course count in catagories } if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) { // Some courses are being moved // user must have category update in both cats to perform this require_capability('moodle/category:update', $context); require_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $moveto)); if (!($destcategory = get_record("course_categories", "id", $data->moveto))) { error("Error finding the category");
/** * Test that event observer is executed on course deletion and the templates are removed. */ public function test_delete_course() { global $DB; $this->resetAfterTest(); feedback_save_as_template($this->eventfeedback, 'my template', 0); $courseid = $this->eventcourse->id; $this->assertNotEmpty($DB->get_records('feedback_template', array('course' => $courseid))); delete_course($this->eventcourse, false); $this->assertEmpty($DB->get_records('feedback_template', array('course' => $courseid))); }
navigation_node::override_active_url(new moodle_url('/course/management.php', array('categoryid' => $course->category))); $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext)); $coursefullname = format_string($course->fullname, true, array('context' => $coursecontext)); $categoryurl = new moodle_url('/course/management.php', array('categoryid' => $course->category)); // Check if we've got confirmation. if ($delete === md5($course->timemodified)) { // We do - time to delete the course. require_sesskey(); $strdeletingcourse = get_string("deletingcourse", "", $courseshortname); $PAGE->navbar->add($strdeletingcourse); $PAGE->set_title("{$SITE->shortname}: {$strdeletingcourse}"); $PAGE->set_heading($SITE->fullname); echo $OUTPUT->header(); echo $OUTPUT->heading($strdeletingcourse); // We do this here because it spits out feedback as it goes. delete_course($course); echo $OUTPUT->heading(get_string("deletedcourse", "", $courseshortname)); // Update course count in categories. fix_course_sortorder(); echo $OUTPUT->continue_button($categoryurl); echo $OUTPUT->footer(); exit; // We must exit here!!! } $strdeletecheck = get_string("deletecheck", "", $courseshortname); $strdeletecoursecheck = get_string("deletecoursecheck"); $message = "{$strdeletecoursecheck}<br /><br />{$coursefullname} ({$courseshortname})"; $continueurl = new moodle_url('/course/delete.php', array('id' => $course->id, 'delete' => md5($course->timemodified))); $PAGE->navbar->add($strdeletecheck); $PAGE->set_title("{$SITE->shortname}: {$strdeletecheck}"); $PAGE->set_heading($SITE->fullname);
/* as published by the Free Software Foundation. */ /************************************************************************/ // $Id$ define('AT_INCLUDE_PATH', '../../../../include/'); require AT_INCLUDE_PATH . 'vitals.inc.php'; admin_authenticate(AT_ADMIN_PRIV_COURSES); $course = intval($_REQUEST['course']); if (isset($_POST['submit_no'])) { $msg->addFeedback('CANCELLED'); header('Location: ../../courses/admin/courses.php'); exit; } else { if (isset($_POST['step']) && $_POST['step'] == 2 && isset($_POST['submit_yes'])) { require_once AT_INCLUDE_PATH . '../mods/_core/file_manager/filemanager.inc.php'; require AT_INCLUDE_PATH . '../mods/_core/properties/lib/delete_course.inc.php'; delete_course($course, $entire_course = true, $rel_path = '../'); // delete the course cache_purge('system_courses', 'system_courses'); // purge the system_courses cache (if successful) $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY'); header('Location: ../../courses/admin/courses.php'); exit; } } require AT_INCLUDE_PATH . 'header.inc.php'; if (!isset($_POST['step'])) { $hidden_vars['step'] = 1; $hidden_vars['course'] = $course; $msg->addConfirm(array('DELETE_COURSE_1', $system_courses[$course]['title']), $hidden_vars); $msg->printConfirm(); } else {
/** * Recursively delete category including all subcategories and courses. * @param stdClass $category * @param boolean $showfeedback display some notices * @return array return deleted courses */ function category_delete_full($category, $showfeedback = true) { global $CFG, $DB; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->libdir . '/questionlib.php'; require_once $CFG->dirroot . '/cohort/lib.php'; if ($children = $DB->get_records('course_categories', array('parent' => $category->id), 'sortorder ASC')) { foreach ($children as $childcat) { category_delete_full($childcat, $showfeedback); } } $deletedcourses = array(); if ($courses = $DB->get_records('course', array('category' => $category->id), 'sortorder ASC')) { foreach ($courses as $course) { if (!delete_course($course, false)) { throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname); } $deletedcourses[] = $course; } } // move or delete cohorts in this context cohort_delete_category($category); // now delete anything that may depend on course category context grade_course_category_delete($category->id, 0, $showfeedback); if (!question_delete_course_category($category, 0, $showfeedback)) { throw new moodle_exception('cannotdeletecategoryquestions', '', '', $category->name); } // finally delete the category and it's context $DB->delete_records('course_categories', array('id' => $category->id)); delete_context(CONTEXT_COURSECAT, $category->id); events_trigger('course_category_deleted', $category); return $deletedcourses; }
/** * Delete the current course. * * @return bool */ protected function delete() { global $DB; $this->id = $DB->get_field_select('course', 'id', 'shortname = :shortname', array('shortname' => $this->shortname), MUST_EXIST); return delete_course($this->id, false); }
/** * Delete courses * * @param array $courseids A list of course ids * @since Moodle 2.2 */ public static function delete_courses($courseids) { global $CFG, $DB; require_once($CFG->dirroot."/course/lib.php"); // Parameter validation. $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids)); $transaction = $DB->start_delegated_transaction(); foreach ($params['courseids'] as $courseid) { $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); // Check if the context is valid. $coursecontext = context_course::instance($course->id); self::validate_context($coursecontext); // Check if the current user has enought permissions. if (!can_delete_course($courseid)) { throw new moodle_exception('cannotdeletecategorycourse', 'error', '', format_string($course->fullname)." (id: $courseid)"); } delete_course($course, false); } $transaction->allow_commit(); return null; }
/** * Recursively delete category including all subcategories and courses. * @param object $ccategory * @return bool status */ function category_delete_full($category, $showfeedback = true) { global $CFG; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->libdir . '/questionlib.php'; if ($children = get_records('course_categories', 'parent', $category->id, 'sortorder ASC')) { foreach ($children as $childcat) { if (!category_delete_full($childcat, $showfeedback)) { notify("Error deleting category {$childcat->name}"); return false; } } } if ($courses = get_records('course', 'category', $category->id, 'sortorder ASC')) { foreach ($courses as $course) { if (!delete_course($course->id, false)) { notify("Error deleting course {$course->shortname}"); return false; } notify(get_string('coursedeleted', '', $course->shortname), 'notifysuccess'); } } // now delete anything that may depend on course category context grade_course_category_delete($category->id, 0, $showfeedback); if (!question_delete_course_category($category, 0, $showfeedback)) { notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess'); return false; } // finally delete the category and it's context delete_records('course_categories', 'id', $category->id); delete_context(CONTEXT_COURSECAT, $category->id); events_trigger('course_category_deleted', $category); notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess'); return true; }