function create_course_pditt($category,$idnumber,$kodemk,$namamk,$summary,$startdate=0,$visible=0,$format='topics'){ global $DB, $CFG; //$x = $DB->get_record('course', array('idnumber'=>$idnumber, 'shortname'=>$kodemk), '*'); $x = $DB->get_record('course', array('idnumber'=>$idnumber), '*'); if (!$x) { $data = new stdClass(); $data->category=$category; $data->idnumber = $idnumber; $data->fullname=$namamk; $data->shortname = $kodemk; $data->summary = $summary; $data->summaryformat=0; $data->format=$format; $data->startdate = $startdate; $data->showgrades=1; $data->visible=$visible; $h=create_course($data); return $h->id; } else { $data = new stdClass(); $data->fullname=$namamk; $data->idnumber = $idnumber; $data->shortname = $kodemk; $data->summary = $summary; $data->id = $x->id; update_course($data); return $x->id; } }
public function test_update_course_numsections() { global $DB; $this->resetAfterTest(true); $generator = $this->getDataGenerator(); $course = $generator->create_course(array('numsections' => 10, 'format' => 'weeks'), array('createsections' => true)); $generator->create_module('assign', array('course' => $course, 'section' => 7)); $this->setAdminUser(); $this->assertEquals(11, $DB->count_records('course_sections', array('course' => $course->id))); // Change the numsections to 8, last two sections did not have any activities, they should be deleted. update_course((object) array('id' => $course->id, 'numsections' => 8)); $this->assertEquals(9, $DB->count_records('course_sections', array('course' => $course->id))); $this->assertEquals(9, count(get_fast_modinfo($course)->get_section_info_all())); // Change the numsections to 5, section 8 should be deleted but section 7 should remain as it has activities. update_course((object) array('id' => $course->id, 'numsections' => 6)); $this->assertEquals(8, $DB->count_records('course_sections', array('course' => $course->id))); $this->assertEquals(8, count(get_fast_modinfo($course)->get_section_info_all())); $this->assertEquals(6, course_get_format($course)->get_course()->numsections); }
/** * Automatically clean-up all plugin data and remove the plugin DB tables * * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc. * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc. * @uses global $OUTPUT to produce notices and other messages * @return void */ function uninstall_plugin($type, $name) { global $CFG, $DB, $OUTPUT; // This may take a long time. @set_time_limit(0); // recursively uninstall all module/editor subplugins first if ($type === 'mod' || $type === 'editor') { $base = get_component_directory($type . '_' . $name); if (file_exists("{$base}/db/subplugins.php")) { $subplugins = array(); include "{$base}/db/subplugins.php"; foreach ($subplugins as $subplugintype => $dir) { $instances = get_plugin_list($subplugintype); foreach ($instances as $subpluginname => $notusedpluginpath) { uninstall_plugin($subplugintype, $subpluginname); } } } } $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum' if ($type === 'mod') { $pluginname = $name; // eg. 'forum' if (get_string_manager()->string_exists('modulename', $component)) { $strpluginname = get_string('modulename', $component); } else { $strpluginname = $component; } } else { $pluginname = $component; if (get_string_manager()->string_exists('pluginname', $component)) { $strpluginname = get_string('pluginname', $component); } else { $strpluginname = $component; } } echo $OUTPUT->heading($pluginname); $plugindirectory = get_plugin_directory($type, $name); $uninstalllib = $plugindirectory . '/db/uninstall.php'; if (file_exists($uninstalllib)) { require_once $uninstalllib; $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()' if (function_exists($uninstallfunction)) { if (!$uninstallfunction()) { echo $OUTPUT->notification('Encountered a problem running uninstall function for ' . $pluginname); } } } if ($type === 'mod') { // perform cleanup tasks specific for activity modules if (!($module = $DB->get_record('modules', array('name' => $name)))) { print_error('moduledoesnotexist', 'error'); } // delete all the relevant instances from all course sections if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) { foreach ($coursemods as $coursemod) { if (!delete_mod_from_section($coursemod->id, $coursemod->section)) { echo $OUTPUT->notification("Could not delete the {$strpluginname} with id = {$coursemod->id} from section {$coursemod->section}"); } } } // clear course.modinfo for courses that used this module $sql = "UPDATE {course}\n SET modinfo=''\n WHERE id IN (SELECT DISTINCT course\n FROM {course_modules}\n WHERE module=?)"; $DB->execute($sql, array($module->id)); // delete all the course module records $DB->delete_records('course_modules', array('module' => $module->id)); // delete module contexts if ($coursemods) { foreach ($coursemods as $coursemod) { if (!delete_context(CONTEXT_MODULE, $coursemod->id)) { echo $OUTPUT->notification("Could not delete the context for {$strpluginname} with id = {$coursemod->id}"); } } } // delete the module entry itself $DB->delete_records('modules', array('name' => $module->name)); // cleanup the gradebook require_once $CFG->libdir . '/gradelib.php'; grade_uninstalled_module($module->name); // Perform any custom uninstall tasks if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) { require_once $CFG->dirroot . '/mod/' . $module->name . '/lib.php'; $uninstallfunction = $module->name . '_uninstall'; if (function_exists($uninstallfunction)) { debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER); if (!$uninstallfunction()) { echo $OUTPUT->notification('Encountered a problem running uninstall function for ' . $module->name . '!'); } } } } else { if ($type === 'enrol') { // NOTE: this is a bit brute force way - it will not trigger events and hooks properly // nuke all role assignments role_unassign_all(array('component' => $component)); // purge participants $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name)); // purge enrol instances $DB->delete_records('enrol', array('enrol' => $name)); // tweak enrol settings if (!empty($CFG->enrol_plugins_enabled)) { $enabledenrols = explode(',', $CFG->enrol_plugins_enabled); $enabledenrols = array_unique($enabledenrols); $enabledenrols = array_flip($enabledenrols); unset($enabledenrols[$name]); $enabledenrols = array_flip($enabledenrols); if (is_array($enabledenrols)) { set_config('enrol_plugins_enabled', implode(',', $enabledenrols)); } } } else { if ($type === 'block') { if ($block = $DB->get_record('block', array('name' => $name))) { // Inform block it's about to be deleted if (file_exists("{$CFG->dirroot}/blocks/{$block->name}/block_{$block->name}.php")) { $blockobject = block_instance($block->name); if ($blockobject) { $blockobject->before_delete(); //only if we can create instance, block might have been already removed } } // First delete instances and related contexts $instances = $DB->get_records('block_instances', array('blockname' => $block->name)); foreach ($instances as $instance) { blocks_delete_instance($instance); } // Delete block $DB->delete_records('block', array('id' => $block->id)); } } else { if ($type === 'format') { if (($defaultformat = get_config('moodlecourse', 'format')) && $defaultformat !== $name) { $courses = $DB->get_records('course', array('format' => $name), 'id'); $data = (object) array('id' => null, 'format' => $defaultformat); foreach ($courses as $record) { $data->id = $record->id; update_course($data); } } $DB->delete_records('course_format_options', array('format' => $name)); } } } } // perform clean-up task common for all the plugin/subplugin types //delete the web service functions and pre-built services require_once $CFG->dirroot . '/lib/externallib.php'; external_delete_descriptions($component); // delete calendar events $DB->delete_records('event', array('modulename' => $pluginname)); // delete all the logs $DB->delete_records('log', array('module' => $pluginname)); // delete log_display information $DB->delete_records('log_display', array('component' => $component)); // delete the module configuration records unset_all_config_for_plugin($pluginname); // delete message provider message_provider_uninstall($component); // delete message processor if ($type === 'message') { message_processor_uninstall($name); } // delete the plugin tables $xmldbfilepath = $plugindirectory . '/db/install.xml'; drop_plugin_tables($component, $xmldbfilepath, false); if ($type === 'mod' or $type === 'block') { // non-frankenstyle table prefixes drop_plugin_tables($name, $xmldbfilepath, false); } // delete the capabilities that were defined by this module capabilities_cleanup($component); // remove event handlers and dequeue pending events events_uninstall($component); // Delete all remaining files in the filepool owned by the component. $fs = get_file_storage(); $fs->delete_component_files($component); // Finally purge all caches. purge_all_caches(); echo $OUTPUT->notification(get_string('success'), 'notifysuccess'); }
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/reou/controllers/courses_controller.php'; // We are going to update or edit course update_course($db, $_POST); # Or # list($course_details, $course_schedules, $course_categories, $instructors) = course_edit($db); $weekdays = array("Sunday", "Monday", "Tuesday", "Wedesday", "Thursday", "Friday", "Saturday"); require_once $_SERVER['DOCUMENT_ROOT'] . '/reou/views/layouts/header.php'; // Load course_schedule result to be used in javascript variable. ?> <script> var course_schedules = <?php echo json_encode($course_schedules); ?> ; console.log(course_schedules); console.log("variable - course_schedules"); </script> <!-- Courses. Thisgs we would liek to update --> <!-- - The Goal today is to be able to create a course then create a schedule for that course.
/** * Changes the visibility of a course. * * @param int $courseid The course to change. * @param bool $show True to make it visible, false otherwise. * @return bool */ function course_change_visibility($courseid, $show = true) { $course = new stdClass(); $course->id = $courseid; $course->visible = $show ? '1' : '0'; $course->visibleold = $course->visible; update_course($course); return true; }
/** * Test that triggering a course_updated event works as expected. */ public function test_course_updated_event() { global $DB; $this->resetAfterTest(); // Create a course. $course = $this->getDataGenerator()->create_course(); // Create a category we are going to move this course to. $category = $this->getDataGenerator()->create_category(); // Create a hidden category we are going to move this course to. $categoryhidden = $this->getDataGenerator()->create_category(array('visible' => 0)); // Update course and catch course_updated event. $sink = $this->redirectEvents(); update_course($course); $events = $sink->get_events(); $sink->close(); // Get updated course information from the DB. $updatedcourse = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST); // Validate event. $event = array_shift($events); $this->assertInstanceOf('\\core\\event\\course_updated', $event); $this->assertEquals('course', $event->objecttable); $this->assertEquals($updatedcourse->id, $event->objectid); $this->assertEquals(context_course::instance($course->id), $event->get_context()); $url = new moodle_url('/course/edit.php', array('id' => $event->objectid)); $this->assertEquals($url, $event->get_url()); $this->assertEquals($updatedcourse, $event->get_record_snapshot('course', $event->objectid)); $this->assertEquals('course_updated', $event->get_legacy_eventname()); $this->assertEventLegacyData($updatedcourse, $event); $expectedlog = array($updatedcourse->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id); $this->assertEventLegacyLogData($expectedlog, $event); // Move course and catch course_updated event. $sink = $this->redirectEvents(); move_courses(array($course->id), $category->id); $events = $sink->get_events(); $sink->close(); // Return the moved course information from the DB. $movedcourse = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST); // Validate event. $event = array_shift($events); $this->assertInstanceOf('\\core\\event\\course_updated', $event); $this->assertEquals('course', $event->objecttable); $this->assertEquals($movedcourse->id, $event->objectid); $this->assertEquals(context_course::instance($course->id), $event->get_context()); $this->assertEquals($movedcourse, $event->get_record_snapshot('course', $movedcourse->id)); $this->assertEquals('course_updated', $event->get_legacy_eventname()); $this->assertEventLegacyData($movedcourse, $event); $expectedlog = array($movedcourse->id, 'course', 'move', 'edit.php?id=' . $movedcourse->id, $movedcourse->id); $this->assertEventLegacyLogData($expectedlog, $event); // Move course to hidden category and catch course_updated event. $sink = $this->redirectEvents(); move_courses(array($course->id), $categoryhidden->id); $events = $sink->get_events(); $sink->close(); // Return the moved course information from the DB. $movedcoursehidden = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST); // Validate event. $event = array_shift($events); $this->assertInstanceOf('\\core\\event\\course_updated', $event); $this->assertEquals('course', $event->objecttable); $this->assertEquals($movedcoursehidden->id, $event->objectid); $this->assertEquals(context_course::instance($course->id), $event->get_context()); $this->assertEquals($movedcoursehidden, $event->get_record_snapshot('course', $movedcoursehidden->id)); $this->assertEquals('course_updated', $event->get_legacy_eventname()); $this->assertEventLegacyData($movedcoursehidden, $event); $expectedlog = array($movedcoursehidden->id, 'course', 'move', 'edit.php?id=' . $movedcoursehidden->id, $movedcoursehidden->id); $this->assertEventLegacyLogData($expectedlog, $event); $this->assertEventContextNotUsed($event); }
// assign default role to creator if not already having permission to manage course assignments if (!has_capability('moodle/course:view', $context) or !has_capability('moodle/role:assign', $context)) { role_assign($CFG->creatornewroleid, $USER->id, 0, $context->id); } // ensure we can use the course right after creating it // this means trigger a reload of accessinfo... mark_context_dirty($context->path); if ($data->metacourse and has_capability('moodle/course:managemetacourse', $context)) { // Redirect users with metacourse capability to student import redirect($CFG->wwwroot . "/course/importstudents.php?id={$course->id}"); } else { // Redirect to roles assignment redirect($CFG->wwwroot . "/{$CFG->admin}/roles/assign.php?contextid={$context->id}"); } } else { if (!update_course($data)) { print_error('coursenotupdated'); } redirect($CFG->wwwroot . "/course/view.php?id={$course->id}"); } } } /// Print the form $site = get_site(); $streditcoursesettings = get_string("editcoursesettings"); $straddnewcourse = get_string("addnewcourse"); $stradministration = get_string("administration"); $strcategories = get_string("categories"); $navlinks = array(); if (!empty($course)) { $navlinks[] = array('name' => $streditcoursesettings, 'link' => null, 'type' => 'misc');
} if (!is_enrolled($context)) { // Redirect to manual enrolment page if possible $instances = enrol_get_instances($course->id, true); foreach($instances as $instance) { if ($plugin = enrol_get_plugin($instance->enrol)) { if ($plugin->get_manual_enrol_link($instance)) { // we know that the ajax enrol UI will have an option to enrol redirect(new moodle_url('/enrol/users.php', array('id'=>$course->id))); } } } } } else { // Save any changes to the files used in the editor update_course($data, $editoroptions); } rebuild_course_cache($course->id); // Redirect user to newly created/updated course. redirect(new moodle_url('/course/view.php', array('id' => $course->id))); } // Print the form $site = get_site(); $streditcoursesettings = get_string("editcoursesettings"); $straddnewcourse = get_string("addnewcourse"); $stradministration = get_string("administration");
/** * Proceed with the import of the course. * * @return void */ public function proceed() { global $CFG, $USER; if (!$this->prepared) { throw new coding_exception('The course has not been prepared.'); } else { if ($this->has_errors()) { throw new moodle_exception('Cannot proceed, errors were detected.'); } else { if ($this->processstarted) { throw new coding_exception('The process has already been started.'); } } } $this->processstarted = true; if ($this->do === self::DO_DELETE) { if ($this->delete()) { $this->status('coursedeleted', new lang_string('coursedeleted', 'tool_uploadcourse')); } else { $this->error('errorwhiledeletingcourse', new lang_string('errorwhiledeletingcourse', 'tool_uploadcourse')); } return true; } else { if ($this->do === self::DO_CREATE) { $course = create_course((object) $this->data); $this->id = $course->id; $this->status('coursecreated', new lang_string('coursecreated', 'tool_uploadcourse')); } else { if ($this->do === self::DO_UPDATE) { $course = (object) $this->data; update_course($course); $this->id = $course->id; $this->status('courseupdated', new lang_string('courseupdated', 'tool_uploadcourse')); } else { // Strangely the outcome has not been defined, or is unknown! throw new coding_exception('Unknown outcome!'); } } } // Restore a course. if (!empty($this->restoredata)) { $rc = new restore_controller($this->restoredata, $course->id, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING); // Check if the format conversion must happen first. if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) { $rc->convert(); } if ($rc->execute_precheck()) { $rc->execute_plan(); $this->status('courserestored', new lang_string('courserestored', 'tool_uploadcourse')); } else { $this->error('errorwhilerestoringcourse', new lang_string('errorwhilerestoringthecourse', 'tool_uploadcourse')); } $rc->destroy(); } // Proceed with enrolment data. $this->process_enrolment_data($course); // Reset the course. if ($this->importoptions['reset'] || $this->options['reset']) { if ($this->do === self::DO_UPDATE && $this->can_reset()) { $this->reset($course); $this->status('coursereset', new lang_string('coursereset', 'tool_uploadcourse')); } } // Mark context as dirty. $context = context_course::instance($course->id); $context->mark_dirty(); }
public function test_update_course() { global $DB; $this->resetAfterTest(); $defaultcategory = $DB->get_field_select('course_categories', "MIN(id)", "parent=0"); $course = new stdClass(); $course->fullname = 'Apu loves Unit Təsts'; $course->shortname = 'test1'; $course->idnumber = '1'; $course->summary = 'Awesome!'; $course->summaryformat = FORMAT_PLAIN; $course->format = 'topics'; $course->newsitems = 0; $course->numsections = 5; $course->category = $defaultcategory; $created = create_course($course); // Ensure the checks only work on idnumber/shortname that are not already ours. update_course($created); $course->shortname = 'test2'; $course->idnumber = '2'; $created2 = create_course($course); // Test duplicate idnumber. $created2->idnumber = '1'; try { update_course($created2); $this->fail('Expected exception when trying to update a course with duplicate idnumber'); } catch (moodle_exception $e) { $this->assertEquals(get_string('idnumbertaken', 'error'), $e->getMessage()); } // Test duplicate shortname. $created2->idnumber = '2'; $created2->shortname = 'test1'; try { update_course($created2); $this->fail('Expected exception when trying to update a course with a duplicate shortname'); } catch (moodle_exception $e) { $this->assertEquals(get_string('shortnametaken', 'error', $created2->shortname), $e->getMessage()); } }
if ($query->is_empty()) { $rollback = true; return array(SERVER_ERROR, "{\"success\":false}"); } return array(OKAY, json_encode($query->get_row_assoc())); }); http_response_code($code); return $json; } header('Content-Type: application/json'); if (!abet_is_admin_authenticated()) { page_fail(UNAUTHORIZED); } if ($_SERVER['REQUEST_METHOD'] == 'GET') { $obj = new stdClass(); $obj->courses = get_courses(); $obj->profiles = get_profiles(); echo json_encode($obj); } else { if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!array_key_exists('id', $_POST)) { // create new course echo create_course(isset($_POST['title']) ? $_POST['title'] : null, isset($_POST['course_number']) ? $_POST['course_number'] : null, isset($_POST['coordinator']) ? $_POST['coordinator'] : null, isset($_POST['instructor']) ? $_POST['instructor'] : null, isset($_POST['description']) ? $_POST['description'] : null, isset($_POST['textbook']) ? $_POST['textbook'] : null, isset($_POST['credit_hours']) ? $_POST['credit_hours'] : null); } else { // edit existing course echo update_course($_POST['id'], isset($_POST['title']) ? $_POST['title'] : null, isset($_POST['course_number']) ? $_POST['course_number'] : null, isset($_POST['coordinator']) ? $_POST['coordinator'] : null, isset($_POST['instructor']) ? $_POST['instructor'] : null, isset($_POST['description']) ? $_POST['description'] : null, isset($_POST['textbook']) ? $_POST['textbook'] : null, isset($_POST['credit_hours']) ? $_POST['credit_hours'] : null); } } else { page_fail(BAD_REQUEST); } }
/** * Update some courses information * @global object $DB * @param array|struct $params - need to be define as struct for XMLRPC * @subparam integer $params:course->id * @subparam string $params:course->idnumber * @subparam string $params:course->shortname * @subparam integer $params:course->category * @subparam string $params:course->fullname * @subparam string $params:course->summary * @subparam string $params:course->format * @subparam integer $params:course->startdate * @subparam integer $params:course->sortorder * @subparam integer $params:course->showgrades * @subparam string $params:course->modinfo * @subparam string $params:course->newsitems * @subparam string $params:course->guest * @subparam integer $params:course->metacourse * @subparam string $params:course->password * @subparam integer $params:course->enrolperiod * @subparam integer $params:course->defaultrole * @subparam integer $params:course->enrollable * @subparam integer $params:course->numsections * @subparam integer $params:course->expirynotify * @subparam integer $params:course->notifystudents * @subparam integer $params:course->expirythreshold * @subparam integer $params:course->marker * @subparam integer $params:course->maxbytes * @subparam integer $params:course->showreports * @subparam integer $params:course->visible * @subparam integer $params:course->hiddensections * @subparam integer $params:course->groupmode * @subparam integer $params:course->groupmodeforce * @subparam integer $params:course->defaultgroupingid * @subparam string $params:course->lang * @subparam string $params:course->theme * @subparam string $params:course->cost * @subparam string $params:course->currency * @subparam integer $params:course->timecreated * @subparam integer $params:course->timemodified * @subparam integer $params:course->requested * @subparam integer $params:course->restrictmodules * @subparam integer $params:course->enrolstartdate * @subparam integer $params:course->enrolenddate * @subparam string $params:course->enrol * @subparam integer $params:course->enablecompletion * @return boolean result true if success */ static function update_courses($params) { global $DB, $USER; if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) { $courses = array(); $result = true; foreach ($params as $courseparams) { $course = new stdClass(); if (array_key_exists('idnumber', $courseparams)) { $course->idnumber = clean_param($courseparams['idnumber'], PARAM_ALPHANUM); } if (array_key_exists('shortname', $courseparams)) { $course->shortname = clean_param($courseparams['shortname'], PARAM_ALPHANUMEXT); } if (array_key_exists('category', $courseparams)) { $course->category = clean_param($courseparams['category'], PARAM_INT); } if (array_key_exists('fullname', $courseparams)) { $course->fullname = clean_param($courseparams['fullname'], PARAM_TEXT); } if (array_key_exists('summary', $courseparams)) { $course->summary = clean_param($courseparams['summary'], PARAM_TEXT); } if (array_key_exists('format', $courseparams)) { $course->format = clean_param($courseparams['format'], PARAM_ALPHANUMEXT); } if (array_key_exists('startdate', $courseparams)) { $course->startdate = clean_param($courseparams['startdate'], PARAM_INT); } if (array_key_exists('sortorder', $courseparams)) { $course->sortorder = clean_param($courseparams['sortorder'], PARAM_INT); } if (array_key_exists('showgrades', $courseparams)) { $course->showgrades = clean_param($courseparams['showgrades'], PARAM_INT); } if (array_key_exists('modinfo', $courseparams)) { $course->modinfo = clean_param($courseparams['modinfo'], PARAM_ALPHANUMEXT); } if (array_key_exists('newsitems', $courseparams)) { $course->newsitems = clean_param($courseparams['newsitems'], PARAM_ALPHANUMEXT); } if (array_key_exists('guest', $courseparams)) { $course->guest = clean_param($courseparams['guest'], PARAM_ALPHANUMEXT); } if (array_key_exists('metacourse', $courseparams)) { $course->metacourse = clean_param($courseparams['metacourse'], PARAM_INT); } if (array_key_exists('password', $courseparams)) { $course->password = clean_param($courseparams['password'], PARAM_ALPHANUMEXT); } if (array_key_exists('enrolperiod', $courseparams)) { $course->enrolperiod = clean_param($courseparams['enrolperiod'], PARAM_INT); } if (array_key_exists('defaultrole', $courseparams)) { $course->defaultrole = clean_param($courseparams['defaultrole'], PARAM_INT); } if (array_key_exists('enrollable', $courseparams)) { $course->enrollable = clean_param($courseparams['enrollable'], PARAM_INT); } if (array_key_exists('numsections', $courseparams)) { $course->numsections = clean_param($courseparams['numsections'], PARAM_INT); } if (array_key_exists('expirynotify', $courseparams)) { $course->expirynotify = clean_param($courseparams['expirynotify'], PARAM_INT); } if (array_key_exists('notifystudents', $courseparams)) { $course->notifystudents = clean_param($courseparams['notifystudents'], PARAM_INT); } if (array_key_exists('expirythreshold', $courseparams)) { $course->expirythreshold = clean_param($courseparams['expirythreshold'], PARAM_INT); } if (array_key_exists('marker', $courseparams)) { $course->marker = clean_param($courseparams['marker'], PARAM_INT); } if (array_key_exists('maxbytes', $courseparams)) { $course->maxbytes = clean_param($courseparams['maxbytes'], PARAM_INT); } if (array_key_exists('showreports', $courseparams)) { $course->showreports = clean_param($courseparams['showreports'], PARAM_INT); } if (array_key_exists('visible', $courseparams)) { $course->visible = clean_param($courseparams['visible'], PARAM_INT); } if (array_key_exists('hiddensections', $courseparams)) { $course->hiddensections = clean_param($courseparams['hiddensections'], PARAM_INT); } if (array_key_exists('groupmode', $courseparams)) { $course->groupmode = clean_param($courseparams['groupmode'], PARAM_INT); } if (array_key_exists('groupmodeforce', $courseparams)) { $course->groupmodeforce = clean_param($courseparams['groupmodeforce'], PARAM_INT); } if (array_key_exists('defaultgroupingid', $courseparams)) { $course->defaultgroupingid = clean_param($courseparams['defaultgroupingid'], PARAM_INT); } if (array_key_exists('lang', $courseparams)) { $course->lang = clean_param($courseparams['lang'], PARAM_ALPHANUMEXT); } if (array_key_exists('theme', $courseparams)) { $course->theme = clean_param($courseparams['theme'], PARAM_ALPHANUMEXT); } if (array_key_exists('cost', $courseparams)) { $course->cost = clean_param($courseparams['cost'], PARAM_ALPHANUMEXT); } if (array_key_exists('currency', $courseparams)) { $course->currency = clean_param($courseparams['currency'], PARAM_ALPHANUMEXT); } if (array_key_exists('timecreated', $courseparams)) { $course->timecreated = clean_param($courseparams['timecreated'], PARAM_INT); } if (array_key_exists('timemodified', $courseparams)) { $course->timemodified = clean_param($courseparams['timemodified'], PARAM_INT); } if (array_key_exists('requested', $courseparams)) { $course->requested = clean_param($courseparams['requested'], PARAM_INT); } if (array_key_exists('restrictmodules', $courseparams)) { $course->restrictmodules = clean_param($courseparams['restrictmodules'], PARAM_INT); } if (array_key_exists('enrolstartdate', $courseparams)) { $course->enrolstartdate = clean_param($courseparams['enrolstartdate'], PARAM_INT); } if (array_key_exists('enrolenddate', $courseparams)) { $course->enrolenddate = clean_param($courseparams['enrolenddate'], PARAM_INT); } if (array_key_exists('enrol', $courseparams)) { $course->enrol = clean_param($courseparams['enrol'], PARAM_ALPHANUMEXT); } if (array_key_exists('enablecompletion', $courseparams)) { $course->enablecompletion = clean_param($courseparams['enablecompletion'], PARAM_INT); } if (array_key_exists('id', $courseparams)) { $course->id = clean_param($courseparams['id'], PARAM_INT); } if (!update_course($course)) { $result = false; } } return $result; } else { throw new moodle_exception('wscouldnotupdatecoursenopermission'); } }
public static function update_course($course) { global $CFG, $DB; // Valida os parametros. $params = self::validate_parameters(self::update_course_parameters(), array('course' => $course)); // Inlcui a biblioteca de cursos do moodle require_once "{$CFG->dirroot}/course/lib.php"; // Transforma o array em objeto. $course = (object) $course; // Inicia a transacao, qualquer erro que aconteca o rollback sera executado. $transaction = $DB->start_delegated_transaction(); // Busca o id do curso apartir do trm_id da turma. $courseid = self::get_course_by_trm_id($course->trm_id); // Se nao existir curso mapeado para a turma dispara uma excessao. if ($courseid) { $course->id = $courseid; } else { throw new Exception("Nenhum curso mapeado com a turma com trm_id: " . $course->trm_id); } // Cria o curso usando a biblioteca do proprio moodle. update_course($course); // Persiste as operacoes em caso de sucesso. $transaction->allow_commit(); // Prepara o array de retorno. $returndata['id'] = $courseid; $returndata['status'] = 'success'; $returndata['message'] = "Curso atualizado com sucesso"; return $returndata; }
$data->startdate = time(); $data->marker = 0; $data->maxbytes = 0; $data->legacyfiles = 0; $data->showreports = 0; $data->visible = 1; $data->visibleold = 1; $data->groupmode = 0; $data->groupmodeforce = 0; $data->defaultgroupingid = 0; $data->lang = ' '; $data->theme = ' '; $data->timecreated = time(); $data->timemodified = time(); $data->requested = 0; $data->enablecompletion = 1; $data->completionnotify = 0; $data->coursetype = 0; $b = create_course($data); update_course($b); //$b=$DB->insert_record('course', $data); $context = context_course::instance($b->id, MUST_EXIST); rebuild_course_cache($b->id); if ($b) { $count = $DB->get_record('course_categories', array('id' => $data->category)); $count->coursecount = ($count->coursecount + 1); $DB->update_record('course_categories', $count); } echo '<input type="hidden" value="' . $b->id . '" name="newonlinecourseid1">'; ?>
/** * Tests for groups_allgroups_course_menu() . */ public function test_groups_allgroups_course_menu() { global $SESSION; $this->resetAfterTest(); // Generate data. $course = $this->getDataGenerator()->create_course(); $record = new stdClass(); $record->courseid = $course->id; $group1 = $this->getDataGenerator()->create_group($record); $group2 = $this->getDataGenerator()->create_group($record); $user = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($user->id, $course->id); $this->setUser($user); $html = groups_allgroups_course_menu($course, 'someurl.php'); // Since user is not a part of this group and doesn't have accessallgroups permission, // the html should be empty. $this->assertEmpty($html); groups_add_member($group1->id, $user); // Now user can access one of the group. We can't assert an exact match here because of random ids generated by yui. So do // partial match to see if all groups are listed or not. $html = groups_allgroups_course_menu($course, 'someurl.php'); $this->assertContains(format_string($group1->name), $html); $this->assertNotContains(format_string($group2->name), $html); $this->setAdminUser(); // Now user can access everything. $html = groups_allgroups_course_menu($course, 'someurl.php'); $this->assertContains(format_string($group1->name), $html); $this->assertContains(format_string($group2->name), $html); // Make sure separate groups mode, doesn't change anything. $course->groupmode = SEPARATEGROUPS; update_course($course); $html = groups_allgroups_course_menu($course, 'someurl.php'); $this->assertContains(format_string($group1->name), $html); $this->assertContains(format_string($group2->name), $html); // Make sure Visible groups mode, doesn't change anything. $course->groupmode = VISIBLEGROUPS; update_course($course); $html = groups_allgroups_course_menu($course, 'someurl.php'); $this->assertContains(format_string($group1->name), $html); $this->assertContains(format_string($group2->name), $html); // Let us test activegroup changes now. $this->setUser($user); $SESSION->activegroup[$course->id][VISIBLEGROUPS][$course->defaultgroupingid] = 5; groups_allgroups_course_menu($course, 'someurl.php', false); // Do not update session. $this->assertSame(5, $SESSION->activegroup[$course->id][VISIBLEGROUPS][$course->defaultgroupingid]); groups_allgroups_course_menu($course, 'someurl.php', true, $group1->id); // Update session. $this->assertSame($group1->id, $SESSION->activegroup[$course->id][VISIBLEGROUPS][$course->defaultgroupingid]); // Try to update session with an invalid groupid. It should not accept the invalid id. groups_allgroups_course_menu($course, 'someurl.php', true, 256); $this->assertEquals($group1->id, $SESSION->activegroup[$course->id][VISIBLEGROUPS][$course->defaultgroupingid]); }
/** * Test test_update_course_frontpage_category. */ public function test_update_course_frontpage_category() { // Fetch front page course. $course = get_course(SITEID); // Test update information on front page course. $course->category = 99; $this->expectException('moodle_exception'); $this->expectExceptionMessage(get_string('invalidcourse', 'error')); update_course($course); }
/** * Tests for groups_user_groups_visible. */ public function test_groups_user_groups_visible() { global $CFG, $DB; $generator = $this->getDataGenerator(); $this->resetAfterTest(); $this->setAdminUser(); // Create a course category, course and groups. $cat = $generator->create_category(array('parent' => 0)); $course = $generator->create_course(array('category' => $cat->id)); $coursecontext = context_course::instance($course->id); $group1 = $generator->create_group(array('courseid' => $course->id, 'name' => 'Group 1')); $group2 = $generator->create_group(array('courseid' => $course->id, 'name' => 'Group 2')); $group3 = $generator->create_group(array('courseid' => $course->id, 'name' => 'Group 3')); $group4 = $generator->create_group(array('courseid' => $course->id, 'name' => 'Group 4')); // Create cm. $assign = $generator->create_module("assign", array('course' => $course->id)); $cm = get_coursemodule_from_instance("assign", $assign->id); // Create users. $user1 = $generator->create_user(); // Normal user. $user2 = $generator->create_user(); // Normal user. $user3 = $generator->create_user(); // Teacher, access all groups. $user4 = $generator->create_user(); // Normal user. // Enrol users into the course. $generator->enrol_user($user1->id, $course->id); $generator->enrol_user($user2->id, $course->id); $generator->enrol_user($user4->id, $course->id); // Assign groups. // User1 and User4 share groups. groups_add_member($group1, $user1); groups_add_member($group2, $user2); groups_add_member($group1, $user4); // Give capability at course level to the user to access all groups. $role = $DB->get_field("role", "id", array("shortname" => "manager")); $generator->enrol_user($user3->id, $course->id, $role); // Make sure the user has the capability. assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $role, $coursecontext->id); // Normal users in different groups. $this->setUser($user1); // No groups , not forced. $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertFalse($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with visible groups. // No groups, forced. $course->groupmode = NOGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); // Cm with visible groups. // Visible groups, forced. $course->groupmode = VISIBLEGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Visible groups, not forced. $course->groupmode = VISIBLEGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertFalse($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Separate groups, forced. $course->groupmode = SEPARATEGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user2->id); $this->assertFalse($result); $result = groups_user_groups_visible($course, $user3->id); $this->assertFalse($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertFalse($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertFalse($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user3->id, $cm); $this->assertTrue($result); $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertFalse($result); // Cm with visible groups. // Separate groups, not forced. $course->groupmode = SEPARATEGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user2->id); $this->assertFalse($result); $result = groups_user_groups_visible($course, $user3->id); $this->assertFalse($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertFalse($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Users sharing groups. // No groups , not forced. $course->groupmode = NOGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with visible groups. // No groups, forced. $course->groupmode = NOGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); // Cm with visible groups. // Visible groups, forced. $course->groupmode = VISIBLEGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Visible groups, not forced. $course->groupmode = VISIBLEGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Separate groups, forced. $course->groupmode = SEPARATEGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user3->id); $this->assertFalse($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user3->id, $cm); $this->assertTrue($result); $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Separate groups, not forced. $course->groupmode = SEPARATEGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user4->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user3->id); $this->assertFalse($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user4->id, $cm); $this->assertTrue($result); // Cm with visible groups. // For teacher with access all groups. // No groups , not forced. $course->groupmode = NOGROUPS; $course->groupmodeforce = false; update_course($course); $this->setUser($user3); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Requesting all groups. $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with visible groups. // No groups, forced. $course->groupmode = NOGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Requesting all groups. $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Cm with visible groups. // Visible groups, forced. $course->groupmode = VISIBLEGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Visible groups, not forced. $course->groupmode = VISIBLEGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Separate groups, forced. $course->groupmode = SEPARATEGROUPS; $course->groupmodeforce = true; update_course($course); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); // Requesting all groups. $result = groups_user_groups_visible($course, $user3->id); $this->assertTrue($result); // Requesting all groups. $result = groups_user_groups_visible($course, $user3->id); $this->assertTrue($result); $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user3->id, $cm); $this->assertTrue($result); $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with visible groups. // Separate groups, not forced. $course->groupmode = SEPARATEGROUPS; $course->groupmodeforce = false; update_course($course); $result = groups_user_groups_visible($course, $user1->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); $result = groups_user_groups_visible($course, $user2->id); $this->assertTrue($result); // Requesting all groups. $result = groups_user_groups_visible($course, $user3->id); $this->assertTrue($result); // Requesting all groups. $cm->groupmode = NOGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with no groups. $cm->groupmode = SEPARATEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with separate groups. $result = groups_user_groups_visible($course, $user2->id, $cm); $this->assertTrue($result); // Cm with separate groups. $cm->groupmode = VISIBLEGROUPS; $result = groups_user_groups_visible($course, $user1->id, $cm); $this->assertTrue($result); // Cm with visible groups. }
/** * Tests deleting discussion and permanent delete * Checks completion */ public function test_delete() { global $DB, $USER, $SITE, $CFG; require_once $CFG->dirroot . '/mod/forumng/mod_forumng_cron.php'; $CFG->enablecompletion = true; $this->resetAfterTest(true); $this->setAdminUser(); $course = $this->get_new_course(); $course->enablecompletion = 1; update_course($course); $forum = $this->get_new_forumng($course->id, array('removeafter' => 1, 'removeto' => 0, 'completion' => 2, 'completiondiscussions' => 1)); $completion = new completion_info($forum->get_course()); $discussion = $this->get_new_discussion($forum, array('userid' => $USER->id)); $root1 = $discussion->get_root_post(); // Get completion status. $complete = $completion->get_data($forum->get_course_module()); $this->assertEquals(COMPLETION_COMPLETE, $complete->completionstate); $discussion2 = $this->get_new_discussion($forum, array('userid' => $USER->id)); // Make post old. $root2 = $discussion2->get_root_post(); $dataobject = new stdClass(); $dataobject->id = $root2->get_id(); $dataobject->modified = $root2->get_modified() - 100; $DB->update_record('forumng_posts', $dataobject); // Check perm delete by manual call. $discussion->permanently_delete(false); $this->assertFalse($DB->get_record('forumng_discussions', array('id' => $discussion->get_id()))); $this->assertFalse($DB->get_record('forumng_posts', array('id' => $root1->get_id()))); // Check cron cleanup (Does permanently_delete() on discussion2). mod_forumng_cron::archive_old_discussions(); $this->assertFalse($DB->get_record('forumng_discussions', array('id' => $discussion2->get_id()))); $this->assertFalse($DB->get_record('forumng_posts', array('id' => $root2->get_id()))); $complete = $completion->get_data($forum->get_course_module()); $this->assertEquals(COMPLETION_INCOMPLETE, $complete->completionstate); if (mod_forumng::search_installed()) { $searchdoc = $root2->search_get_document(); $this->assertFalse($searchdoc->find()); $query = new local_ousearch_search('Message for discussion'); $query->set_coursemodule($forum->get_course_module(true)); $results = $query->query(); $this->assertEmpty($results->results); } }
//retorna NULL si no esta cancelat, si esta submit i si esta ben validat // fem una copia del curs $categoryid = $data->category; include 'backup.php'; $newcourse = get_course($courseid); // id del nou curs //afegim les dades del curs plantilla $data->id = $newcourse->id; $data->shortname = $data->fullname; $data->idnumber = $newcourse->id; $data->visible = '1'; $data->theme = $newcourse->lang; $data->lang = $USER->lang; //barregem $data = array_merge((array) $newcourse, (array) $data); update_course((object) $data, array()); //set the calendar event related to the course beggining $event = new stdClass(); $event->name = 'Debut du course ' . $newcourse->shortname; $event->description = ''; $event->courseid = $data->id; $event->groupid = 0; $event->userid = $USER->id; $event->modulename = ''; $event->instance = $newcourse->id; $event->eventtype = 'course'; $date = usergetdate(time()); //list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); $event->timestart = $data->startdate; $event->visible = 1; $event->timeduration = 0;
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Tool to make all courses in a category visible (or not). * * @package tool_cat * @copyright 2015 University of Kent * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('CLI_SCRIPT', true); require_once dirname(__FILE__) . '/../../../../config.php'; require_once $CFG->libdir . '/clilib.php'; require_once $CFG->dirroot . '/course/lib.php'; list($options, $unrecognized) = cli_get_params(array('category' => 0, 'visibility' => 1)); if (empty($options['category']) || empty($options['visibility'])) { print_error("You must specify a category with --category and visibility with --visibility."); exit(0); } \core\session\manager::set_user(get_admin()); $category = new \tool_cat\category($options['category']); $courses = $category->get_courses(); foreach ($courses as $course) { if ($course->visible != $options['visibility']) { mtrace("Updating {$course->id}"); $course->visible = $options['visibility']; update_course($course); } }
<div id="rightContent"> <h3>Edit Course Information</h3> <hr /> <div class="shortcutHome"> <?php if (isset($_POST['submit'])) { $cid = $_POST['cid']; $cname = $_POST['coursename']; $cd = $_POST['description']; $ch = $_POST['duration']; $ct = $_POST['type']; $cp = $_POST['cost']; include 'includes/functions.php'; update_course($cid, $cname, $cd, $ch, $ct, $cp); } ?> <?php $cid = isset($_GET['cid']) ? $_GET['cid'] : null; if ($cid) { include 'includes/connect.php'; $sqls = mysqli_query($dbhandle, "SELECT * from courses where id_course='{$cid}'"); $sqlr = mysqli_num_rows($sqls); $sqlf = mysqli_fetch_assoc($sqls); ?> </div> <table width="95%">
* @since Moodle 2.3 */ require_once __DIR__ . '/../config.php'; require_once $CFG->dirroot . '/course/lib.php'; $courseid = required_param('courseid', PARAM_INT); $increase = optional_param('increase', true, PARAM_BOOL); $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $courseformatoptions = course_get_format($course)->get_format_options(); $PAGE->set_url('/course/changenumsections.php', array('courseid' => $courseid)); // Authorisation checks. require_login($course); require_capability('moodle/course:update', context_course::instance($course->id)); require_sesskey(); if (isset($courseformatoptions['numsections'])) { if ($increase) { // Add an additional section. $courseformatoptions['numsections']++; } else { // Remove a section. $courseformatoptions['numsections']--; } // Don't go less than 0, intentionally redirect silently (for the case of // double clicks). if ($courseformatoptions['numsections'] >= 0) { update_course((object) array('id' => $course->id, 'numsections' => $courseformatoptions['numsections'])); } } $url = course_get_url($course); $url->set_anchor('changenumsections'); // Redirect to where we were.. redirect($url);
/** * Process the group tag. This defines a Moodle course. * * @param string $tagcontents The raw contents of the XML element */ protected function process_group_tag($tagcontents) { global $DB, $CFG; // Get configs. $truncatecoursecodes = $this->get_config('truncatecoursecodes'); $createnewcourses = $this->get_config('createnewcourses'); $updatecourses = $this->get_config('updatecourses'); if ($createnewcourses) { require_once "{$CFG->dirroot}/course/lib.php"; } // Process tag contents. $group = new stdClass(); if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) { $group->coursecode = trim($matches[1]); } $matches = array(); if (preg_match('{<description>.*?<long>(.*?)</long>.*?</description>}is', $tagcontents, $matches)) { $group->long = trim($matches[1]); } $matches = array(); if (preg_match('{<description>.*?<short>(.*?)</short>.*?</description>}is', $tagcontents, $matches)) { $group->short = trim($matches[1]); } $matches = array(); if (preg_match('{<description>.*?<full>(.*?)</full>.*?</description>}is', $tagcontents, $matches)) { $group->full = trim($matches[1]); } if (preg_match('{<org>(.*?)</org>}is', $tagcontents, $matchesorg)) { if (preg_match_all('{<orgunit>(.*?)</orgunit>}is', $matchesorg[1], $matchesorgunit)) { $group->categories = array_map('trim', $matchesorgunit[1]); } } $recstatus = $this->get_recstatus($tagcontents, 'group'); if (empty($group->coursecode)) { $this->log_line('Error: Unable to find course code in \'group\' element.'); } else { // First, truncate the course code if desired. if (intval($truncatecoursecodes) > 0) { $group->coursecode = $truncatecoursecodes > 0 ? substr($group->coursecode, 0, intval($truncatecoursecodes)) : $group->coursecode; } // For compatibility with the (currently inactive) course aliasing, we need this to be an array. $group->coursecode = array($group->coursecode); // Third, check if the course(s) exist. foreach ($group->coursecode as $coursecode) { $coursecode = trim($coursecode); $dbcourse = $DB->get_record('course', array('idnumber' => $coursecode)); if (!$dbcourse) { if (!$createnewcourses) { $this->log_line("Course {$coursecode} not found in Moodle's course idnumbers."); } else { // Create the (hidden) course(s) if not found. $courseconfig = get_config('moodlecourse'); // Load Moodle Course shell defaults. // New course. $course = new stdClass(); foreach ($this->coursemappings as $courseattr => $imsname) { if ($imsname == 'ignore') { continue; } // Check if the IMS file contains the mapped tag, otherwise fallback on coursecode. if ($imsname == 'coursecode') { $course->{$courseattr} = $coursecode; } else { if (!empty($group->{$imsname})) { $course->{$courseattr} = $group->{$imsname}; } else { $this->log_line('No ' . $imsname . ' description tag found for ' . $coursecode . ' coursecode, using ' . $coursecode . ' instead'); $course->{$courseattr} = $coursecode; } } } $course->idnumber = $coursecode; $course->format = $courseconfig->format; $course->visible = $courseconfig->visible; $course->newsitems = $courseconfig->newsitems; $course->showgrades = $courseconfig->showgrades; $course->showreports = $courseconfig->showreports; $course->maxbytes = $courseconfig->maxbytes; $course->groupmode = $courseconfig->groupmode; $course->groupmodeforce = $courseconfig->groupmodeforce; $course->enablecompletion = $courseconfig->enablecompletion; // Insert default names for teachers/students, from the current language. // Handle course categorisation (taken from the group.org.orgunit or group.org.id fields if present). $course->category = $this->get_category_from_group($group->categories); $course->startdate = time(); // Choose a sort order that puts us at the start of the list! $course->sortorder = 0; $course = create_course($course); $this->log_line("Created course {$coursecode} in Moodle (Moodle ID is {$course->id})"); } } else { if ($recstatus == self::IMSENTERPRISE_UPDATE && $dbcourse) { if ($updatecourses) { // Update course. Allowed fields to be updated are: // Short Name, and Full Name. $hasupdates = false; if (!empty($group->short)) { if ($group->short != $dbcourse->shortname) { $dbcourse->shortname = $group->short; $hasupdates = true; } } if (!empty($group->full)) { if ($group->full != $dbcourse->fullname) { $dbcourse->fullname = $group->full; $hasupdates = true; } } if ($hasupdates) { update_course($dbcourse); $courseid = $dbcourse->id; $this->log_line("Updated course {$coursecode} in Moodle (Moodle ID is {$courseid})"); } } else { // Update courses option is not enabled. Ignore. $this->log_line("Ignoring update to course {$coursecode}"); } } else { if ($recstatus == self::IMSENTERPRISE_DELETE && $dbcourse) { // If course does exist, but recstatus==3 (delete), then set the course as hidden. $courseid = $dbcourse->id; $show = false; course_change_visibility($courseid, $show); $this->log_line("Updated (set to hidden) course {$coursecode} in Moodle (Moodle ID is {$courseid})"); } } } } } }
/** * Will update a moodle course with new values from LDAP * A field will be updated only if it is marked to be updated * on sync in plugin settings * * @param object $course * @param array $externalcourse * @param progress_trace $trace * @return bool */ protected function update_course($course, $externalcourse, progress_trace $trace) { global $CFG, $DB; $coursefields = array('shortname', 'fullname', 'summary'); static $shouldupdate; // Initialize $shouldupdate variable. Set to true if one or more fields are marked for update. if (!isset($shouldupdate)) { $shouldupdate = false; foreach ($coursefields as $field) { $shouldupdate = $shouldupdate || $this->get_config('course_' . $field . '_updateonsync'); } } // If we should not update return immediately. if (!$shouldupdate) { return false; } require_once "{$CFG->dirroot}/course/lib.php"; $courseupdated = false; $updatedcourse = new stdClass(); $updatedcourse->id = $course->id; // Update course fields if necessary. foreach ($coursefields as $field) { // If field is marked to be updated on sync && field data was changed update it. if ($this->get_config('course_' . $field . '_updateonsync') && isset($externalcourse[$this->get_config('course_' . $field)][0]) && $course->{$field} != $externalcourse[$this->get_config('course_' . $field)][0]) { $updatedcourse->{$field} = $externalcourse[$this->get_config('course_' . $field)][0]; $courseupdated = true; } } if (!$courseupdated) { $trace->output(get_string('courseupdateskipped', 'enrol_ldap', $course)); return false; } // Do not allow empty fullname or shortname. if (isset($updatedcourse->fullname) && empty($updatedcourse->fullname) || isset($updatedcourse->shortname) && empty($updatedcourse->shortname)) { // We are in trouble! $trace->output(get_string('cannotupdatecourse', 'enrol_ldap', $course)); return false; } // Check if the shortname already exists if it does - skip course updating. if (isset($updatedcourse->shortname) && $DB->record_exists('course', array('shortname' => $updatedcourse->shortname))) { $trace->output(get_string('cannotupdatecourse_duplicateshortname', 'enrol_ldap', $course)); return false; } // Finally - update course in DB. update_course($updatedcourse); $trace->output(get_string('courseupdated', 'enrol_ldap', $course)); return true; }
/** * Pre-uninstall hook. * * This is intended for disabling of plugin, some DB table purging, etc. * * NOTE: to be called from uninstall_plugin() only. * @private */ public function uninstall_cleanup() { global $DB; if (($defaultformat = get_config('moodlecourse', 'format')) && $defaultformat !== $this->name) { $courses = $DB->get_records('course', array('format' => $this->name), 'id'); $data = (object) array('id' => null, 'format' => $defaultformat); foreach ($courses as $record) { $data->id = $record->id; update_course($data); } } $DB->delete_records('course_format_options', array('format' => $this->name)); parent::uninstall_cleanup(); }
/** * Update courses * * @param array $courses * @since Moodle 2.5 */ public static function update_courses($courses) { global $CFG, $DB; require_once($CFG->dirroot . "/course/lib.php"); $warnings = array(); $params = self::validate_parameters(self::update_courses_parameters(), array('courses' => $courses)); $availablethemes = core_component::get_plugin_list('theme'); $availablelangs = get_string_manager()->get_list_of_translations(); foreach ($params['courses'] as $course) { // Catch any exception while updating course and return as warning to user. try { // Ensure the current user is allowed to run this function. $context = context_course::instance($course['id'], MUST_EXIST); self::validate_context($context); $oldcourse = course_get_format($course['id'])->get_course(); require_capability('moodle/course:update', $context); // Check if user can change category. if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) { require_capability('moodle/course:changecategory', $context); $course['category'] = $course['categoryid']; } // Check if the user can change fullname. if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) { require_capability('moodle/course:changefullname', $context); } // Check if the user can change shortname. if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) { require_capability('moodle/course:changeshortname', $context); } // Check if the user can change the idnumber. if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) { require_capability('moodle/course:changeidnumber', $context); } // Check if user can change summary. if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) { require_capability('moodle/course:changesummary', $context); } // Summary format. if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) { require_capability('moodle/course:changesummary', $context); $course['summaryformat'] = external_validate_format($course['summaryformat']); } // Check if user can change visibility. if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) { require_capability('moodle/course:visibility', $context); } // Make sure lang is valid. if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) { throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang'); } // Make sure theme is valid. if (array_key_exists('forcetheme', $course)) { if (!empty($CFG->allowcoursethemes)) { if (empty($availablethemes[$course['forcetheme']])) { throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme'); } else { $course['theme'] = $course['forcetheme']; } } } // Make sure completion is enabled before setting it. if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) { $course['enabledcompletion'] = 0; } // Make sure maxbytes are less then CFG->maxbytes. if (array_key_exists('maxbytes', $course)) { $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']); } if (!empty($course['courseformatoptions'])) { foreach ($course['courseformatoptions'] as $option) { if (isset($option['name']) && isset($option['value'])) { $course[$option['name']] = $option['value']; } } } // Update course if user has all required capabilities. update_course((object) $course); } catch (Exception $e) { $warning = array(); $warning['item'] = 'course'; $warning['itemid'] = $course['id']; if ($e instanceof moodle_exception) { $warning['warningcode'] = $e->errorcode; } else { $warning['warningcode'] = $e->getCode(); } $warning['message'] = $e->getMessage(); $warnings[] = $warning; } } $result = array(); $result['warnings'] = $warnings; return $result; }
/** * Update a course * @todo: consider factoring this some more once other actions exist * * @param object $record One record of import data * @param string $filename The import file name, used for logging * @return boolean true on success, otherwise false */ function course_update($record, $filename) { global $CFG, $DB; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/lib/enrollib.php'; //remove invalid fields $record = $this->remove_invalid_course_fields($record); //field length checking $lengthcheck = $this->check_course_field_lengths($record, $filename); if (!$lengthcheck) { return false; } //data checking if (!$this->validate_core_course_data('update', $record, $filename)) { return false; } //validate and set up the category if (isset($record->category)) { $categoryid = $this->get_category_id($record, $filename); if ($categoryid === false) { return false; } $record->category = $categoryid; } $record->id = $DB->get_field('course', 'id', array('shortname' => $record->shortname)); if (empty($record->id)) { if (isset($record->idnumber) && $record->idnumber !== '' && $DB->count_records('course', array('idnumber' => $record->idnumber)) == 1) { $record->id = $DB->get_field('course', 'id', array('idnumber' => $record->idnumber)); } else { $identifier = $this->mappings['shortname']; $this->fslogger->log_failure("{$identifier} value of \"{$record->shortname}\" does not refer to a valid course.", 0, $filename, $this->linenumber, $record, "course"); return false; } } else { if (isset($record->idnumber) && $record->idnumber !== '' && $DB->record_exists('course', array('idnumber' => $record->idnumber))) { $checkrecordid = $DB->get_field('course', 'id', array('idnumber' => $record->idnumber)); if ($checkrecordid != $record->id) { $identifier = $this->mappings['idnumber']; $this->fslogger->log_failure("{$identifier} value of \"{$record->idnumber}\" already exists " . "in an existing course.", 0, $filename, $this->linenumber, $record, 'course'); return false; } } } update_course($record); //special work for "guest" settings if (isset($record->guest) && empty($record->guest)) { //todo: add more error checking if ($enrol = $DB->get_record('enrol', array('courseid' => $record->id, 'enrol' => 'guest'))) { //disable the plugin for the current course $enrol->status = ENROL_INSTANCE_DISABLED; $DB->update_record('enrol', $enrol); } else { //should never get here due to validation //$this->process_error("[$filename line $this->linenumber] \"guest\" enrolments cannot be enabled because the guest enrolment plugin has been removed from course {$record->shortname}."); return false; } } if (!empty($record->guest)) { //todo: add more error checking if ($enrol = $DB->get_record('enrol', array('courseid' => $record->id, 'enrol' => 'guest'))) { //enable the plugin for the current course $enrol->status = ENROL_INSTANCE_ENABLED; if (isset($record->password)) { //password specified, so set it $enrol->password = $record->password; } $DB->update_record('enrol', $enrol); } else { //should never get here due to validation //$this->process_error("[$filename line $this->linenumber] guest enrolment plugin cannot be assigned a password because the guest enrolment plugin has been removed from course {$record->shortname}."); return false; } } //log success $this->fslogger->log_success("Course with shortname \"{$record->shortname}\" successfully updated.", 0, $filename, $this->linenumber); if (!$this->fslogger->get_logfile_status()) { return false; } return true; }