function fastcreatecourse_ex($hcategory, $course, $header, $validate) { if (!is_array($course) || !is_array($header) || !is_array($validate)) { return -2; } global $CFG; // declaring as static prevents object pointers being continually created and destroyed, saving time in theory static $courseid; static $mysqlresource1; static $mysqlresource2; static $mysqlresource3; static $mysqlresource4; static $dcomma; // Creating SQL for composite fields static $dtopics; static $dtopicno; static $dtopicname; static $dteachers; static $dteacherno; static $dteacherdata; // Dynamically Create Query Based on number of headings excluding Teacher[1,2,...] and Topic[1,2,...] // Added for increased functionality with newer versions of moodle // Author: Ashley Gooding & Cole Spicer static $tempstring; $query = 'INSERT INTO `' . $CFG->prefix . 'course` (`category`,'; foreach ($header as $i => $col) { $col = strtolower($col); if (preg_match(TOPIC_FIELD, $col) || preg_match(TEACHER_FIELD, $col) || $col == 'category' || $col == 'template') { continue; } $query = $query . '`' . $col . '`,'; } $query = $query . '`modinfo`) VALUES (' . $hcategory . ','; foreach ($header as $i => $col) { $col = strtolower($col); if (preg_match(TOPIC_FIELD, $col) || preg_match(TEACHER_FIELD, $col) || $col == 'category' || $col == 'template') { continue; } if ($col == 'expirythreshold') { $course[$col] = $course[$col] * 86400; } $temparray = explode(',', $validate[$col][1]); if ($validate[$col][0] == 1 || $validate[$col][0] == 4 && !checkisint($temparray[0])) { //String or Domain with strings $query = $query . '' . mystr($course[$col]) . ', '; } else { $query = $query . '' . $course[$col] . ', '; } } $query = $query . ' \'\');'; // End Dynamic Query if (!($mysqlresource2 = mysql_query($query))) { return -2; } $courseid = mysql_insert_id(); if (isset($course['template']) && $course['template'] != '') { if (!($mysqlresource6 = mysql_query('SELECT `id` FROM `' . $CFG->prefix . 'course` WHERE `shortname`=\'' . $course['template'] . '\';'))) { return -7; } if (!mysql_num_rows($mysqlresource6)) { return -7; } $row = mysql_fetch_row($mysqlresource6); $id = $row[0]; if (!($mysqlresource7 = mysql_query(' INSERT INTO `' . $CFG->prefix . 'block_instance` ( `blockid` , `pageid` , `pagetype` , `position` , `weight` , `visible` , `configdata` ) SELECT `blockid` , ' . $courseid . ', `pagetype` , `position` , `weight` , `visible` , `configdata` FROM `' . $CFG->prefix . 'block_instance` WHERE `pageid` = ' . $id . ';'))) { return -8; } } else { $page = page_create_object(PAGE_COURSE_VIEW, $courseid); blocks_repopulate_page($page); // Setup blocks } $dtopics = ''; // String concatenation for topic INSERT $dcomma = false; // Should we add a comma before the next item? if (isset($course['topics'])) { // Any topic headings specified ? foreach ($course['topics'] as $dtopicno => $dtopicname) { if ($dtopicno <= $course['numsections']) { // Avoid overflowing topic headings if ($dcomma == true) { $dtopics .= ','; } else { $dcomma = true; } $dtopics .= '(' . $courseid . ',' . mystr($dtopicno) . ',' . mystr($dtopicname) . ',\'\',\'1\')'; } } } if (!isset($course['topics'][0])) { // Ensure at least default topic section exists if ($dcomma == true) { $dtopics .= ','; } else { $dcomma = true; } $dtopics .= '(\'' . $courseid . '\',\'0\',\'\',\'\',\'1\');'; } else { $dtopics .= ';'; } if (!($mysqlresource3 = mysql_query('INSERT INTO `' . $CFG->prefix . 'course_sections` (`course`,`section`,`summary`,`sequence`,`visible`) VALUES ' . $dtopics))) { return -3; } $dteachers = ''; // String concatenation for topic INSERT $dcomma = false; // Should we add a comma before the next item? // SELECT id FROM mdl_role WHERE name = blah // use that id and change insert to: // mdl_role_assignments // roleid contextid userid timemodified modifierid enrol // courseshit 0 'manual' // If SELECT id... doesnt work (returns false or contians no items) then throw error $roleid; if (!($context = get_context_instance(CONTEXT_COURSE, $courseid))) { return -6; } if (isset($course['teachers_enrol']) && count($course['teachers_enrol']) > 0) { // Any teachers specified? foreach ($course['teachers_enrol'] as $dteacherno => $dteacherdata) { if (isset($dteacherdata['_account'])) { if ($dcomma == true) { $dteachers .= ','; } else { $dcomma = true; } if (!($mysqlresource5 = mysql_query('SELECT `id` FROM `' . $CFG->prefix . 'role` WHERE `shortname`=\'' . $dteacherdata['_role'] . '\';'))) { return -5; } if (!mysql_num_rows($mysqlresource5)) { return -5; } $row = mysql_fetch_row($mysqlresource5); $dteachers .= '(' . $row[0] . ',' . $context->id . ',' . $dteacherdata['_account'] . ',' . $course['timecreated'] . ',0,\'manual\');'; } } if ($dteachers != '') { if (!($mysqlresource4 = mysql_query('INSERT INTO `' . $CFG->prefix . 'role_assignments` (`roleid`,`contextid`,`userid`,`timemodified`,`modifierid`,`enrol`) VALUES ' . $dteachers))) { return -4; } } } return 1; }
function upgrade_blocks_plugins($continueto) { global $CFG, $db; $blocktitles = array(); $invalidblocks = array(); $validblocks = array(); $notices = array(); //Count the number of blocks in db $blockcount = count_records('block'); //If there isn't records. This is the first install, so I remember it if ($blockcount == 0) { $first_install = true; } else { $first_install = false; } $site = get_site(); if (!($blocks = get_list_of_plugins('blocks', 'db'))) { error('No blocks installed!'); } include_once $CFG->dirroot . '/blocks/moodleblock.class.php'; if (!class_exists('block_base')) { error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php'); } foreach ($blocks as $blockname) { if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it continue; } if (!block_is_compatible($blockname)) { // This is an old-style block //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.'; $invalidblocks[] = $blockname; continue; } $fullblock = $CFG->dirroot . '/blocks/' . $blockname; if (is_readable($fullblock . '/block_' . $blockname . '.php')) { include_once $fullblock . '/block_' . $blockname . '.php'; } else { $notices[] = 'Block ' . $blockname . ': ' . $fullblock . '/block_' . $blockname . '.php was not readable'; continue; } $oldupgrade = false; $newupgrade = false; if (@is_dir($fullblock . '/db/')) { if (@is_readable($fullblock . '/db/' . $CFG->dbtype . '.php')) { include_once $fullblock . '/db/' . $CFG->dbtype . '.php'; // defines old upgrading function $oldupgrade = true; } if (@is_readable($fullblock . '/db/upgrade.php')) { include_once $fullblock . '/db/upgrade.php'; // defines new upgrading function $newupgrade = true; } } $classname = 'block_' . $blockname; if (!class_exists($classname)) { $notices[] = 'Block ' . $blockname . ': ' . $classname . ' not implemented'; continue; } // Here is the place to see if the block implements a constructor (old style), // an init() function (new style) or nothing at all (error time). $constructor = get_class_constructor($classname); if (empty($constructor)) { // No constructor $notices[] = 'Block ' . $blockname . ': class does not have a constructor'; $invalidblocks[] = $blockname; continue; } $block = new stdClass(); // This may be used to update the db below $blockobj = new $classname(); // This is what we 'll be testing // Inherits from block_base? if (!is_subclass_of($blockobj, 'block_base')) { $notices[] = 'Block ' . $blockname . ': class does not inherit from block_base'; continue; } // OK, it's as we all hoped. For further tests, the object will do them itself. if (!$blockobj->_self_test()) { $notices[] = 'Block ' . $blockname . ': self test failed'; continue; } $block->version = $blockobj->get_version(); if (!isset($block->version)) { $notices[] = 'Block ' . $blockname . ': has no version support. It must be updated by a programmer.'; continue; } $block->name = $blockname; // The name MUST match the directory $blocktitle = $blockobj->get_title(); if ($currblock = get_record('block', 'name', $block->name)) { if ($currblock->version == $block->version) { // do nothing } else { if ($currblock->version < $block->version) { if (empty($updated_blocks)) { $strblocksetup = get_string('blocksetup'); print_header($strblocksetup, $strblocksetup, build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); } $updated_blocks = true; upgrade_log_start(); print_heading('New version of ' . $blocktitle . ' (' . $block->name . ') exists'); @set_time_limit(0); // To allow slow databases to complete the long SQL /// Run de old and new upgrade functions for the module $oldupgrade_function = $block->name . '_upgrade'; $newupgrade_function = 'xmldb_block_' . $block->name . '_upgrade'; /// First, the old function if exists $oldupgrade_status = true; if ($oldupgrade && function_exists($oldupgrade_function)) { $db->debug = true; $oldupgrade_status = $oldupgrade_function($currblock->version, $block); } else { if ($oldupgrade) { notify('Upgrade function ' . $oldupgrade_function . ' was not available in ' . $fullblock . '/db/' . $CFG->dbtype . '.php'); } } /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { $db->debug = true; $newupgrade_status = $newupgrade_function($currblock->version, $block); } else { if ($newupgrade) { notify('Upgrade function ' . $newupgrade_function . ' was not available in ' . $fullblock . '/db/upgrade.php'); } } $db->debug = false; /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed // Set the block cron on upgrade $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0; // OK so far, now update the block record $block->id = $currblock->id; if (!update_record('block', $block)) { error('Could not update block ' . $block->name . ' record in block table!'); } $component = 'block/' . $block->name; if (!update_capabilities($component)) { error('Could not update ' . $block->name . ' capabilities!'); } events_update_definition($component); notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess'); } else { notify('Upgrading block ' . $block->name . ' from ' . $currblock->version . ' to ' . $block->version . ' FAILED!'); } echo '<hr />'; } else { upgrade_log_start(); error('Version mismatch: block ' . $block->name . ' can\'t downgrade ' . $currblock->version . ' -> ' . $block->version . '!'); } } } else { // block not installed yet, so install it // If it allows multiples, start with it enabled if ($blockobj->instance_allow_multiple()) { $block->multiple = 1; } // Set the block cron on install $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0; // [pj] Normally this would be inline in the if, but we need to // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0) $conflictblock = array_search($blocktitle, $blocktitles); if ($conflictblock !== false && $conflictblock !== NULL) { // Duplicate block titles are not allowed, they confuse people // AND PHP's associative arrays ;) error('<strong>Naming conflict</strong>: block <strong>' . $block->name . '</strong> has the same title with an existing block, <strong>' . $conflictblock . '</strong>!'); } if (empty($updated_blocks)) { $strblocksetup = get_string('blocksetup'); print_header($strblocksetup, $strblocksetup, build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); } $updated_blocks = true; upgrade_log_start(); print_heading($block->name); $db->debug = true; @set_time_limit(0); // To allow slow databases to complete the long SQL /// Both old .sql files and new install.xml are supported /// but we priorize install.xml (XMLDB) if present $status = false; if (file_exists($fullblock . '/db/install.xml')) { $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method } else { if (file_exists($fullblock . '/db/' . $CFG->dbtype . '.sql')) { $status = modify_database($fullblock . '/db/' . $CFG->dbtype . '.sql'); //Old method } else { $status = true; } } $db->debug = false; if ($status) { if ($block->id = insert_record('block', $block)) { $blockobj->after_install(); $component = 'block/' . $block->name; if (!update_capabilities($component)) { notify('Could not set up ' . $block->name . ' capabilities!'); } events_update_definition($component); notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess'); echo '<hr />'; } else { error($block->name . ' block could not be added to the block list!'); } } else { error('Block ' . $block->name . ' tables could NOT be set up successfully!'); } } $blocktitles[$block->name] = $blocktitle; } if (!empty($notices)) { upgrade_log_start(); foreach ($notices as $notice) { notify($notice); } } // Finally, if we are in the first_install of BLOCKS (this means that we are // upgrading from Moodle < 1.3), put blocks in all existing courses. if ($first_install) { upgrade_log_start(); //Iterate over each course if ($courses = get_records('course')) { foreach ($courses as $course) { $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_repopulate_page($page); } } } if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade upgrade_log_start(); $page = page_create_object(PAGE_COURSE_VIEW, SITEID); blocks_repopulate_page($page); delete_records('config', 'name', 'siteblocksadded'); } upgrade_log_finish(); if (!empty($updated_blocks)) { print_continue($continueto); print_footer('none'); die; } }
} $course->requested = 1; unset($course->reason); unset($course->id); $teacherid = $course->requester; unset($course->requester); $course->teacher = get_string("defaultcourseteacher"); $course->teachers = get_string("defaultcourseteachers"); $course->student = get_string("defaultcoursestudent"); $course->students = get_string("defaultcoursestudents"); if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { $course->restrictmodules = 1; } if ($courseid = insert_record("course", $course)) { $page = page_create_object(PAGE_COURSE_VIEW, $courseid); blocks_repopulate_page($page); // Return value not checked because you can always edit later add_teacher($teacherid, $courseid); $course->id = $courseid; 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); } delete_records('course_request', 'id', $approve); $success = 1; } if (!empty($success)) { $user = get_record('user', 'id', $teacherid); $a->name = $course->fullname; $a->url = $CFG->wwwroot . '/course/view.php?id=' . $courseid;
function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) { global $CFG; $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... $newpage = page_create_object(PAGE_COURSE_VIEW, $restore->course_id); blocks_repopulate_page($newpage); } else { // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup $blockrecords = get_records_select('block', '', '', '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 = 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; // override defaults with template course if (!empty($CFG->enrol_ldap_template)) { $course = get_record("course", '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->student = get_string('defaultcoursestudent'); $course->students = get_string('defaultcoursestudents'); $course->teacher = get_string('defaultcourseteacher'); $course->teachers = get_string('defaultcourseteachers'); $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]; if (!empty($CFG->enrol_ldap_category)) { // optional ... but ensure it is set! $course->category = $CFG->enrol_ldap_category; } if ($course->category == 0) { // must be avoided as it'll break moodle $course->category = 1; // the misc 'catch-all' category } // define the sortorder (yuck) $sort = get_record_sql('SELECT MAX(sortorder) AS max, 1 FROM ' . $CFG->prefix . 'course WHERE category=' . $course->category); $sort = $sort->max; $sort++; $course->sortorder = $sort; // override with local data $course->startdate = time(); $course->timecreated = time(); $course->visible = 1; $course = addslashes_recursive($course); // store it and log if ($newcourseid = insert_record("course", $course)) { // Set up new course $section = new object(); $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = insert_record("course_sections", $section); $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid); blocks_repopulate_page($page); // Return value no 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']); notify("Serious Error! Could not create the new course!"); return false; } return $newcourseid; }
function create_course($course, $skip_fix_course_sortorder = 0) { global $CFG; // define a template if (!empty($CFG->enrol_db_template)) { $template = get_record("course", '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, 'student' => $site->student, 'students' => $site->students, 'teacher' => $site->teacher, 'teachers' => $site->teachers); } // overlay template foreach (array_keys($template) as $key) { if (empty($course->{$key})) { $course->{$key} = $template[$key]; } } $course->category = 1; // the misc 'catch-all' category if (!empty($CFG->enrol_db_category)) { //category = 0 or undef will break moodle $course->category = $CFG->enrol_db_category; } // define the sortorder $sort = get_field_sql('SELECT COALESCE(MAX(sortorder)+1, 100) AS max ' . ' FROM ' . $CFG->prefix . 'course ' . ' WHERE category=' . $course->category); $course->sortorder = $sort; // 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 = insert_record("course", addslashes_object($course))) { // Set up new course $section = NULL; $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = insert_record("course_sections", $section); $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid); blocks_repopulate_page($page); // Return value no 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; }
/** * 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; // 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 category fix_course_sortorder(); $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category={$data->category}"); if (empty($data->sortorder)) { $data->sortorder = 100; } if ($newcourseid = insert_record('course', $data)) { // Set up new course $course = get_record('course', 'id', $newcourseid); // Setup the blocks $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_repopulate_page($page); // Return value not checked because you can always edit later update_restricted_mods($course, $allowedmods); $section = new object(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->id = 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 }
/** * 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; // 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 = get_field('enrol_coursealias', 'toids', '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 (!get_field('course', 'id', '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(); if (current_language() == $CFG->lang) { $course->teacher = $site->teacher; $course->teachers = $site->teachers; $course->student = $site->student; $course->students = $site->students; } else { $course->teacher = get_string("defaultcourseteacher"); $course->teachers = get_string("defaultcourseteachers"); $course->student = get_string("defaultcoursestudent"); $course->students = get_string("defaultcoursestudents"); } // 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 = get_field('course_categories', 'id', 'name', addslashes($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 = 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! $sortinfo = get_record_sql('SELECT MIN(sortorder) AS min, MAX(sortorder) AS max FROM ' . $CFG->prefix . 'course WHERE category<>0'); if (is_object($sortinfo)) { // no courses? $max = $sortinfo->max; $min = $sortinfo->min; unset($sortinfo); $course->sortorder = $min - 1; } else { $course->sortorder = 1000; } if ($course->id = insert_record('course', addslashes_object($course))) { // Setup the blocks $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_repopulate_page($page); // Return value not checked because you can always edit later $section = new object(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->id = 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 = get_field('course', 'id', 'idnumber', $coursecode))) { // If course does exist, but recstatus==3 (delete), then set the course as hidden set_field('course', 'visible', '0', 'id', $courseid); } } // End of foreach(coursecode) } }
function create_course($data) { global $CFG, $USER; // preprocess allowed mods $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods; unset($data->allowedmods); if ($CFG->restrictmodulesfor == 'all') { $data->restrictmodules = 1; } else { $data->restrictmodules = 0; } $data->timecreated = time(); // place at beginning of category fix_course_sortorder(); $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category={$data->category}"); if (empty($data->sortorder)) { $data->sortorder = 100; } if ($newcourseid = insert_record('course', $data)) { // Set up new course $course = get_record('course', 'id', $newcourseid); // Setup the blocks $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_repopulate_page($page); // Return value not checked because you can always edit later update_restricted_mods($course, $allowedmods); $section = new object(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->id = insert_record('course_sections', $section); fix_course_sortorder(); 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; } return false; // error }
public function importCourses($xml, $catID, $catName) { //DOM parsing and validating $dom = new DOMDocument(); $dom->loadXML($xml); if (!@$dom->schemaValidate($this->courses_schema)) { throw new MoodlePluginException("ERROR, not valid XML data...", 2); } //Check if category exists if (!record_exists($this->categories_table, "id", $catID, "name", $catName)) { throw new MoodlePluginException("ERROR, category not found...", 1); } $this->error[$this->courses_table] = array(); //Create new courses $count = 0; $courses = $dom->getElementsByTagName("course"); foreach ($courses as $course) { $newcourse = null; while ($child = $course->firstChild) { $course->removeChild($child); switch ($key = $child->nodeName) { case "id": //ID must be assigned later break; case "category": $newcourse->{$key} = $catID; break; default: $newcourse->{$key} = $child->textContent; break; } } //Try to give an ID to the new course and then insert it in database if ($newcourseid = insert_record($this->courses_table, $newcourse)) { $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid); blocks_repopulate_page($page); // Set up new course $section = NULL; $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = insert_record($this->course_sections_table, $section); $count++; } else { array_push($this->error[$this->courses_table], $newcourse->shortname); } } return $count; }
/** * Change boxlayout for all user's courses by su_isadvanced value * * @param stdClass $olduser user class before update * @param stdClass $newuser user class after update * @author Kowy - Samouk */ function useredit_update_boxlayout($olduser, $newuser) { global $USER; if ($USER->id == $newuser->id) { // only logged user can run this code, because it is repopulated for logged user if ($olduser->su_isadvanced != $newuser->su_isadvanced) { // IsAdvanced user property changed // if user change it's account to advanced, repopulate block arranegement $USER->su_isadvanced = $newuser->su_isadvanced; $courses = get_my_courses($newuser->id, '', 'id'); foreach ($courses as $course) { $page = page_create_object(PAGE_COURSE_VIEW, $course['id']); blocks_repopulate_page($page); // change blocks arrangement } } } }
/** * @see /course/lib.php - create_course * - empty course contents, and clear backups * - doesn't create new course records * - doesn't change sort order * - doesn't update restricted modules */ function rebuild_course($cid) { global $CFG; require_once $CFG->dirroot . '/backup/lib.php'; require_once $CFG->libdir . '/pagelib.php'; empty_course_contents($cid); delete_dir_contents($CFG->dataroot . '/' . $cid, 'backupdata'); $course = get_record('course', 'id', $cid); // Setup the blocks $page = page_create_object(PAGE_COURSE_VIEW, $cid); blocks_repopulate_page($page); // Return value not checked because you can always edit later }