/** * 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); } } }
/** * Create a course and either return a $course object * * Please note this functions does not verify any access control, * the calling code is responsible for all validation (usually it is the form definition). * * @param array $editoroptions course description editor options * @param object $data - all the data needed for an entry in the 'course' table * @return object new course instance */ function create_course($data, $editoroptions = NULL) { global $DB; //check the categoryid - must be given for all new courses $category = $DB->get_record('course_categories', array('id' => $data->category), '*', MUST_EXIST); // Check if the shortname already exists. if (!empty($data->shortname)) { if ($DB->record_exists('course', array('shortname' => $data->shortname))) { throw new moodle_exception('shortnametaken', '', '', $data->shortname); } } // Check if the idnumber already exists. if (!empty($data->idnumber)) { if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) { throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber); } } $data->timecreated = time(); $data->timemodified = $data->timecreated; // place at beginning of any category $data->sortorder = 0; if ($editoroptions) { // summary text is updated later, we need context to store the files first $data->summary = ''; $data->summary_format = FORMAT_HTML; } if (!isset($data->visible)) { // data not from form, add missing visibility info $data->visible = $category->visible; } $data->visibleold = $data->visible; $newcourseid = $DB->insert_record('course', $data); $context = context_course::instance($newcourseid, MUST_EXIST); if ($editoroptions) { // Save the files used in the summary editor and store $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0); $DB->set_field('course', 'summary', $data->summary, array('id' => $newcourseid)); $DB->set_field('course', 'summaryformat', $data->summary_format, array('id' => $newcourseid)); } if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) { // Save the course overviewfiles $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0); } // update course format options course_get_format($newcourseid)->update_course_format_options($data); $course = course_get_format($newcourseid)->get_course(); // Setup the blocks blocks_add_default_course_blocks($course); // Create a default section. course_create_sections_if_missing($course, 0); fix_course_sortorder(); // purge appropriate caches in case fix_course_sortorder() did not change anything cache_helper::purge_by_event('changesincourse'); // new context created - better mark it as dirty $context->mark_dirty(); // Save any custom role names. save_local_role_names($course->id, (array) $data); // set up enrolments enrol_course_updated(true, $course, $data); // Trigger a course created event. $event = \core\event\course_created::create(array('objectid' => $course->id, 'context' => context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname))); $event->trigger(); return $course; }
/** * Create a course and either return a $course object * * Please note this functions does not verify any access control, * the calling code is responsible for all validation (usually it is the form definition). * * @param array $editoroptions course description editor options * @param object $data - all the data needed for an entry in the 'course' table * @return object new course instance */ function create_course($data, $editoroptions = NULL) { global $CFG, $DB; //check the categoryid - must be given for all new courses $category = $DB->get_record('course_categories', array('id' => $data->category), '*', MUST_EXIST); //check if the shortname already exist if (!empty($data->shortname)) { if ($DB->record_exists('course', array('shortname' => $data->shortname))) { throw new moodle_exception('shortnametaken'); } } //check if the id number already exist if (!empty($data->idnumber)) { if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) { throw new moodle_exception('idnumbertaken'); } } $data->timecreated = time(); $data->timemodified = $data->timecreated; // place at beginning of any category $data->sortorder = 0; if ($editoroptions) { // summary text is updated later, we need context to store the files first $data->summary = ''; $data->summary_format = FORMAT_HTML; } if (!isset($data->visible)) { // data not from form, add missing visibility info $data->visible = $category->visible; } $data->visibleold = $data->visible; $newcourseid = $DB->insert_record('course', $data); $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST); if ($editoroptions) { // Save the files used in the summary editor and store $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0); $DB->set_field('course', 'summary', $data->summary, array('id' => $newcourseid)); $DB->set_field('course', 'summaryformat', $data->summary_format, array('id' => $newcourseid)); } $course = $DB->get_record('course', array('id' => $newcourseid)); // Setup the blocks blocks_add_default_course_blocks($course); $section = new stdClass(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->summaryformat = FORMAT_HTML; $DB->insert_record('course_sections', $section); fix_course_sortorder(); // new context created - better mark it as dirty mark_context_dirty($context->path); // Save any custom role names. save_local_role_names($course->id, (array) $data); // set up enrolments enrol_course_updated(true, $course, $data); add_to_log(SITEID, 'course', 'new', 'view.php?id=' . $course->id, $data->fullname . ' (ID ' . $course->id . ')'); // Trigger events events_trigger('course_created', $course); return $course; }
/** * Process the group tag. This defines a Moodle course. * @param string $tagconents The raw contents of the XML element */ function process_group_tag($tagcontents) { global $DB; // Get configs $truncatecoursecodes = $this->get_config('truncatecoursecodes'); $createnewcourses = $this->get_config('createnewcourses'); $createnewcategories = $this->get_config('createnewcategories'); // Process tag contents $group = new stdClass(); if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) { $group->coursecode = trim($matches[1]); } if (preg_match('{<description>.*?<long>(.*?)</long>.*?</description>}is', $tagcontents, $matches)) { $group->description = trim($matches[1]); } if (preg_match('{<description>.*?<short>(.*?)</short>.*?</description>}is', $tagcontents, $matches)) { $group->shortName = trim($matches[1]); } if (preg_match('{<description>.*?<full>(.*?)</full>.*?</description>}is', $tagcontents, $matches)) { $group->fulldescription = trim($matches[1]); } if (preg_match('{<org>.*?<orgunit>(.*?)</orgunit>.*?</org>}is', $tagcontents, $matches)) { $group->category = trim($matches[1]); } $recstatus = $this->get_recstatus($tagcontents, 'group'); //echo "<p>get_recstatus for this group returned $recstatus</p>"; if (!(strlen($group->coursecode) > 0)) { $this->log_line('Error at line ' . $line . ': 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; } /* -----------Course aliasing is DEACTIVATED until a more general method is in place--------------- // Second, look in the course alias table to see if the code should be translated to something else if($aliases = $DB->get_field('enrol_coursealias', 'toids', array('fromid'=>$group->coursecode))){ $this->log_line("Found alias of course code: Translated $group->coursecode to $aliases"); // Alias is allowed to be a comma-separated list, so let's split it $group->coursecode = explode(',', $aliases); } */ // 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); if (!$DB->get_field('course', 'id', array('idnumber' => $coursecode))) { if (!$createnewcourses) { $this->log_line("Course {$coursecode} not found in Moodle's course idnumbers."); } else { // Set shortname to description or description to shortname if one is set but not the other. $nodescription = !isset($group->description); $noshortname = !isset($group->shortName); if ($nodescription && $noshortname) { // If neither short nor long description are set let if fail $this->log_line("Neither long nor short name are set for {$coursecode}"); } else { if ($nodescription) { // If short and ID exist, then give the long short's value, then give short the ID's value $group->description = $group->shortName; $group->shortName = $coursecode; } else { if ($noshortname) { // If long and ID exist, then map long to long, then give short the ID's value. $group->shortName = $coursecode; } } } // Create the (hidden) course(s) if not found $courseconfig = get_config('moodlecourse'); // Load Moodle Course shell defaults $course = new stdClass(); $course->fullname = $group->description; $course->shortname = $group->shortName; if (!empty($group->fulldescription)) { $course->summary = format_text($group->fulldescription, FORMAT_HTML); } $course->idnumber = $coursecode; $course->format = $courseconfig->format; $course->visible = $courseconfig->visible; $course->numsections = $courseconfig->numsections; $course->hiddensections = $courseconfig->hiddensections; $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; $course->completionstartonenrol = $courseconfig->completionstartonenrol; // Insert default names for teachers/students, from the current language // Handle course categorisation (taken from the group.org.orgunit field if present) if (strlen($group->category) > 0) { // If the category is defined and exists in Moodle, we want to store it in that one if ($catid = $DB->get_field('course_categories', 'id', array('name' => $group->category))) { $course->category = $catid; } else { if ($createnewcategories) { // Else if we're allowed to create new categories, let's create this one $newcat = new stdClass(); $newcat->name = $group->category; $newcat->visible = 0; $catid = $DB->insert_record('course_categories', $newcat); $course->category = $catid; $this->log_line("Created new (hidden) category, #{$catid}: {$newcat->name}"); } else { // If not found and not allowed to create, stick with default $this->log_line('Category ' . $group->category . ' not found in Moodle database, so using default category instead.'); $course->category = 1; } } } else { $course->category = 1; } $course->timecreated = time(); $course->startdate = time(); // Choose a sort order that puts us at the start of the list! $course->sortorder = 0; $courseid = $DB->insert_record('course', $course); // Setup default enrolment plugins $course->id = $courseid; enrol_course_updated(true, $course, null); // 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); add_to_log(SITEID, "course", "new", "view.php?id={$course->id}", "{$course->fullname} (ID {$course->id})"); $this->log_line("Created course {$coursecode} in Moodle (Moodle ID is {$course->id})"); } } else { if ($recstatus == 3 && ($courseid = $DB->get_field('course', 'id', array('idnumber' => $coursecode)))) { // If course does exist, but recstatus==3 (delete), then set the course as hidden $DB->set_field('course', 'visible', '0', array('id' => $courseid)); } } } // End of foreach(coursecode) } }
/** * This function finds all available blocks and install them * into blocks table or do all the upgrade process if newer. * * @global object * @global object */ function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) { global $CFG, $DB; require_once($CFG->dirroot.'/blocks/moodleblock.class.php'); $blocktitles = array(); // we do not want duplicate titles //Is this a first install $first_install = null; $blocks = core_component::get_plugin_list('block'); foreach ($blocks as $blockname=>$fullblock) { if (is_null($first_install)) { $first_install = ($DB->count_records('block_instances') == 0); } if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it continue; } $component = clean_param('block_'.$blockname, PARAM_COMPONENT); // check block dir is valid name if (empty($component)) { throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.'); } if (!is_readable($fullblock.'/version.php')) { throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.'); } $plugin = new stdClass(); $plugin->version = null; $plugin->cron = 0; $module = $plugin; // Prevent some notices when module placed in wrong directory. include($fullblock.'/version.php'); unset($module); $block = clone($plugin); unset($block->version); unset($block->component); unset($block->dependencies); unset($block->release); // if plugin tells us it's full name we may check the location if (isset($plugin->component)) { if ($plugin->component !== $component) { throw new plugin_misplaced_exception($plugin->component, null, $fullblock); } } if (empty($plugin->version)) { throw new plugin_defective_exception($component, 'Missing block version.'); } if (!empty($plugin->requires)) { if ($plugin->requires > $CFG->version) { throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires); } else if ($plugin->requires < 2010000000) { throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.'); } } if (!is_readable($fullblock.'/block_'.$blockname.'.php')) { throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.'); } include_once($fullblock.'/block_'.$blockname.'.php'); $classname = 'block_'.$blockname; if (!class_exists($classname)) { throw new plugin_defective_exception($component, 'Can not load main class.'); } $blockobj = new $classname; // This is what we'll be testing $blocktitle = $blockobj->get_title(); // OK, it's as we all hoped. For further tests, the object will do them itself. if (!$blockobj->_self_test()) { throw new plugin_defective_exception($component, 'Self test failed.'); } $block->name = $blockname; // The name MUST match the directory $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching! if (file_exists($fullblock.'/db/install.php')) { if (get_config('block_'.$blockname, 'installrunning')) { require_once($fullblock.'/db/install.php'); $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery'; if (function_exists($recover_install_function)) { $startcallback($component, true, $verbose); $recover_install_function(); unset_config('installrunning', 'block_'.$blockname); // Install various components update_capabilities($component); log_update_descriptions($component); external_update_descriptions($component); events_update_definition($component); \core\task\manager::reset_scheduled_tasks_for_component($component); message_update_providers($component); \core\message\inbound\manager::update_handlers_for_component($component); upgrade_plugin_mnet_functions($component); $endcallback($component, true, $verbose); } } } if (empty($installedversion)) { // block not installed yet, so install it $conflictblock = array_search($blocktitle, $blocktitles); if ($conflictblock !== false) { // Duplicate block titles are not allowed, they confuse people // AND PHP's associative arrays ;) throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock))); } $startcallback($component, true, $verbose); if (file_exists($fullblock.'/db/install.xml')) { $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml'); } $block->id = $DB->insert_record('block', $block); upgrade_block_savepoint(true, $plugin->version, $block->name, false); if (file_exists($fullblock.'/db/install.php')) { require_once($fullblock.'/db/install.php'); // Set installation running flag, we need to recover after exception or error set_config('installrunning', 1, 'block_'.$blockname); $post_install_function = 'xmldb_block_'.$blockname.'_install'; $post_install_function(); unset_config('installrunning', 'block_'.$blockname); } $blocktitles[$block->name] = $blocktitle; // Install various components update_capabilities($component); log_update_descriptions($component); external_update_descriptions($component); events_update_definition($component); \core\task\manager::reset_scheduled_tasks_for_component($component); message_update_providers($component); \core\message\inbound\manager::update_handlers_for_component($component); upgrade_plugin_mnet_functions($component); $endcallback($component, true, $verbose); } else if ($installedversion < $plugin->version) { $startcallback($component, false, $verbose); if (is_readable($fullblock.'/db/upgrade.php')) { require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade'; $result = $newupgrade_function($installedversion, $block); } else { $result = true; } $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching! $currblock = $DB->get_record('block', array('name'=>$block->name)); if ($installedversion < $plugin->version) { // store version if not already there upgrade_block_savepoint($result, $plugin->version, $block->name, false); } if ($currblock->cron != $block->cron) { // update cron flag if needed $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id)); } // Upgrade various components update_capabilities($component); log_update_descriptions($component); external_update_descriptions($component); events_update_definition($component); \core\task\manager::reset_scheduled_tasks_for_component($component); message_update_providers($component); \core\message\inbound\manager::update_handlers_for_component($component); upgrade_plugin_mnet_functions($component); $endcallback($component, false, $verbose); } else if ($installedversion > $plugin->version) { throw new downgrade_exception($component, $installedversion, $plugin->version); } } // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks if ($first_install) { //Iterate over each course - there should be only site course here now if ($courses = $DB->get_records('course')) { foreach ($courses as $course) { blocks_add_default_course_blocks($course); } } blocks_add_default_system_blocks(); } }
/// Build up a course record based on the request. $course->category = $category->id; $course->sortorder = $category->sortorder; // place as the first in category $course->requested = 1; unset($course->reason); unset($course->id); $teacherid = $course->requester; unset($course->requester); if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { $course->restrictmodules = 1; } /// Insert the record. if ($courseid = $DB->insert_record('course', $course)) { $course = $DB->get_record('course', array('id' => $courseid)); blocks_add_default_course_blocks($course); $context = get_context_instance(CONTEXT_COURSE, $courseid); role_assign($CFG->creatornewroleid, $teacherid, 0, $context->id); // assing teacher role if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { // if we're all or requested we're ok. $allowedmods = explode(',', $CFG->defaultallowedmodules); update_restricted_mods($course, $allowedmods); } $DB->delete_records('course_request', array('id' => $approve)); $success = 1; fix_course_sortorder(); } if (!empty($success)) { $user = $DB->get_record('user', array('id' => $teacherid)); $a->name = $course->fullname;
/** * This function finds all available blocks and install them * into blocks table or do all the upgrade process if newer. * * @global object * @global object */ function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) { global $CFG, $DB; require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; $blocktitles = array(); // we do not want duplicate titles //Is this a first install $first_install = null; $blocks = get_plugin_list('block'); foreach ($blocks as $blockname => $fullblock) { if (is_null($first_install)) { $first_install = $DB->count_records('block') == 0; } if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it continue; } $component = 'block_' . $blockname; if (!is_readable($fullblock . '/block_' . $blockname . '.php')) { throw new plugin_defective_exception('block/' . $blockname, 'Missing main block class file.'); } require_once $fullblock . '/block_' . $blockname . '.php'; $classname = 'block_' . $blockname; if (!class_exists($classname)) { throw new plugin_defective_exception($component, 'Can not load main class.'); } $blockobj = new $classname(); // This is what we 'll be testing $blocktitle = $blockobj->get_title(); // OK, it's as we all hoped. For further tests, the object will do them itself. if (!$blockobj->_self_test()) { throw new plugin_defective_exception($component, 'Self test failed.'); } $block = new object(); // This may be used to update the db below $block->name = $blockname; // The name MUST match the directory $block->version = $blockobj->get_version(); $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0; $block->multiple = $blockobj->instance_allow_multiple() ? 1 : 0; if (empty($block->version)) { throw new plugin_defective_exception($component, 'Missing block version.'); } $currblock = $DB->get_record('block', array('name' => $block->name)); if (file_exists($fullblock . '/db/install.php')) { if (get_config('block_' . $blockname, 'installrunning')) { require_once $fullblock . '/db/install.php'; $recover_install_function = 'xmldb_block_' . $blockname . '_install_recovery'; if (function_exists($recover_install_function)) { $startcallback($component, true, $verbose); $recover_install_function(); unset_config('installrunning', 'block_' . $blockname); // Install various components update_capabilities($component); events_update_definition($component); message_update_providers($component); $endcallback($component, true, $verbose); } } } if (empty($currblock->version)) { // block not installed yet, so install it // If it allows multiples, start with it enabled $conflictblock = array_search($blocktitle, $blocktitles); if ($conflictblock !== false) { // Duplicate block titles are not allowed, they confuse people // AND PHP's associative arrays ;) throw new plugin_defective_exception($component, get_string('blocknameconflict', '', (object) array('name' => $block->name, 'conflict' => $conflictblock))); } $startcallback($component, true, $verbose); if (file_exists($fullblock . '/db/install.xml')) { $DB->get_manager()->install_from_xmldb_file($fullblock . '/db/install.xml'); } $block->id = $DB->insert_record('block', $block); if (file_exists($fullblock . '/db/install.php')) { require_once $fullblock . '/db/install.php'; // Set installation running flag, we need to recover after exception or error set_config('installrunning', 1, 'block_' . $blockname); $post_install_function = 'xmldb_block_' . $blockname . '_install'; $post_install_function(); unset_config('installrunning', 'block_' . $blockname); } $blocktitles[$block->name] = $blocktitle; // Install various components update_capabilities($component); events_update_definition($component); message_update_providers($component); $endcallback($component, true, $verbose); } else { if ($currblock->version < $block->version) { $startcallback($component, false, $verbose); if (is_readable($fullblock . '/db/upgrade.php')) { require_once $fullblock . '/db/upgrade.php'; // defines new upgrading function $newupgrade_function = 'xmldb_block_' . $blockname . '_upgrade'; $result = $newupgrade_function($currblock->version, $block); } else { $result = true; } $currblock = $DB->get_record('block', array('name' => $block->name)); if ($currblock->version < $block->version) { // store version if not already there upgrade_block_savepoint($result, $block->version, $block->name, false); } if ($currblock->cron != $block->cron) { // update cron flag if needed $currblock->cron = $block->cron; $DB->update_record('block', $currblock); } // Upgrade various componebts update_capabilities($component); events_update_definition($component); message_update_providers($component); $endcallback($component, false, $verbose); } else { if ($currblock->version > $block->version) { throw new downgrade_exception($component, $currblock->version, $block->version); } } } } // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks if ($first_install) { //Iterate over each course - there should be only site course here now if ($courses = $DB->get_records('course')) { foreach ($courses as $course) { blocks_add_default_course_blocks($course); } } blocks_add_default_system_blocks(); } }
function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) { global $CFG, $DB; $status = true; blocks_delete_all_on_page(PAGE_COURSE_VIEW, $restore->course_id); if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5 if (empty($blockinfo)) { // Looks like it's from Moodle < 1.3. Let's give the course default blocks... blocks_add_default_course_blocks($DB->get_record('course', array('id' => $restore->course_id))); } else { // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup $blockrecords = $DB->get_records('block', null, '', 'name, id'); $temp_blocks_l = array(); $temp_blocks_r = array(); @(list($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo)); $temp_blocks = array(BLOCK_POS_LEFT => explode(',', $temp_blocks_l), BLOCK_POS_RIGHT => explode(',', $temp_blocks_r)); foreach ($temp_blocks as $blockposition => $blocks) { $blockweight = 0; foreach ($blocks as $blockname) { if (!isset($blockrecords[$blockname])) { // We don't know anything about this block! continue; } $blockinstance = new stdClass(); // Remove any - prefix before doing the name-to-id mapping if (substr($blockname, 0, 1) == '-') { $blockname = substr($blockname, 1); $blockinstance->visible = 0; } else { $blockinstance->visible = 1; } $blockinstance->blockid = $blockrecords[$blockname]->id; $blockinstance->pageid = $restore->course_id; $blockinstance->pagetype = PAGE_COURSE_VIEW; $blockinstance->position = $blockposition; $blockinstance->weight = $blockweight; if (!($status = $DB->insert_record('block_instance', $blockinstance))) { $status = false; } ++$blockweight; } } } } else { if ($backup_block_format == 'instances') { $status = restore_create_block_instances($restore, $xml_file); } } return $status; }
function create_course($course_ext, $skip_fix_course_sortorder = 0) { global $CFG, $DB, $OUTPUT; // override defaults with template course if (!empty($CFG->enrol_ldap_template)) { $course = $DB->get_record("course", array('shortname' => $CFG->enrol_ldap_template)); unset($course->id); // so we are clear to reinsert the record unset($course->sortorder); } else { // set defaults $course = new object(); $course->format = 'topics'; } // override with required ext data $course->idnumber = $course_ext[$CFG->enrol_ldap_course_idnumber][0]; $course->fullname = $course_ext[$CFG->enrol_ldap_course_fullname][0]; $course->shortname = $course_ext[$CFG->enrol_ldap_course_shortname][0]; if (empty($course->idnumber) || empty($course->fullname) || empty($course->shortname)) { // we are in trouble! error_log("Cannot create course: missing required data from the LDAP record!"); error_log(var_export($course, true)); return false; } $course->summary = empty($CFG->enrol_ldap_course_summary) || empty($course_ext[$CFG->enrol_ldap_course_summary][0]) ? '' : $course_ext[$CFG->enrol_ldap_course_summary][0]; $category = get_course_category($CFG->enrol_db_category); // put at the end of category $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - 1; // override with local data $course->startdate = time(); $course->timecreated = time(); $course->visible = 1; // store it and log if ($newcourseid = $DB->insert_record("course", $course)) { // Set up new course $section = new object(); $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = $DB->insert_record("course_sections", $section); $course = $DB->get_record('course', array('id' => $newcourseid)); blocks_add_default_course_blocks($course); if (!$skip_fix_course_sortorder) { fix_course_sortorder(); } add_to_log($newcourseid, "course", "new", "view.php?id={$newcourseid}", "enrol/ldap auto-creation"); } else { error_log("Could not create new course from LDAP from DN:" . $course_ext['dn']); echo $OUTPUT->notification("Serious Error! Could not create the new course!"); return false; } return $newcourseid; }
/** * Create a course and either return a $course object or false * * @param object $data - all the data needed for an entry in the 'course' table */ function create_course($data) { global $CFG, $USER, $DB; //check the categoryid if (!empty($data->category) && !$data->category == 0) { $category = $DB->get_record('course_categories', array('id' => $data->category)); if (empty($category)) { throw new moodle_exception('noexistingcategory'); } } //check if the shortname already exist if (!empty($data->shortname)) { $course = $DB->get_record('course', array('shortname' => $data->shortname)); if (!empty($course)) { throw new moodle_exception('shortnametaken'); } } //check if the id number already exist if (!empty($data->idnumber)) { $course = $DB->get_record('course', array('idnumber' => $data->idnumber)); if (!empty($course)) { throw new moodle_exception('idnumbertaken'); } } // preprocess allowed mods $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods; unset($data->allowedmods); if ($CFG->restrictmodulesfor == 'all') { $data->restrictmodules = 1; // if the user is not an admin, get the default allowed modules because // there are no modules passed by the form if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { if (!$allowedmods && $CFG->defaultallowedmodules) { $allowedmods = explode(',', $CFG->defaultallowedmodules); } } } else { $data->restrictmodules = 0; } $data->timecreated = time(); // place at beginning of any category $data->sortorder = 0; if ($newcourseid = $DB->insert_record('course', $data)) { // Set up new course $course = $DB->get_record('course', array('id' => $newcourseid)); // Setup the blocks blocks_add_default_course_blocks($course); update_restricted_mods($course, $allowedmods); $section = new object(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->id = $DB->insert_record('course_sections', $section); fix_course_sortorder(); add_to_log(SITEID, 'course', 'new', 'view.php?id=' . $course->id, $data->fullname . ' (ID ' . $course->id . ')'); // Save any custom role names. save_local_role_names($course->id, $data); // Trigger events events_trigger('course_created', $course); return $course; } return false; // error }
public function resetCourseBlocks() { global $CFG; require_once gcr::moodleDir . 'lib/blocklib.php'; $courses = get_courses(); //can be feed categoryid to just effect one category foreach ($courses as $course) { $context = get_context_instance(CONTEXT_COURSE, $course->id); blocks_delete_all_for_context($context->id); blocks_add_default_course_blocks($course); } }
/** * 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; // Get configs. $truncatecoursecodes = $this->get_config('truncatecoursecodes'); $createnewcourses = $this->get_config('createnewcourses'); $createnewcategories = $this->get_config('createnewcategories'); // Process tag contents. $group = new stdClass(); if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) { $group->coursecode = trim($matches[1]); } if (preg_match('{<description>.*?<long>(.*?)</long>.*?</description>}is', $tagcontents, $matches)) { $group->long = trim($matches[1]); } if (preg_match('{<description>.*?<short>(.*?)</short>.*?</description>}is', $tagcontents, $matches)) { $group->short = trim($matches[1]); } if (preg_match('{<description>.*?<full>(.*?)</full>.*?</description>}is', $tagcontents, $matches)) { $group->full = trim($matches[1]); } if (preg_match('{<org>.*?<orgunit>(.*?)</orgunit>.*?</org>}is', $tagcontents, $matches)) { $group->category = trim($matches[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); if (!$DB->get_field('course', 'id', array('idnumber' => $coursecode))) { 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 field if present). if (!empty($group->category)) { // If the category is defined and exists in Moodle, we want to store it in that one. if ($catid = $DB->get_field('course_categories', 'id', array('name' => $group->category))) { $course->category = $catid; } else { if ($createnewcategories) { // Else if we're allowed to create new categories, let's create this one. $newcat = new stdClass(); $newcat->name = $group->category; $newcat->visible = 0; $catid = $DB->insert_record('course_categories', $newcat); $course->category = $catid; $this->log_line("Created new (hidden) category, #{$catid}: {$newcat->name}"); } else { // If not found and not allowed to create, stick with default. $this->log_line('Category ' . $group->category . ' not found in Moodle database, so using ' . 'default category instead.'); $course->category = $this->get_default_category_id(); } } } else { $course->category = $this->get_default_category_id(); } $course->timecreated = time(); $course->startdate = time(); // Choose a sort order that puts us at the start of the list! $course->sortorder = 0; $courseid = $DB->insert_record('course', $course); // Setup default enrolment plugins. $course->id = $courseid; enrol_course_updated(true, $course, null); // Setup the blocks. $course = $DB->get_record('course', array('id' => $courseid)); blocks_add_default_course_blocks($course); // Create default 0-section. course_create_sections_if_missing($course, 0); add_to_log(SITEID, "course", "new", "view.php?id={$course->id}", "{$course->fullname} (ID {$course->id})"); $this->log_line("Created course {$coursecode} in Moodle (Moodle ID is {$course->id})"); } } else { if ($recstatus == 3 && ($courseid = $DB->get_field('course', 'id', array('idnumber' => $coursecode)))) { // If course does exist, but recstatus==3 (delete), then set the course as hidden. $DB->set_field('course', 'visible', '0', array('id' => $courseid)); } } } } }
/** * Attempts to insert a course into the moodle database * * @param type $course * @return string */ function up_insert_course($course) { global $DB; $courserequestnumber = $course->idnumber; $category = $course->category; $dbinfo = get_db_info(); $oc = new stdClass(); try { $oc = oci_connect($dbinfo->username, $dbinfo->password, $dbinfo->db); } catch (exception $e) { print $e->getMessage(); } // Check if the course exists if (up_course_exists($courserequestnumber, $category)) { add_to_log('1', 'course', 'error', '', "Course already exists: BannerID: {$courserequestnumber}", '', '4'); // Mark course as added in banner $totalrows = 0; $query = "INSERT INTO UP_MOODLE.TBL_UPM_COURSE_SYNC VALUES ('{$courserequestnumber}','{$course->termcode}','Y')"; $sql = oci_parse($oc, $query); oci_execute($sql); $results = array(); $rows = oci_fetch_all($sql, $results, 0, $totalrows, OCI_FETCHSTATEMENT_BY_ROW); if ($rows = false) { print 'Insert to TBL_UPM_COURSE_SYNC failed. Sync may be broken.'; exit; } return COURSE_ALREADY_EXISTS; } else { if ($newcourseid = $DB->insert_record('course', $course)) { if (UP_DEBUG) { print "New Course ID is: " . $newcourseid . "<br />\n"; } //get the newly inserted course so we can add the default blocks $newMoodleCourse = $DB->get_record('course', array('id' => $newcourseid)); $data = $course; $course = course_get_format($newcourseid)->get_course(); // Setup the blocks blocks_add_default_course_blocks($newMoodleCourse); //set section information and insert into the section database $section = new stdClass(); $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->summaryformat = FORMAT_HTML; try { $DB->insert_record('course_sections', $section); } catch (coding_exception $e) { print $e->getMessage(); } fix_course_sortorder(); up_add_enrol_plugin('manual', true, $course, $data); // Mark course as added in banner $totalrows = 0; $query = "INSERT INTO UP_MOODLE.TBL_UPM_COURSE_SYNC VALUES ('{$courserequestnumber}','{$data->termcode}','Y')"; $sql = oci_parse($oc, $query); oci_execute($sql); $results = array(); $rows = oci_fetch_all($sql, $results, 0, $totalrows, OCI_FETCHSTATEMENT_BY_ROW); if ($rows = false) { print 'Insert to TBL_UPM_COURSE_SYNC failed. Sync may be broken.'; exit; } $event = \core\event\course_created::create(array('objectid' => $course->id, 'context' => context_course::instance($course->id), 'other' => array('shortname' => $course->shortname, 'fullname' => $course->fullname))); $event->trigger(); return COURSE_CREATION_SUCCEEDED; } else { add_to_log('1', 'course', 'error', '', "Creating: {$shortname} (BANID {$courserequestnumber})", '', '4'); return COURSE_CREATION_FAILED; } } // end of else on if ( $newcourseid = $DB->insert_record('course', $form) ) }
function create_course($course, $skip_fix_course_sortorder = 0) { global $CFG, $DB; // define a template if (!empty($CFG->enrol_db_template)) { $template = $DB->get_record("course", array('shortname' => $CFG->enrol_db_template)); $template = (array) $template; } else { $site = get_site(); $template = array('startdate' => time() + 3600 * 24, 'summary' => get_string("defaultcoursesummary"), 'format' => "weeks", 'password' => "", 'guest' => 0, 'numsections' => 10, 'idnumber' => '', 'cost' => '', 'newsitems' => 5, 'showgrades' => 1, 'groupmode' => 0, 'groupmodeforce' => 0); } // overlay template foreach (array_keys($template) as $key) { if (empty($course->{$key})) { $course->{$key} = $template[$key]; } } $category = get_course_category($CFG->enrol_db_category); // put at the end of category $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - 1; // override with local data $course->startdate = time() + 3600 * 24; $course->timecreated = time(); $course->visible = 1; // clear out id just in case unset($course->id); // truncate a few key fields $course->idnumber = substr($course->idnumber, 0, 100); $course->shortname = substr($course->shortname, 0, 100); // store it and log if ($newcourseid = $DB->insert_record("course", $course)) { // Set up new course $section = new object(); $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = $DB->insert_record("course_sections", $section); $course = $DB->get_record('course', array('id' => $newcourseid)); blocks_add_default_course_blocks($course); if (!$skip_fix_course_sortorder) { fix_course_sortorder(); } add_to_log($newcourseid, "course", "new", "view.php?id={$newcourseid}", "enrol/database auto-creation"); } else { trigger_error("Could not create new course {$extcourse} from from database"); notify("Serious Error! Could not create the new course!"); return false; } return $newcourseid; }
if (!isset($sitenewsitems)) { $sitenewsitems = $DEFAULT['sitenewsitems']; } $newsite = new Object(); $newsite->fullname = $sitefullname; $newsite->shortname = $siteshortname; $newsite->summary = $sitesummary; $newsite->newsitems = $sitenewsitems; $newsite->numsections = 0; $newsite->category = 0; $newsite->format = 'site'; // Only for this course $newsite->timemodified = time(); if ($newid = $DB->insert_record('course', $newsite)) { // Site created, add blocks for it blocks_add_default_course_blocks($DB->get_record('course', array('id' => $newid))); // create default course category $cat = get_course_category(); } } /// Define the unique site ID code if it isn't already if (empty($CFG->siteidentifier)) { // Unique site identification code set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']); } /// Check if the guest user exists. If not, create one. if (!$DB->record_exists("user", array("username" => "guest"))) { if (!($guest = create_guest_record())) { notify("Could not create guest user record !!!"); } }
/** * Process the group tag. This defines a Moodle course. * @param string $tagconents The raw contents of the XML element */ function process_group_tag($tagcontents) { global $CFG, $DB; // Process tag contents unset($group); if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) { $group->coursecode = trim($matches[1]); } if (preg_match('{<description>.*?<short>(.*?)</short>.*?</description>}is', $tagcontents, $matches)) { $group->description = trim($matches[1]); } if (preg_match('{<org>.*?<orgunit>(.*?)</orgunit>.*?</org>}is', $tagcontents, $matches)) { $group->category = trim($matches[1]); } $recstatus = $this->get_recstatus($tagcontents, 'group'); //echo "<p>get_recstatus for this group returned $recstatus</p>"; if (!(strlen($group->coursecode) > 0)) { $this->log_line('Error at line ' . $line . ': Unable to find course code in \'group\' element.'); } else { // First, truncate the course code if desired if (intval($CFG->enrol_truncatecoursecodes) > 0) { $group->coursecode = $CFG->enrol_truncatecoursecodes > 0 ? substr($group->coursecode, 0, intval($CFG->enrol_truncatecoursecodes)) : $group->coursecode; } /* -----------Course aliasing is DEACTIVATED until a more general method is in place--------------- // Second, look in the course alias table to see if the code should be translated to something else if($aliases = $DB->get_field('enrol_coursealias', 'toids', array('fromid'=>$group->coursecode))){ $this->log_line("Found alias of course code: Translated $group->coursecode to $aliases"); // Alias is allowed to be a comma-separated list, so let's split it $group->coursecode = explode(',', $aliases); } */ // 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); if (!$DB->get_field('course', 'id', array('idnumber' => $coursecode))) { if (!$CFG->enrol_createnewcourses) { $this->log_line("Course {$coursecode} not found in Moodle's course idnumbers."); } else { // Create the (hidden) course(s) if not found $course = new object(); $course->fullname = $group->description; $course->shortname = $coursecode; $course->idnumber = $coursecode; $course->format = 'topics'; $course->visible = 0; // Insert default names for teachers/students, from the current language $site = get_site(); // Handle course categorisation (taken from the group.org.orgunit field if present) if (strlen($group->category) > 0) { // If the category is defined and exists in Moodle, we want to store it in that one if ($catid = $DB->get_field('course_categories', 'id', array('name' => $group->category))) { $course->category = $catid; } elseif ($CFG->enrol_createnewcategories) { // Else if we're allowed to create new categories, let's create this one $newcat->name = $group->category; $newcat->visible = 0; if ($catid = $DB->insert_record('course_categories', $newcat)) { $course->category = $catid; $this->log_line("Created new (hidden) category, #{$catid}: {$newcat->name}"); } else { $this->log_line('Failed to create new category: ' . $newcat->name); } } else { // If not found and not allowed to create, stick with default $this->log_line('Category ' . $group->category . ' not found in Moodle database, so using default category instead.'); $course->category = 1; } } else { $course->category = 1; } $course->timecreated = time(); $course->startdate = time(); $course->numsections = 1; // Choose a sort order that puts us at the start of the list! $course->sortorder = 0; if ($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 object(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->id = $DB->insert_record("course_sections", $section); add_to_log(SITEID, "course", "new", "view.php?id={$course->id}", "{$course->fullname} (ID {$course->id})"); $this->log_line("Created course {$coursecode} in Moodle (Moodle ID is {$course->id})"); } else { $this->log_line('Failed to create course ' . $coursecode . ' in Moodle'); } } } elseif ($recstatus == 3 && ($courseid = $DB->get_field('course', 'id', array('idnumber' => $coursecode)))) { // If course does exist, but recstatus==3 (delete), then set the course as hidden $DB->set_field('course', 'visible', '0', array('id' => $courseid)); } } // End of foreach(coursecode) } }