print_error('invalidfunction', '', course_get_url($course, $cw->section)); } else { print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $fromform->modulename); } } $fromform->instance = $returnfromfunc; $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $fromform->coursemodule)); // update embedded links and save files $modcontext = context_module::instance($fromform->coursemodule); if (!empty($introeditor)) { $fromform->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $fromform->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']); $DB->set_field($fromform->modulename, 'intro', $fromform->intro, array('id' => $fromform->instance)); } // course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. $sectionid = course_add_cm_to_section($course, $fromform->coursemodule, $fromform->section); // make sure visibility is set correctly (in particular in calendar) // note: allow them to set it even without moodle/course:activityvisibility set_coursemodule_visible($fromform->coursemodule, $fromform->visible); if (isset($fromform->cmidnumber)) { //label // set cm idnumber - uniqueness is already verified by form validation set_coursemodule_idnumber($fromform->coursemodule, $fromform->cmidnumber); } // Set up conditions if ($CFG->enableavailability) { condition_info::update_cm_from_form((object) array('id' => $fromform->coursemodule), $fromform, false); } $eventname = 'mod_created'; add_to_log($course->id, "course", "add mod", "../mod/{$fromform->modulename}/view.php?id={$fromform->coursemodule}", "{$fromform->modulename} {$fromform->instance}"); add_to_log($course->id, $fromform->modulename, "add", "view.php?id={$fromform->coursemodule}", "{$fromform->instance}", $fromform->coursemodule);
// course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. if (! $currmodule = $DB->get_record("modules", array("name"=>'glossary'))) { print_error('modulenotexist', 'debug', '', 'Glossary'); } $mod->module = $currmodule->id; $mod->course = $course->id; $mod->modulename = 'glossary'; $mod->section = 0; if (! $mod->coursemodule = add_course_module($mod) ) { print_error('cannotaddcoursemodule'); } $sectionid = course_add_cm_to_section($course, $mod->coursemodule, 0); //We get the section's visible field status $visible = $DB->get_field("course_sections", "visible", array("id"=>$sectionid)); $DB->set_field("course_modules", "visible", $visible, array("id"=>$mod->coursemodule)); add_to_log($course->id, "course", "add mod", "../mod/$mod->modulename/view.php?id=$mod->coursemodule", "$mod->modulename $mod->instance"); add_to_log($course->id, $mod->modulename, "add", "view.php?id=$mod->coursemodule", "$mod->instance", $mod->coursemodule); rebuild_course_cache($course->id); echo $OUTPUT->box(get_string("newglossarycreated","glossary"),'generalbox boxaligncenter boxwidthnormal');
/** * Create a migrated turnitin assignment in Moodle * * @global type $DB * @global type $CFG * @param array $partids the ids of turnitin assignment to create as parts of new assignment * @param int $courseid * @param string $assignmentname * @return boolean false if failed */ public static function create_migration_assignment($partids, $courseid, $assignmentname) { global $DB, $CFG, $OUTPUT; $config = turnitintooltwo_admin_config(); $partids = (array) $partids; $tempassignment = new turnitintooltwo_assignment(0, '', 'M'); $newassignment = $tempassignment->update_assignment_from_tii($partids); $newassignment["turnitintooltwo"]->course = $courseid; $newassignment["turnitintooltwo"]->name = $assignmentname; $newassignment["turnitintooltwo"]->numparts = count($partids); $newassignment["turnitintooltwo"]->gradedisplay = 1; $newassignment["turnitintooltwo"]->shownonsubmission = 1; $newassignment["turnitintooltwo"]->usegrademark = $config->usegrademark; // Get maximum grade. $newassignment["turnitintooltwo"]->grade = 0; foreach ($newassignment["parts"] as $part) { if ($newassignment["turnitintooltwo"]->grade < $part->maxmarks) { $newassignment["turnitintooltwo"]->grade = $part->maxmarks; } } $turnitintooltwoassignment = new turnitintooltwo_assignment(0, $newassignment["turnitintooltwo"]); if (!($toolid = $DB->insert_record("turnitintooltwo", $turnitintooltwoassignment->turnitintooltwo))) { turnitintooltwo_activitylog(get_string('migrationassignmentcreationerror', 'turnitintooltwo', $courseid), "REQUEST"); return false; } else { turnitintooltwo_activitylog(get_string('migrationassignmentcreated', 'turnitintooltwo', $toolid), "REQUEST"); } $module = $DB->get_record("modules", array("name" => "turnitintooltwo")); $coursemodule = new stdClass(); $coursemodule->course = $courseid; $coursemodule->module = $module->id; $coursemodule->added = time(); $coursemodule->instance = $toolid; $coursemodule->section = 0; include_once $CFG->dirroot . "/course/lib.php"; // Add Course module and get course section. if (!($coursemodule->coursemodule = add_course_module($coursemodule))) { echo $OUTPUT->notification(get_string('migrationassignmenterror1', 'turnitintooltwo', $courseid)); turnitintooltwo_activitylog(get_string('migrationassignmenterror1', 'turnitintooltwo', $courseid), "REQUEST"); return false; } if (is_callable('course_add_cm_to_section')) { if (!($sectionid = course_add_cm_to_section($coursemodule->course, $coursemodule->coursemodule, $coursemodule->section))) { echo $OUTPUT->notification(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid)); turnitintooltwo_activitylog(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid), "REQUEST"); return false; } } else { if (!($sectionid = add_mod_to_section($coursemodule))) { echo $OUTPUT->notification(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid)); turnitintooltwo_activitylog(get_string('migrationassignmenterror2', 'turnitintooltwo', $courseid), "REQUEST"); return false; } } $DB->set_field("course_modules", "section", $sectionid, array("id" => $coursemodule->coursemodule)); rebuild_course_cache($courseid); foreach ($newassignment["parts"] as $part) { $part->turnitintooltwoid = $toolid; $part->deleted = 0; $part->migrated = -1; if ($part->id = $DB->insert_record("turnitintooltwo_parts", $part)) { turnitintooltwo_activitylog(get_string('migrationassignmentpartcreated', 'turnitintooltwo', $part->id), "REQUEST"); } if ($turnitintooltwoassignment->create_event($toolid, $part->partname, $part->dtdue)) { $part->migrated = 1; $DB->update_record("turnitintooltwo_parts", $part); } else { echo $OUTPUT->notification(get_string('migrationassignmenterror3', 'turnitintooltwo', $courseid)); turnitintooltwo_activitylog(get_string('migrationassignmenterror3', 'turnitintooltwo', $courseid), "REQUEST"); } } }
public function test_course_add_cm_to_section() { global $DB; $this->resetAfterTest(true); // Create course with 1 section. $course = $this->getDataGenerator()->create_course(array('shortname' => 'GrowingCourse', 'fullname' => 'Growing Course', 'numsections' => 1), array('createsections' => true)); // Trash modinfo. rebuild_course_cache($course->id, true); // Create some cms for testing. $cmids = array(); for ($i = 0; $i < 4; $i++) { $cmids[$i] = $DB->insert_record('course_modules', array('course' => $course->id)); } // Add it to section that exists. course_add_cm_to_section($course, $cmids[0], 1); // Check it got added to sequence. $sequence = $DB->get_field('course_sections', 'sequence', array('course' => $course->id, 'section' => 1)); $this->assertEquals($cmids[0], $sequence); // Add a second, this time using courseid variant of parameters. $coursecacherev = $DB->get_field('course', 'cacherev', array('id' => $course->id)); course_add_cm_to_section($course->id, $cmids[1], 1); $sequence = $DB->get_field('course_sections', 'sequence', array('course' => $course->id, 'section' => 1)); $this->assertEquals($cmids[0] . ',' . $cmids[1], $sequence); // Check that modinfo cache was reset but not rebuilt (important for performance if calling repeatedly). $this->assertGreaterThan($coursecacherev, $DB->get_field('course', 'cacherev', array('id' => $course->id))); $this->assertEmpty(cache::make('core', 'coursemodinfo')->get($course->id)); // Add one to section that doesn't exist (this might rebuild modinfo). course_add_cm_to_section($course, $cmids[2], 2); $this->assertEquals(3, $DB->count_records('course_sections', array('course' => $course->id))); $sequence = $DB->get_field('course_sections', 'sequence', array('course' => $course->id, 'section' => 2)); $this->assertEquals($cmids[2], $sequence); // Add using the 'before' option. course_add_cm_to_section($course, $cmids[3], 2, $cmids[2]); $this->assertEquals(3, $DB->count_records('course_sections', array('course' => $course->id))); $sequence = $DB->get_field('course_sections', 'sequence', array('course' => $course->id, 'section' => 2)); $this->assertEquals($cmids[3] . ',' . $cmids[2], $sequence); }
/** * Called after the mod has set itself up, to finish off any course module settings * (set instance id, add to correct section, set visibility, etc.) and send the response * * @param int $instanceid id returned by the mod when it was created */ protected function finish_setup_course_module($instanceid) { global $DB, $USER; if (!$instanceid) { // Something has gone wrong - undo everything we can. delete_course_module($this->cm->id); throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name); } $DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm->id)); // Rebuild the course cache after update action rebuild_course_cache($this->course->id, true); $this->course->modinfo = null; // Otherwise we will just get the old version back again. $sectionid = course_add_cm_to_section($this->course, $this->cm->id, $this->section); set_coursemodule_visible($this->cm->id, true); // retrieve the final info about this module. $info = get_fast_modinfo($this->course); if (!isset($info->cms[$this->cm->id])) { // The course module has not been properly created in the course - undo everything. delete_course_module($this->cm->id); throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name); } $mod = $info->cms[$this->cm->id]; $mod->groupmodelink = $this->cm->groupmodelink; $mod->groupmode = $this->cm->groupmode; // Trigger mod_created event with information about this module. $eventdata = new stdClass(); $eventdata->modulename = $mod->modname; $eventdata->name = $mod->name; $eventdata->cmid = $mod->id; $eventdata->courseid = $this->course->id; $eventdata->userid = $USER->id; events_trigger('mod_created', $eventdata); add_to_log($this->course->id, "course", "add mod", "../mod/{$mod->modname}/view.php?id={$mod->id}", "{$mod->modname} {$instanceid}"); add_to_log($this->course->id, $mod->modname, "add", "view.php?id={$mod->id}", "{$instanceid}", $mod->id); $this->send_response($mod); }
/** * Add course module. * * The function does not check user capabilities. * The function creates course module, module instance, add the module to the correct section. * It also trigger common action that need to be done after adding/updating a module. * * @param object $moduleinfo the moudle data * @param object $course the course of the module * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance() * @return object the updated module info */ function add_moduleinfo($moduleinfo, $course, $mform = null) { global $DB, $CFG; // Attempt to include module library before we make any changes to DB. include_modulelib($moduleinfo->modulename); $moduleinfo->course = $course->id; $moduleinfo = set_moduleinfo_defaults($moduleinfo); if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) { $moduleinfo->groupmode = 0; // Do not set groupmode. } // First add course_module record because we need the context. $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $moduleinfo->module; $newcm->instance = 0; // Not known yet, will be updated later (this is similar to restore code). $newcm->visible = $moduleinfo->visible; $newcm->visibleold = $moduleinfo->visible; if (isset($moduleinfo->cmidnumber)) { $newcm->idnumber = $moduleinfo->cmidnumber; } $newcm->groupmode = $moduleinfo->groupmode; $newcm->groupingid = $moduleinfo->groupingid; $completion = new completion_info($course); if ($completion->is_enabled()) { $newcm->completion = $moduleinfo->completion; $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber; $newcm->completionview = $moduleinfo->completionview; $newcm->completionexpected = $moduleinfo->completionexpected; } if (!empty($CFG->enableavailability)) { // This code is used both when submitting the form, which uses a long // name to avoid clashes, and by unit test code which uses the real // name in the table. $newcm->availability = null; if (property_exists($moduleinfo, 'availabilityconditionsjson')) { if ($moduleinfo->availabilityconditionsjson !== '') { $newcm->availability = $moduleinfo->availabilityconditionsjson; } } else { if (property_exists($moduleinfo, 'availability')) { $newcm->availability = $moduleinfo->availability; } } } if (isset($moduleinfo->showdescription)) { $newcm->showdescription = $moduleinfo->showdescription; } else { $newcm->showdescription = 0; } // From this point we make database changes, so start transaction. $transaction = $DB->start_delegated_transaction(); if (!($moduleinfo->coursemodule = add_course_module($newcm))) { print_error('cannotaddcoursemodule'); } if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) && isset($moduleinfo->introeditor)) { $introeditor = $moduleinfo->introeditor; unset($moduleinfo->introeditor); $moduleinfo->intro = $introeditor['text']; $moduleinfo->introformat = $introeditor['format']; } $addinstancefunction = $moduleinfo->modulename . "_add_instance"; try { $returnfromfunc = $addinstancefunction($moduleinfo, $mform); } catch (moodle_exception $e) { $returnfromfunc = $e; } if (!$returnfromfunc or !is_number($returnfromfunc)) { // Undo everything we can. This is not necessary for databases which // support transactions, but improves consistency for other databases. $modcontext = context_module::instance($moduleinfo->coursemodule); context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule); $DB->delete_records('course_modules', array('id' => $moduleinfo->coursemodule)); if ($e instanceof moodle_exception) { throw $e; } else { if (!is_number($returnfromfunc)) { print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section)); } else { print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename); } } } $moduleinfo->instance = $returnfromfunc; $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $moduleinfo->coursemodule)); // Update embedded links and save files. $modcontext = context_module::instance($moduleinfo->coursemodule); if (!empty($introeditor)) { $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $moduleinfo->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']); $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id' => $moduleinfo->instance)); } // Course_modules and course_sections each contain a reference to each other. // So we have to update one of them twice. $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section); // Trigger event based on the action we did. // Api create_from_cm expects modname and id property, and we don't want to modify $moduleinfo since we are returning it. $eventdata = clone $moduleinfo; $eventdata->modname = $eventdata->modulename; $eventdata->id = $eventdata->coursemodule; $event = \core\event\course_module_created::create_from_cm($eventdata, $modcontext); $event->trigger(); $moduleinfo = edit_module_post_actions($moduleinfo, $course); $transaction->allow_commit(); return $moduleinfo; }
/** * Given a full mod object with section and course already defined, adds this module to that section. * * This function is deprecated, please use {@link course_add_cm_to_section()} * Note that course_add_cm_to_section() also updates field course_modules.section and * calls rebuild_course_cache() * * @deprecated since 2.4 * * @param object $mod * @param int $beforemod An existing ID which we will insert the new module before * @return int The course_sections ID where the mod is inserted */ function add_mod_to_section($mod, $beforemod = null) { debugging('Function add_mod_to_section() is deprecated, please use course_add_cm_to_section()', DEBUG_DEVELOPER); global $DB; return course_add_cm_to_section($mod->course, $mod->coursemodule, $mod->section, $beforemod); }
function pearsondirect_create_lti($ltilink, $courseid) { global $DB, $CFG; require_once $CFG->dirroot . '/course/lib.php'; $lti = new stdClass(); $lti->course = $courseid; $lti->name = $ltilink->title; $lti->timecreated = time(); $lti->timemodified = $lti->timecreated; $lti->typeid = 0; $lti->toolurl = $ltilink->launchUrl; $lti->instructorchoicesendname = 1; $lti->instructorchoicesendemailaddr = 1; $strCustomParams = ''; $cps = $ltilink->customParameters; foreach ($cps as $cp) { $n = $cp->name; // @todo fix if ($n == 'target_function') { $n = 'targetId'; } $v = $cp->value; if ($strCustomParams == NULL) { $strCustomParams = ''; } $strCustomParams .= $n . '=' . $v . "\n"; } if ($strCustomParams != null) { $lti->instructorcustomparameters = $strCustomParams; } $lti->launchcontainer = 4; $lti->resourcekey = $CFG->pearson_key; $lti->password = $CFG->pearson_secret; $lti->debuglaunch = 0; $lti->showtitlelaunch = 0; $lti->showdescriptionlaunch = 0; $use_icons = $CFG->pearson_use_icons; if ($use_icons) { $lti->icon = $CFG->wwwroot . '/blocks/pearson/pix/icon.png'; } $lti->id = $DB->insert_record('lti', $lti); $cm = new stdClass(); $cm->course = $courseid; $cm->module = pearsondirect_get_lti_module(); $cm->instance = $lti->id; $cm->section = 0; $cm->idnumber = pearsondirect_construct_id_for_lti($ltilink->id, $courseid, $lti->id, 't'); $cm->added = time(); $cm->score = 0; $cm->indent = 0; $instructoronly = pearsondirect_is_instructor_link($ltilink); if ($instructoronly) { $cm->visible = 0; $cm->visibleold = 0; } else { $cm->visible = 1; $cm->visibleold = 1; } $cm->groupmode = 0; $cm->groupingid = 0; $cm->groupmembersonly = 0; $cm->completion = 0; $cm->completionview = 0; $cm->completionexpected = 0; $cm->showavailability = 0; $cm->showdescription = 0; $cm->coursemodule = add_course_module($cm); $sectionid = course_add_cm_to_section($cm->course, $cm->coursemodule, $cm->section, null); $DB->set_field("course_modules", "section", $sectionid, array("id" => $cm->coursemodule)); return $lti->id; }
$eq->intro = $equrl; $eq->introformat = FORMAT_HTML; $eq->url = $equrl; $eq->course = $courseid; $eq->modulename = 'equella'; $eq->module = $module->id; $eq->attachmentuuid = $attachmentuuid; $eq->mimetype = mimeinfo('type', $equrl); try { $moduleid = equella_add_instance($eq); } catch (Exception $ex) { throw new equella_exception('Failed to create EQUELLA resource.'); } $eq->instance = $moduleid; if (!($eq->coursemodule = add_course_module($eq))) { print_error('cannotaddcoursemodule'); } if (!($addedsectionid = course_add_cm_to_section($eq->course, $eq->coursemodule, 0))) { print_error('cannotaddcoursemoduletosection'); } if (!$DB->set_field('course_modules', 'section', $addedsectionid, array('id' => $eq->coursemodule))) { print_error('Could not update the course module with the correct section'); } set_coursemodule_visible($eq->coursemodule, true); } $courseurl = new moodle_url('/course/view.php', array('id' => $courseid)); redirect($courseurl); } echo $OUTPUT->header(); $form->display(); echo $OUTPUT->footer();
/** * Move the module object $mod to the specified $section * If $beforemod exists then that is the module * before which $modid should be inserted * All parameters are objects */ function moveto_module($mod, $section, $beforemod = NULL) { global $OUTPUT; /// Remove original module from original section if (!delete_mod_from_section($mod->id, $mod->section)) { echo $OUTPUT->notification("Could not delete module from existing section"); } // if moving to a hidden section then hide module if (!$section->visible && $mod->visible) { set_coursemodule_visible($mod->id, 0); } /// Add the module into the new section course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod); return true; }
/** * Given an object containing all the necessary data, * (defined by the form in mod.html) this function * will create a new instance and return the id number * of the new instance. * * @param object $instance An object from the form in mod.html * @return int The id of the newly inserted basiclti record **/ function pearson_add_instance($pd, $mform) { global $DB, $CFG; require_once $CFG->dirroot . '/mod/lti/locallib.php'; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/blocks/pearson/locallib.php'; require_once $CFG->dirroot . '/lib/modinfolib.php'; $pd_c = clean_param($pd->pdcourseid, PARAM_INT); $pd_s = clean_param($pd->pdsection, PARAM_INT); $launchpresentation = 4; if (isset($pd->inframe)) { $launchpresentation = 2; } $templatelink = $DB->get_record('lti_types', array('id' => $pd->selectedlink), '*', MUST_EXIST); $ltilink = new stdClass(); $ltilink->course = $templatelink->course; $linkname = ''; if (isset($pd->mediaurltitle) && trim($pd->mediaurltitle) !== '') { $linkname = clean_param($pd->mediaurltitle, PARAM_TEXT); } else { if (isset($pd->linktitle) && trim($pd->linktitle) !== '') { $linkname = clean_param($pd->linktitle, PARAM_TEXT); } else { $linkname = $templatelink->name; } } $ltilink->name = format_string($linkname); $ltilink->timecreated = time(); $ltilink->timemodified = $ltilink->timecreated; $ltilink->typeid = 0; $ltilink->toolurl = $templatelink->baseurl; $ltilink->instructorchoicesendname = 1; $ltilink->instructorchoicesendemailaddr = 1; $strCustomParams = $DB->get_field('lti_types_config', 'value', array('typeid' => $templatelink->id, 'name' => 'customparameters'), IGNORE_MISSING); if ($strCustomParams == null) { $strCustomParams = ''; } $pd_customparams = clean_param($pd->customparams, PARAM_TEXT); if (isset($pd_customparams) && trim($pd_customparams) !== '') { if (strpos($pd_customparams, ',') !== false) { $cp_array = explode(',', $pd_customparams); foreach ($cp_array as $cpa) { $kv_array = explode('=', $cpa); $key = $kv_array[0]; $length = strlen('custom_'); if (substr($key, 0, $length) === 'custom_') { $key = substr($key, $length, strlen($key)); } $strCustomParams .= $key . '=' . $kv_array[1] . "\n"; } } else { $kv_array = explode('=', $pd_customparams); $key = $kv_array[0]; $length = strlen('custom_'); if (substr($key, 0, $length) === 'custom_') { $key = substr($key, $length, strlen($key)); } $strCustomParams .= $key . '=' . $kv_array[1] . "\n"; } } $pd_mediaurl = clean_param($pd->mediaurl, PARAM_URL); if (isset($pd_mediaurl) && trim($pd_mediaurl) !== '') { $strCustomParams .= 'genericmediaurl=' . $pd_mediaurl . "\n"; } if ($strCustomParams != null) { $ltilink->instructorcustomparameters = $strCustomParams; } $ltilink->launchcontainer = $launchpresentation; $ltilink->resourcekey = $CFG->pearson_key; $ltilink->password = $CFG->pearson_secret; $ltilink->debuglaunch = 0; $ltilink->showtitlelaunch = 0; $ltilink->showdescriptionlaunch = 0; $use_icons = $CFG->pearson_use_icons; if ($use_icons) { $ltilink->icon = $CFG->wwwroot . '/blocks/pearson/pix/icon.png'; } $ltilink->id = $DB->insert_record('lti', $ltilink); $cm = new stdClass(); $cm->course = $pd_c; $cm->module = pearsondirect_get_lti_module(); $cm->instance = $ltilink->id; $cm->section = $pd_s; $cm->idnumber = $templatelink->tooldomain . ':' . $ltilink->id . ':c'; $cm->added = time(); $cm->score = 0; $cm->indent = 0; $cm->visible = 1; $cm->visibleold = 1; $cm->groupmode = 0; $cm->groupingid = 0; $cm->groupmembersonly = 0; $cm->completion = 0; $cm->completionview = 0; $cm->completionexpected = 0; $cm->showavailability = 0; $cm->showdescription = 0; $cm->coursemodule = add_course_module($cm); $sectionid = course_add_cm_to_section($cm->course, $cm->coursemodule, $cm->section, null); $DB->set_field("course_modules", "section", $sectionid, array("id" => $cm->coursemodule)); rebuild_course_cache($pd_c); redirect("{$CFG->wwwroot}/course/view.php?id={$pd_c}#section-" . $pd_s); return $ltilink->id; }
static function add($modulename, $courseid, $atstart = 0, $ifexists = 0, $moduleparams = null, $section = 0, $visible = 0, $permissionsoverrides = array()) { global $DB, $CFG; // Check module type exists if (!($module = $DB->get_record('modules', array('name' => $modulename), '*'))) { return array(false, 'Module type not found'); } // Check course exists if (!($course = $DB->get_record('course', array('id' => $courseid), '*'))) { return array(false, 'Course not found'); } // Check course is correct format if ($course->format == 'site' || $course->format == 'social' || $course->format == 'scorm') { return array(false, 'Course is not a weekly or topic type, skipping'); } // Check user has required permissions to add course module $requiredcapabilities = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:override'); if (!has_all_capabilities($requiredcapabilities, context_course::instance($courseid))) { return array(false, 'Insufficient permissions to add course module'); } // Set course module initial data $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $module->id; $newcm->modulename = $module->name; $newcm->section = 0; $newcm->instance = 0; $newcm->visible = $visible; $newcm->groupmode = 0; // No groups $newcm->groupingid = 0; $newcm->groupmembersonly = 0; $newcm->showdescription = 0; $newcm->cmidnumber = ''; // Check whether module plugin class exists for selected module otherwise use generic module plugin $modulepluginclass = 'module_plugin_' . $modulename; $modulepluginfilename = 'moduleplugins/' . $modulepluginclass . '.php'; if (file_exists($modulepluginfilename)) { include_once $modulepluginfilename; $moduleplugin = new $modulepluginclass($moduleparams, $newcm); } else { include_once 'moduleplugins/module_plugin_generic.php'; $moduleplugin = new module_plugin_generic($moduleparams, $newcm, $modulename); $modulepluginclass = 'module_plugin_generic'; } // Check that module params XML is valid if (!$modulepluginclass::check_params_xml($moduleparams)) { return array(false, 'Module parameters not valid'); } $newcm->name = (string) $moduleparams->title; $newcm->intro = (string) $moduleparams->description; $newcm->introformat = 1; // Check whether module instance with title already exists $sql = 'SELECT COUNT(*) AS count FROM {course_sections} AS cs JOIN {course_modules} AS cm ON cm.section = cs.id JOIN {modules} AS ms ON ms.id = cm.module JOIN {' . $module->name . '} AS m ON m.id = cm.instance WHERE cs.course = ? AND cs.section = ? AND m.name = ? AND ms.name = ?'; $instances = $DB->get_record_sql($sql, array($course->id, $section, $newcm->name, $module->name)); if ($instances->count > 0) { if ($ifexists == 0) { return array(false, 'Already exists, skipping'); } else { if ($ifexists == 2) { if (!self::delete($modulename, $course, $newcm->name, $section)) { return array(false, 'Error removing existing module instance(s), could not replace'); } } } } // Create course module if (!($newcm->coursemodule = add_course_module($newcm))) { return array(false, 'Could not create course module'); } // Create module instance $ret = $moduleplugin->create_instance(); if (!$ret[0]) { return $ret; } // Update course_modules DB row to reference new module instance $DB->set_field('course_modules', 'instance', $newcm->instance, array('id' => $newcm->coursemodule)); // course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. if ($atstart) { if (!($section = $DB->get_record('course_sections', array('course' => $newcm->course, 'section' => $newcm->section)))) { // Section doesn't already exist so create it in normal manner // $sectionid = add_mod_to_section($newcm); JAC change 20160809 // requires course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) $sectionid = course_add_cm_to_section($newcm->course, $newcm->coursemodule, $newcm->section); } else { // Moodle's add_mod_to_section add before functionality is broken so we have to do this here $section->sequence = trim($section->sequence); if (empty($section->sequence)) { $newsequence = "{$newcm->coursemodule}"; } else { $newsequence = "{$newcm->coursemodule},{$section->sequence}"; } $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id)); $sectionid = $section->id; } } else { // $sectionid = add_mod_to_section($newcm); JAC change 20160809 $sectionid = course_add_cm_to_section($newcm->course, $newcm->coursemodule, $newcm->section); } $DB->set_field('course_modules', 'section', $sectionid, array('id' => $newcm->coursemodule)); // Trigger post create actions $ret = $moduleplugin->post_create_setup(); if (!$ret[0]) { self::delete($modulename, $course, $newcm->name, $section); return array(false, 'Error carrying out post creation setup. Error was: ' . $ret[1]); } // If $permissionsoverrides is not empty, override permissions of specified role capabilites if (count($permissionsoverrides) > 0) { $modcontext = context_module::instance($newcm->coursemodule); foreach ($permissionsoverrides as $permissionoverride) { $permission = $permissionoverride[2] == 'allow' ? CAP_ALLOW : CAP_PREVENT; role_change_permission($permissionoverride[0], $modcontext, $permissionoverride[1], $permission); } } // Trigger mod_created event with information about this module. $eventname = 'mod_created'; $eventdata = new stdClass(); $eventdata->modulename = $module->name; $eventdata->name = $newcm->name; $eventdata->cmid = $newcm->coursemodule; $eventdata->courseid = $course->id; $eventdata->userid = 0; events_trigger($eventname, $eventdata); // Rebuild course cache rebuild_course_cache($course->id); return array(true, ''); }
public function add_file($section, $name, $path, $display = 0) { global $DB, $CFG, $USER; $section = (int) $section; $display = (int) $display; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/mod/resource/lib.php'; require_once $CFG->dirroot . '/mod/resource/locallib.php'; $params = self::validate_parameters(self::add_file_parameters(), array('section' => $section, 'name' => $name, 'path' => $path, 'display' => $display)); $section = $DB->get_record('course_sections', array('id' => $section), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $section->course), '*', MUST_EXIST); self::require_access($course->id); // Finally create the file item. // First add course_module record because we need the context. $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $DB->get_field('modules', 'id', array('name' => 'resource')); // Not known yet, will be updated later (this is similar to restore code). $newcm->instance = 0; $newcm->section = $params['section']; $newcm->visible = 1; $newcm->groupmode = 0; $newcm->groupingid = 0; $newcm->groupmembersonly = 0; if (!($coursemodule = add_course_module($newcm))) { throw new invalid_parameter_exception('Error creating course module'); } $config = get_config('resource'); $module = new stdClass(); $module->course = $course->id; $module->name = format_string($params['name']); $module->intro = '<p></p>'; $module->introformat = 1; $module->coursemodule = $coursemodule; if (!$display) { $module->display = $config->display; } else { $module->display = $display; } $module->popupwidth = $config->popupwidth; $module->popupheight = $config->popupheight; $module->printintro = $config->printintro; // 'Show size' support only from Moodle 2.3 / OU moodle April 2012. if (isset($config->showsize)) { $module->showsize = $config->showsize; $module->showtype = $config->showtype; } $module->filterfiles = $config->filterfiles; $module->section = $section->section; // Check $params['path'] and create files based on that and attach to $module->files // now check $path and obtain $filename and $filepath. $contextuser = context_user::instance($USER->id); $fs = get_file_storage(); $module->files = 0; file_prepare_draft_area($module->files, null, null, null, null); $fileinfo = array('contextid' => $contextuser->id, 'component' => 'user', 'filearea' => 'draft', 'itemid' => $module->files, 'filepath' => '/', 'filename' => basename($params['path']), 'timecreated' => time(), 'timemodified' => time(), 'mimetype' => mimeinfo('type', $path), 'userid' => $USER->id); if (strpos($params['path'], '://') === false) { // This is a path. if (!file_exists($params['path'])) { throw new invalid_parameter_exception('Error accessing filepath - file may not exist.'); } $fs->create_file_from_pathname($fileinfo, $params['path']); } else { // This is a URL - download the file first. $content = download_file_content($params['path']); if ($content === false) { throw new invalid_parameter_exception('Error accessing file - url may not exist.'); } $fs->create_file_from_string($fileinfo, $content); } $module->instance = resource_add_instance($module, array()); $DB->set_field('course_modules', 'instance', $module->instance, array('id' => $coursemodule)); course_add_cm_to_section($module->course, $coursemodule, $section->section); rebuild_course_cache($course->id, true); return array('id' => $coursemodule); }
function make_forumng($courseid, $starttime, $discussions, $posts, $readpercent, $readusers, &$userids, $subscribepercent, $ratingpercent) { global $DB; $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => 0), '*', MUST_EXIST); $transaction = $DB->start_delegated_transaction(); // Create course modules record $mod = new stdClass(); $mod->course = $courseid; $mod->module = $DB->get_field('modules', 'id', array('name' => 'forumng')); $mod->section = $section->section; // was $section->id; logical but incorrect! $mod->added = $starttime; $mod->visible = 1; // course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. // Note: This is unbelievable!!! $mod->section MUST BE section number (not id) // Adds course_module with section number, add_mod_to_section uses // section number (& course id) to get section id, which is returned // course module record then updated to replace section number by id!!! if (!($mod->coursemodule = add_course_module($mod))) { throw new Exception("Could not add a new course module"); } if (!($sectionid = course_add_cm_to_section($mod->course, $mod->coursemodule, $mod->section))) { throw new Exception("Could not add the new course module to that section"); } // Create forum object $forumng = new stdClass(); static $index = 0; $index++; $forumng->name = 'Perf test ' . date('Ymd H:j', $starttime) . ' ' . $index; $forumng->course = $courseid; $forumng->section = $section; $forumng->cmidnumber = $mod->coursemodule; if (!($forumng->id = forumng_add_instance($forumng))) { throw new dml_exception('Failed to add forum'); } // Mark cm object as owning it $updatemod = new stdClass(); $updatemod->id = $mod->coursemodule; $updatemod->instance = $forumng->id; $updatemod->section = $sectionid; $DB->update_record('course_modules', $updatemod); // Make it be random users included in the forum shuffle($userids); // OK, forum is created. Let's make discussions $forum = mod_forumng::get_from_id($forumng->id, mod_forumng::CLONE_DIRECT); $count = my_random($discussions); for ($i = 0; $i < $count; $i++) { make_discussion($forum, $posts, my_random_percentage($readpercent) ? $readusers : 0, $userids, $ratingpercent); } // Add subscribe users set_time_limit(200); for ($i = 0; $i < $readusers; $i++) { if (my_random_percentage($subscribepercent)) { $forum->subscribe($userids[$i]); } } $transaction->allow_commit(); }
/** * Create course module and link it to course * * Since 2.6 it is recommended to use function add_moduleinfo() to create a module. * * @deprecated since 2.6 * @see testing_module_generator::create_instance() * * @param integer $courseid * @param array $options section, visible * @return integer $cm instance id */ protected function precreate_course_module($courseid, array $options) { global $DB, $CFG; require_once "{$CFG->dirroot}/course/lib.php"; $modulename = $this->get_modulename(); $sectionnum = isset($options['section']) ? $options['section'] : 0; unset($options['section']); // Prevent confusion, it would be overridden later in course_add_cm_to_section() anyway. $cm = new stdClass(); $cm->course = $courseid; $cm->module = $DB->get_field('modules', 'id', array('name' => $modulename)); $cm->instance = 0; $cm->section = 0; $cm->idnumber = isset($options['idnumber']) ? $options['idnumber'] : 0; $cm->added = time(); $columns = $DB->get_columns('course_modules'); foreach ($options as $key => $value) { if ($key === 'id' or !isset($columns[$key])) { continue; } if (property_exists($cm, $key)) { continue; } $cm->{$key} = $value; } $cm->id = $DB->insert_record('course_modules', $cm); course_add_cm_to_section($courseid, $cm->id, $sectionnum); return $cm->id; }
// the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // 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/>. // Dodgy hack to setup the global blog instance (section not created yet on install). if (!isset($CFG->oublogsetup)) { if ($pbcm = get_coursemodule_from_instance('oublog', 1, SITEID, 1)) { $mod = new stdClass(); $mod->id = $pbcm->id; $mod->section = course_add_cm_to_section($pbcm->course, $pbcm->id, 1); $DB->update_record('course_modules', $mod); } set_config('oublogsetup', true); } $module = new stdClass(); require $CFG->dirroot . '/mod/oublog/version.php'; $settings->add(new admin_setting_heading('oublog_version', '', get_string('displayversion', 'oublog', $module->displayversion))); if (isset($CFG->maxbytes)) { // Default maximum size for attachments allowed per post per oublog. $settings->add(new admin_setting_configselect('mod_oublog/maxbytes', get_string('maxattachmentsize', 'oublog'), get_string('configmaxbytes', 'oublog'), 512000, get_max_upload_sizes($CFG->maxbytes))); } // Default number of attachments allowed per post in all oublogs. $settings->add(new admin_setting_configtext('mod_oublog/maxattachments', get_string('maxattachments', 'oublog'), get_string('configmaxattachments', 'oublog'), 9, PARAM_INT)); $settings->add(new admin_setting_configcheckbox('oublogallpostslogin', get_string('oublogallpostslogin', 'oublog'), get_string('oublogallpostslogin_desc', 'oublog'), 1)); $settings->add(new admin_setting_configtext('mod_oublog/globalusageexclude', get_string('globalusageexclude', 'oublog'), get_string('globalusageexclude_desc', 'oublog'), ''));
/** * Move the module object $mod to the specified $section * If $beforemod exists then that is the module * before which $modid should be inserted * All parameters are objects */ function moveto_module($mod, $section, $beforemod = NULL) { global $OUTPUT, $DB; /// Remove original module from original section if (!delete_mod_from_section($mod->id, $mod->section)) { echo $OUTPUT->notification("Could not delete module from existing section"); } // if moving to a hidden section then hide module if ($mod->section != $section->id) { if (!$section->visible && $mod->visible) { // Set this in the object because it is sent as a response to ajax calls. $mod->visible = 0; set_coursemodule_visible($mod->id, 0); // Set visibleold to 1 so module will be visible when section is made visible. $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id)); } if ($section->visible && !$mod->visible) { set_coursemodule_visible($mod->id, $mod->visibleold); // Set this in the object because it is sent as a response to ajax calls. $mod->visible = $mod->visibleold; } } /// Add the module into the new section course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod); return true; }
/** * Called after the mod has set itself up, to finish off any course module settings * (set instance id, add to correct section, set visibility, etc.) and send the response * * @param int $instanceid id returned by the mod when it was created */ protected function finish_setup_course_module($instanceid) { global $DB, $USER; if (!$instanceid) { // Something has gone wrong - undo everything we can. course_delete_module($this->cm->id); throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name); } // Note the section visibility $visible = get_fast_modinfo($this->course)->get_section_info($this->section)->visible; $DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm->id)); // Rebuild the course cache after update action rebuild_course_cache($this->course->id, true); $sectionid = course_add_cm_to_section($this->course, $this->cm->id, $this->section); set_coursemodule_visible($this->cm->id, $visible); if (!$visible) { $DB->set_field('course_modules', 'visibleold', 1, array('id' => $this->cm->id)); } // retrieve the final info about this module. $info = get_fast_modinfo($this->course); if (!isset($info->cms[$this->cm->id])) { // The course module has not been properly created in the course - undo everything. course_delete_module($this->cm->id); throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name); } $mod = $info->get_cm($this->cm->id); // Trigger course module created event. $event = \core\event\course_module_created::create(array('courseid' => $this->course->id, 'context' => context_module::instance($mod->id), 'objectid' => $mod->id, 'other' => array('modulename' => $mod->modname, 'name' => $mod->name, 'instanceid' => $instanceid))); $event->trigger(); add_to_log($this->course->id, $mod->modname, "add", "view.php?id={$mod->id}", "{$instanceid}", $mod->id); $this->send_response($mod); }
public static function move_item($user, $itemid, $courseid, $locationid) { global $DB, $USER; $params = self::validate_parameters(self::move_item_parameters(), array('user' => $user, 'itemid' => $itemid, 'courseid' => $courseid, 'locationid' => $locationid)); $item = $DB->get_record('equella', array('id' => $params['itemid']), '*', MUST_EXIST); self::check_modify_permissions($params['user'], $item->course); $cm = get_coursemodule_from_instance('equella', $item->id, $item->course, false, MUST_EXIST); $oldCourse = $cm->course; $newCourse = $params['courseid']; $newSection = $DB->get_record('course_sections', array('course' => $newCourse, 'section' => $params['locationid']), '*', MUST_EXIST); delete_mod_from_section($cm->id, $cm->section); $cm->section = $newSection->id; $cm->course = $newCourse; $item->course = $newCourse; $item->section = $newSection->section; $item->instance = $cm->instance; $item->cm = $cm->id; $success = $DB->update_record("course_modules", $cm); if ($success) { $success = equella_update_instance($item); if (!($sectionid = course_add_cm_to_section($newCourse, $cm->id, $newSection->section))) { print_error('cannotaddcoursemoduletosection'); return null; } if (class_exists('core\\event\\course_module_updated')) { $event = \core\event\course_module_updated::create_from_cm($cm); $event->trigger(); } else { $eventdata = new stdClass(); $eventdata->modulename = 'equella'; $eventdata->name = $item->name; $eventdata->cmid = $cm->id; $eventdata->courseid = $item->course; $eventdata->userid = $USER->id; events_trigger('mod_updated', $eventdata); add_to_log($item->course, "course", "update mod", "../mod/equella/view.php?id={$cm->id}", "equella {$item->instance}"); add_to_log($item->course, "equella", "update equella resource", "view.php?id={$cm->id}", "{$item->instance}", $cm->id); } rebuild_course_cache($oldCourse); rebuild_course_cache($newCourse); } return array('success' => $success); }
function RWSAAQuiz() { global $CFG; global $DB; global $RWSLB; global $RWSUID; RWSCMAuth(); RWSCRAuth(); RWSCMUSvc(); RWSCMMaint(); $r_pm = RWSGSOpt("courseid", PARAM_ALPHANUM); if ($r_pm === false || strlen($r_pm) == 0) { RWSSErr("2057"); } $r_cid = intval($r_pm); $r_crs = RWSCMUCourse($r_cid, true); $r_si = false; $r_pm = RWSGSOpt("sectionid", PARAM_ALPHANUM); if ($r_pm !== false && strlen($r_pm) > 0) { $r_si = intval($r_pm); } if ($r_si === false) { $r_sr = 0; } else { $r_sec = $DB->get_record("course_sections", array("id" => $r_si)); if ($r_sec === false) { RWSSErr("2071"); } if ($r_sec->course != $r_cid) { RWSSErr("2072"); } $r_sr = $r_sec->section; } $r_pm = RWSGSOpt("name", PARAM_TEXT); if ($r_pm === false || strlen($r_pm) == 0) { RWSSErr("2073"); } $r_qzn = trim(clean_text(strip_tags($r_pm, "<lang><span>"))); $r_sfl = RWSGSOpt("sfile", RWSPRF); if ($r_sfl === false) { $r_sn = RWSGSOpt("sname", PARAM_FILE); $r_sd = RWSGSOpt("sdata", PARAM_NOTAGS); $r_ecd = true; } else { $r_sn = $r_sfl->filename; $r_sd = $r_sfl->filedata; $r_ecd = false; } $r_imp = false; if ($r_sd !== false && strlen($r_sd) > 0) { if ($r_sn === false || strlen($r_sn) == 0) { RWSSErr("2075"); } $r_sn = clean_filename($r_sn); $r_imp = true; } $r_mr = $DB->get_record("modules", array("name" => "quiz")); if ($r_mr === false) { RWSSErr("2074"); } $r_qiz = new stdClass(); $r_qiz->name = $r_qzn; $r_qiz->section = $r_sr; $r_qiz->course = $r_cid; $r_qiz->coursemodule = 0; $r_qiz->instance = 0; $r_qiz->id = 0; $r_qiz->modulename = $r_mr->name; $r_qiz->module = $r_mr->id; $r_qiz->groupmembersonly = 0; if (respondusws_floatcompare($CFG->version, 2011120500.0, 2) >= 0) { $r_qiz->showdescription = 0; } $r_cpl = new completion_info($r_crs); if ($r_cpl->is_enabled()) { $r_qiz->completion = COMPLETION_TRACKING_NONE; $r_qiz->completionview = COMPLETION_VIEW_NOT_REQUIRED; $r_qiz->completiongradeitemnumber = null; $r_qiz->completionexpected = 0; } if ($CFG->enableavailability) { $r_qiz->availablefrom = 0; $r_qiz->availableuntil = 0; if ($r_qiz->availableuntil) { $r_qiz->availableuntil = strtotime("23:59:59", $r_qiz->availableuntil); } $r_qiz->showavailability = CONDITION_STUDENTVIEW_HIDE; } RWSSQDefs($r_qiz); if ($r_imp) { RWSIQSet($r_qiz, $r_sn, $r_sd, $r_ecd); } if (is_null($r_qiz->quizpassword) && !is_null($r_qiz->password)) { $r_qiz->quizpassword = $r_qiz->password; } $r_qzmi = add_course_module($r_qiz); if (!$r_qzmi) { RWSSErr("2077"); } $r_qiz->coursemodule = $r_qzmi; $r_insi = quiz_add_instance($r_qiz); if (!$r_insi || is_string($r_insi)) { RWSSErr("2076"); } $r_qiz->instance = $r_insi; if (respondusws_floatcompare($CFG->version, 2012120300, 2) >= 0) { $r_siu = course_add_cm_to_section($r_qiz->course, $r_qiz->coursemodule, $r_qiz->section); } else { $r_siu = add_mod_to_section($r_qiz); } if (!$r_siu) { RWSSErr("2078"); } if (respondusws_floatcompare($CFG->version, 2012120300, 2) < 0) { $DB->set_field("course_modules", "section", $r_siu, array("id" => $r_qzmi)); } if ($r_si !== false && $r_siu != $r_si) { RWSSErr("2078"); } RWSSLBSet($r_qiz); set_coursemodule_visible($r_qzmi, $r_qiz->visible); if (isset($r_qiz->cmidnumber)) { set_coursemodule_idnumber($r_qzmi, $r_qiz->cmidnumber); } RWSUQGrades($r_qiz); if (respondusws_floatcompare($CFG->version, 2014051200, 2) >= 0) { $r_qiz->modname = $r_qiz->modulename; $r_qiz->id = $r_qiz->coursemodule; $r_evt = \core\event\course_module_created::create_from_cm($r_qiz); $r_evt->trigger(); } else { $r_evt = new stdClass(); $r_evt->modulename = $r_qiz->modulename; $r_evt->name = $r_qiz->name; $r_evt->cmid = $r_qiz->coursemodule; $r_evt->courseid = $r_qiz->course; $r_evt->userid = $RWSUID; events_trigger("mod_created", $r_evt); } rebuild_course_cache($r_cid); grade_regrade_final_grades($r_cid); RWSRHXml(); echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"; echo "<addquiz>\r\n"; echo "\t<name>"; echo utf8_encode(htmlspecialchars(trim($r_qiz->name))); echo "</name>\r\n"; echo "\t<id>"; echo utf8_encode(htmlspecialchars(trim($r_qzmi))); echo "</id>\r\n"; echo "\t<section_id>"; echo utf8_encode(htmlspecialchars(trim($r_siu))); echo "</section_id>\r\n"; echo "\t<writable>yes</writable>\r\n"; if ($RWSLB->mex || $RWSLB->bex) { if ($RWSLB->mok) { if ($RWSLB->perr) { echo "\t<service_warning>3003</service_warning>\r\n"; } } else { if ($RWSLB->bok) { if ($RWSLB->perr) { echo "\t<service_warning>3003</service_warning>\r\n"; } } else { echo "\t<service_warning>3001</service_warning>\r\n"; } } } else { echo "\t<service_warning>3000</service_warning>\r\n"; } echo "</addquiz>\r\n"; exit; }
/** * Purpose: add a Moodle page resource to a course * * @author Andrew Zoltay * date 2011-04-27 * @global $CFG - configuration settings for CACE * @global object $DB Moodle database object * @global $CACE_CFG - configuration settings for CACE * @param int $courseid * @param object $pagedata */ function cace_add_page_resource($course, $pagedata) { global $CFG, $DB, $CACE_CFG, $USER; require_once "{$CFG->dirroot}/mod/page/lib.php"; try { // Create a new course module for the page. $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $pagedata->module; $newcm->instance = 0; // Don't have this value yet, but will update later. $newcm->visible = $pagedata->visible; $newcm->groupmode = $pagedata->groupmode; $newcm->groupingid = $pagedata->groupingid; $newcm->groupmembersonly = $pagedata->groupmembersonly; $pagedata->coursemodule = add_course_module($newcm); // This is lame, but need to create a dummy object for page_add_instance() // useless $mform parameter that isn't used in the function. $dummyform = new stdClass(); // Create the page instance. $pageid = page_add_instance($pagedata, $dummyform); $pagedata->instance = $pageid; // Update course_modules table with new instance. $DB->set_field('course_modules', 'instance', $pageid, array('id' => $pagedata->coursemodule)); // Add the module to the correct section of the course // course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. $sectionid = course_add_cm_to_section($pagedata->course, $pagedata->coursemodule, $pagedata->section); $DB->set_field('course_modules', 'section', $sectionid, array('id' => $pagedata->coursemodule)); set_coursemodule_visible($pagedata->coursemodule, $pagedata->visible); // Trigger mod_created event with information about the new module. // Use the new events system to log the creation of a resource. $eventdata = clone $pagedata; $eventdata->modname = $pagedata->modulename; $eventdata->name = $pagedata->name; $eventdata->id = $pagedata->coursemodule; $eventdata->courseid = $course->id; $eventdata->userid = $CACE_CFG->admin_user; // Use Admin account for event data. $event = \core\event\course_module_created::create_from_cm($eventdata); $event->trigger(); return true; } catch (Exception $e) { return false; } }
/** * Creates a copy of the emarking in the database. * * @param unknown $original_emarking * @return boolean|multitype:unknown NULL Ambigous <boolean, number> */ function emarking_copy_to_cm($original_emarking) { require_once $CFG->dirroot . "/course/lib.php"; require_once $CFG->dirroot . "/mod/emarking/mod_form.php"; $emarkingmod = $DB->get_record('modules', array('name' => 'emarking')); $emarking = new stdClass(); $emarking = $original_emarking; $emarking->id = null; $emarking->id = emarking_add_instance($emarking); // Add coursemodule $mod = new stdClass(); $mod->course = $emarking->course; $mod->module = $emarkingmod->id; $mod->instance = $emarking->id; $mod->section = 0; $mod->visible = 0; // Hide the forum $mod->visibleold = 0; // Hide the forum $mod->groupmode = 0; $mod->grade = 100; if (!($cmid = add_course_module($mod))) { return false; } $sectionid = course_add_cm_to_section($mod->course, $cmid, 0); return array($emarking->id, $cmid, $sectionid); }
/** * Move the module object $mod to the specified $section * If $beforemod exists then that is the module * before which $modid should be inserted * * @param stdClass|cm_info $mod * @param stdClass|section_info $section * @param int|stdClass $beforemod id or object with field id corresponding to the module * before which the module needs to be included. Null for inserting in the * end of the section * @return int new value for module visibility (0 or 1) */ function moveto_module($mod, $section, $beforemod = NULL) { global $OUTPUT, $DB; // Current module visibility state - return value of this function. $modvisible = $mod->visible; // Remove original module from original section. if (!delete_mod_from_section($mod->id, $mod->section)) { echo $OUTPUT->notification("Could not delete module from existing section"); } // If moving to a hidden section then hide module. if ($mod->section != $section->id) { if (!$section->visible && $mod->visible) { // Module was visible but must become hidden after moving to hidden section. $modvisible = 0; set_coursemodule_visible($mod->id, 0); // Set visibleold to 1 so module will be visible when section is made visible. $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id)); } if ($section->visible && !$mod->visible) { // Hidden module was moved to the visible section, restore the module visibility from visibleold. set_coursemodule_visible($mod->id, $mod->visibleold); $modvisible = $mod->visibleold; } } // Add the module into the new section. course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod); return $modvisible; }
/** * Add course module. * * The function does not check user capabilities. * The function creates course module, module instance, add the module to the correct section. * It also trigger common action that need to be done after adding/updating a module. * * @param object $moduleinfo the moudle data * @param object $course the course of the module * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance() * @return object the updated module info */ function local_ltiprovider_add_moduleinfo($moduleinfo, $course, $mform = null) { global $DB, $CFG; $moduleinfo->course = $course->id; $moduleinfo = local_ltiprovider_set_moduleinfo_defaults($moduleinfo); if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) { $moduleinfo->groupmode = 0; // Do not set groupmode. } if (!course_allowed_module($course, $moduleinfo->modulename)) { print_error('moduledisable', '', '', $moduleinfo->modulename); } // First add course_module record because we need the context. $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $moduleinfo->module; $newcm->instance = 0; // Not known yet, will be updated later (this is similar to restore code). $newcm->visible = $moduleinfo->visible; $newcm->visibleold = $moduleinfo->visible; $newcm->groupmode = $moduleinfo->groupmode; $newcm->groupingid = $moduleinfo->groupingid; $newcm->groupmembersonly = $moduleinfo->groupmembersonly; $completion = new completion_info($course); if ($completion->is_enabled()) { $newcm->completion = $moduleinfo->completion; $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber; $newcm->completionview = $moduleinfo->completionview; $newcm->completionexpected = $moduleinfo->completionexpected; } if (!empty($CFG->enableavailability)) { $newcm->availablefrom = $moduleinfo->availablefrom; $newcm->availableuntil = $moduleinfo->availableuntil; $newcm->showavailability = $moduleinfo->showavailability; } if (isset($moduleinfo->showdescription)) { $newcm->showdescription = $moduleinfo->showdescription; } else { $newcm->showdescription = 0; } if (!($moduleinfo->coursemodule = add_course_module($newcm))) { print_error('cannotaddcoursemodule'); } if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) { $introeditor = $moduleinfo->introeditor; unset($moduleinfo->introeditor); $moduleinfo->intro = $introeditor['text']; $moduleinfo->introformat = $introeditor['format']; } $addinstancefunction = $moduleinfo->modulename . "_add_instance"; $returnfromfunc = $addinstancefunction($moduleinfo, $mform); if (!$returnfromfunc or !is_number($returnfromfunc)) { // Undo everything we can. $modcontext = context_module::instance($moduleinfo->coursemodule); delete_context(CONTEXT_MODULE, $moduleinfo->coursemodule); $DB->delete_records('course_modules', array('id' => $moduleinfo->coursemodule)); if (!is_number($returnfromfunc)) { print_error('invalidfunction', '', course_get_url($course, $cw->section)); } else { print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $moduleinfo->modulename); } } $moduleinfo->instance = $returnfromfunc; $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $moduleinfo->coursemodule)); // Update embedded links and save files. $modcontext = context_module::instance($moduleinfo->coursemodule); if (!empty($introeditor)) { $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $moduleinfo->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']); $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id' => $moduleinfo->instance)); } // Course_modules and course_sections each contain a reference to each other. // So we have to update one of them twice. $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section); // Make sure visibility is set correctly (in particular in calendar). // Note: allow them to set it even without moodle/course:activityvisibility. set_coursemodule_visible($moduleinfo->coursemodule, $moduleinfo->visible); if (isset($moduleinfo->cmidnumber)) { // Label. // Set cm idnumber - uniqueness is already verified by form validation. set_coursemodule_idnumber($moduleinfo->coursemodule, $moduleinfo->cmidnumber); } // Set up conditions. if ($CFG->enableavailability) { condition_info::update_cm_from_form((object) array('id' => $moduleinfo->coursemodule), $moduleinfo, false); } $eventname = 'mod_created'; add_to_log($course->id, "course", "add mod", "../mod/{$moduleinfo->modulename}/view.php?id={$moduleinfo->coursemodule}", "{$moduleinfo->modulename} {$moduleinfo->instance}"); add_to_log($course->id, $moduleinfo->modulename, "add", "view.php?id={$moduleinfo->coursemodule}", "{$moduleinfo->instance}", $moduleinfo->coursemodule); $moduleinfo = local_ltiprovider_edit_module_post_actions($moduleinfo, $course, 'mod_created'); return $moduleinfo; }
/** * Create a duplicate course module record so we can create the upgraded * setask module alongside the old setaskment module. * * @param stdClass $cm The old course module record * @param int $moduleid The id of the new setask module * @param int $newinstanceid The id of the new instance of the setask module * @return mixed stdClass|bool The new course module record or FALSE */ private function duplicate_course_module(stdClass $cm, $moduleid, $newinstanceid) { global $DB, $CFG; $newcm = new stdClass(); $newcm->course = $cm->course; $newcm->module = $moduleid; $newcm->instance = $newinstanceid; $newcm->visible = $cm->visible; $newcm->section = $cm->section; $newcm->score = $cm->score; $newcm->indent = $cm->indent; $newcm->groupmode = $cm->groupmode; $newcm->groupingid = $cm->groupingid; $newcm->completion = $cm->completion; $newcm->completiongradeitemnumber = $cm->completiongradeitemnumber; $newcm->completionview = $cm->completionview; $newcm->completionexpected = $cm->completionexpected; if (!empty($CFG->enableavailability)) { $newcm->availability = $cm->availability; } $newcm->showdescription = $cm->showdescription; $newcmid = add_course_module($newcm); $newcm = get_coursemodule_from_id('', $newcmid, $cm->course); if (!$newcm) { return false; } $section = $DB->get_record("course_sections", array("id" => $newcm->section)); if (!$section) { return false; } $newcm->section = course_add_cm_to_section($newcm->course, $newcm->id, $section->section, $cm->id); // Make sure visibility is set correctly (in particular in calendar). // Note: Allow them to set it even without moodle/course:activityvisibility. set_coursemodule_visible($newcm->id, $newcm->visible); return $newcm; }
/** * Add course module. * * The function does not check user capabilities. * The function creates course module, module instance, add the module to the correct section. * It also trigger common action that need to be done after adding/updating a module. * * @param object $moduleinfo the moudle data * @param object $course the course of the module * @param object $mform this is required by an existing hack to deal with files during MODULENAME_add_instance() * @return object the updated module info */ function add_moduleinfo($moduleinfo, $course, $mform = null) { global $DB, $CFG; // Attempt to include module library before we make any changes to DB. include_modulelib($moduleinfo->modulename); $moduleinfo->course = $course->id; $moduleinfo = set_moduleinfo_defaults($moduleinfo); if (!empty($course->groupmodeforce) or !isset($moduleinfo->groupmode)) { $moduleinfo->groupmode = 0; // Do not set groupmode. } // First add course_module record because we need the context. $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $moduleinfo->module; $newcm->instance = 0; // Not known yet, will be updated later (this is similar to restore code). $newcm->visible = $moduleinfo->visible; $newcm->visibleold = $moduleinfo->visible; if (isset($moduleinfo->cmidnumber)) { $newcm->idnumber = $moduleinfo->cmidnumber; } $newcm->groupmode = $moduleinfo->groupmode; $newcm->groupingid = $moduleinfo->groupingid; $newcm->groupmembersonly = $moduleinfo->groupmembersonly; $completion = new completion_info($course); if ($completion->is_enabled()) { $newcm->completion = $moduleinfo->completion; $newcm->completiongradeitemnumber = $moduleinfo->completiongradeitemnumber; $newcm->completionview = $moduleinfo->completionview; $newcm->completionexpected = $moduleinfo->completionexpected; } if (!empty($CFG->enableavailability)) { $newcm->availablefrom = $moduleinfo->availablefrom; $newcm->availableuntil = $moduleinfo->availableuntil; $newcm->showavailability = $moduleinfo->showavailability; } if (isset($moduleinfo->showdescription)) { $newcm->showdescription = $moduleinfo->showdescription; } else { $newcm->showdescription = 0; } if (!($moduleinfo->coursemodule = add_course_module($newcm))) { print_error('cannotaddcoursemodule'); } if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true) && isset($moduleinfo->introeditor)) { $introeditor = $moduleinfo->introeditor; unset($moduleinfo->introeditor); $moduleinfo->intro = $introeditor['text']; $moduleinfo->introformat = $introeditor['format']; } $addinstancefunction = $moduleinfo->modulename . "_add_instance"; $returnfromfunc = $addinstancefunction($moduleinfo, $mform); if (!$returnfromfunc or !is_number($returnfromfunc)) { // Undo everything we can. $modcontext = context_module::instance($moduleinfo->coursemodule); context_helper::delete_instance(CONTEXT_MODULE, $moduleinfo->coursemodule); $DB->delete_records('course_modules', array('id' => $moduleinfo->coursemodule)); if (!is_number($returnfromfunc)) { print_error('invalidfunction', '', course_get_url($course, $moduleinfo->section)); } else { print_error('cannotaddnewmodule', '', course_get_url($course, $moduleinfo->section), $moduleinfo->modulename); } } $moduleinfo->instance = $returnfromfunc; $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $moduleinfo->coursemodule)); // Update embedded links and save files. $modcontext = context_module::instance($moduleinfo->coursemodule); if (!empty($introeditor)) { $moduleinfo->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $moduleinfo->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']); $DB->set_field($moduleinfo->modulename, 'intro', $moduleinfo->intro, array('id' => $moduleinfo->instance)); } // Course_modules and course_sections each contain a reference to each other. // So we have to update one of them twice. $sectionid = course_add_cm_to_section($course, $moduleinfo->coursemodule, $moduleinfo->section); // Set up conditions. if ($CFG->enableavailability) { condition_info::update_cm_from_form((object) array('id' => $moduleinfo->coursemodule), $moduleinfo, false); } // Trigger event based on the action we did. $event = \core\event\course_module_created::create(array('courseid' => $course->id, 'context' => $modcontext, 'objectid' => $moduleinfo->coursemodule, 'other' => array('modulename' => $moduleinfo->modulename, 'name' => $moduleinfo->name, 'instanceid' => $moduleinfo->instance))); $event->trigger(); add_to_log($course->id, $moduleinfo->modulename, "add", "view.php?id={$moduleinfo->coursemodule}", "{$moduleinfo->instance}", $moduleinfo->coursemodule); $moduleinfo = edit_module_post_actions($moduleinfo, $course); return $moduleinfo; }
/** * @global object * @global object * @param int $courseid * @param string $type */ function forum_get_course_forum($courseid, $type) { // How to set up special 1-per-course forums global $CFG, $DB, $OUTPUT, $USER; if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) { // There should always only be ONE, but with the right combination of // errors there might be more. In this case, just return the oldest one (lowest ID). foreach ($forums as $forum) { return $forum; // ie the first one } } // Doesn't exist, so create one now. $forum = new stdClass(); $forum->course = $courseid; $forum->type = "{$type}"; if (!empty($USER->htmleditor)) { $forum->introformat = $USER->htmleditor; } switch ($forum->type) { case "news": $forum->name = get_string("namenews", "forum"); $forum->intro = get_string("intronews", "forum"); $forum->forcesubscribe = FORUM_FORCESUBSCRIBE; $forum->assessed = 0; if ($courseid == SITEID) { $forum->name = get_string("sitenews"); $forum->forcesubscribe = 0; } break; case "social": $forum->name = get_string("namesocial", "forum"); $forum->intro = get_string("introsocial", "forum"); $forum->assessed = 0; $forum->forcesubscribe = 0; break; case "blog": $forum->name = get_string('blogforum', 'forum'); $forum->intro = get_string('introblog', 'forum'); $forum->assessed = 0; $forum->forcesubscribe = 0; break; default: echo $OUTPUT->notification("That forum type doesn't exist!"); return false; break; } $forum->timemodified = time(); $forum->id = $DB->insert_record("forum", $forum); if (!($module = $DB->get_record("modules", array("name" => "forum")))) { echo $OUTPUT->notification("Could not find forum module!!"); return false; } $mod = new stdClass(); $mod->course = $courseid; $mod->module = $module->id; $mod->instance = $forum->id; $mod->section = 0; include_once "{$CFG->dirroot}/course/lib.php"; if (!($mod->coursemodule = add_course_module($mod))) { echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'"); return false; } $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0); return $DB->get_record("forum", array("id" => "{$forum->id}")); }
// Add coursemodule $mod = new stdClass(); $mod->course = $emarking->course; $mod->module = $emarkingmod->id; $mod->instance = $emarking->id; $mod->section = 0; $mod->visible = 0; // Hide the forum $mod->visibleold = 0; // Hide the forum $mod->groupmode = 0; $mod->grade = 100; if (!($cmid = add_course_module($mod))) { emarking_json_error('cannotcreateinstanceforteacher'); } $sectionid = course_add_cm_to_section($mod->course, $cmid, 0); $emarkingid = $emarking->id; } if (!($emarking = $DB->get_record('emarking', array('id' => $emarkingid)))) { emarking_json_error('Invalid emarking id'); } if (!($cm = get_coursemodule_from_instance('emarking', $emarking->id, $course->id))) { emarking_json_error('Invalid course module'); } if (count($_FILES) < 1 || !is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) { emarking_json_error('You must upload a file'); } $extension = strtolower(substr($_FILES['uploadedfile']['name'], strrpos($_FILES['uploadedfile']['name'], "."), strlen($_FILES['uploadedfile']['name']) - strrpos($_FILES['uploadedfile']['name'], "."))); if ($extension !== '.zip') { emarking_json_error('Invalid extension file ' . $extension . ' in ' . $_FILES['uploadedfile']['tmp_name'] . '. Only zip files are allowed'); }
/** * Converts a forum to use the Roles System * * @global object * @global object * @param object $forum a forum object with the same attributes as a record * from the forum database table * @param int $forummodid the id of the forum module, from the modules table * @param array $teacherroles array of roles that have archetype teacher * @param array $studentroles array of roles that have archetype student * @param array $guestroles array of roles that have archetype guest * @param int $cmid the course_module id for this forum instance * @return boolean forum was converted or not */ function forum_convert_to_roles($forum, $forummodid, $teacherroles=array(), $studentroles=array(), $guestroles=array(), $cmid=NULL) { global $CFG, $DB, $OUTPUT; if (!isset($forum->open) && !isset($forum->assesspublic)) { // We assume that this forum has already been converted to use the // Roles System. Columns forum.open and forum.assesspublic get dropped // once the forum module has been upgraded to use Roles. return false; } if ($forum->type == 'teacher') { // Teacher forums should be converted to normal forums that // use the Roles System to implement the old behavior. // Note: // Seems that teacher forums were never backed up in 1.6 since they // didn't have an entry in the course_modules table. require_once($CFG->dirroot.'/course/lib.php'); if ($DB->count_records('forum_discussions', array('forum' => $forum->id)) == 0) { // Delete empty teacher forums. $DB->delete_records('forum', array('id' => $forum->id)); } else { // Create a course module for the forum and assign it to // section 0 in the course. $mod = new stdClass(); $mod->course = $forum->course; $mod->module = $forummodid; $mod->instance = $forum->id; $mod->section = 0; $mod->visible = 0; // Hide the forum $mod->visibleold = 0; // Hide the forum $mod->groupmode = 0; if (!$cmid = add_course_module($mod)) { print_error('cannotcreateinstanceforteacher', 'forum'); } else { $sectionid = course_add_cm_to_section($forum->course, $mod->coursemodule, 0); } // Change the forum type to general. $forum->type = 'general'; $DB->update_record('forum', $forum); $context = context_module::instance($cmid); // Create overrides for default student and guest roles (prevent). foreach ($studentroles as $studentrole) { assign_capability('mod/forum:viewdiscussion', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:viewhiddentimedposts', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:replypost', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:viewrating', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:viewanyrating', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:rate', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:createattachment', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:deleteownpost', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:deleteanypost', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:splitdiscussions', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:movediscussions', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:editanypost', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:viewqandawithoutposting', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:viewsubscribers', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:managesubscriptions', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:postwithoutthrottling', CAP_PREVENT, $studentrole->id, $context->id); } foreach ($guestroles as $guestrole) { assign_capability('mod/forum:viewdiscussion', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:viewhiddentimedposts', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:replypost', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:viewrating', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:viewanyrating', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:rate', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:createattachment', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:deleteownpost', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:deleteanypost', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:splitdiscussions', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:movediscussions', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:editanypost', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:viewqandawithoutposting', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:viewsubscribers', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:managesubscriptions', CAP_PREVENT, $guestrole->id, $context->id); assign_capability('mod/forum:postwithoutthrottling', CAP_PREVENT, $guestrole->id, $context->id); } } } else { // Non-teacher forum. if (empty($cmid)) { // We were not given the course_module id. Try to find it. if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) { echo $OUTPUT->notification('Could not get the course module for the forum'); return false; } else { $cmid = $cm->id; } } $context = context_module::instance($cmid); // $forum->open defines what students can do: // 0 = No discussions, no replies // 1 = No discussions, but replies are allowed // 2 = Discussions and replies are allowed switch ($forum->open) { case 0: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:replypost', CAP_PREVENT, $studentrole->id, $context->id); } break; case 1: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:startdiscussion', CAP_PREVENT, $studentrole->id, $context->id); assign_capability('mod/forum:replypost', CAP_ALLOW, $studentrole->id, $context->id); } break; case 2: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:startdiscussion', CAP_ALLOW, $studentrole->id, $context->id); assign_capability('mod/forum:replypost', CAP_ALLOW, $studentrole->id, $context->id); } break; } // $forum->assessed defines whether forum rating is turned // on (1 or 2) and who can rate posts: // 1 = Everyone can rate posts // 2 = Only teachers can rate posts switch ($forum->assessed) { case 1: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:rate', CAP_ALLOW, $studentrole->id, $context->id); } foreach ($teacherroles as $teacherrole) { assign_capability('mod/forum:rate', CAP_ALLOW, $teacherrole->id, $context->id); } break; case 2: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:rate', CAP_PREVENT, $studentrole->id, $context->id); } foreach ($teacherroles as $teacherrole) { assign_capability('mod/forum:rate', CAP_ALLOW, $teacherrole->id, $context->id); } break; } // $forum->assesspublic defines whether students can see // everybody's ratings: // 0 = Students can only see their own ratings // 1 = Students can see everyone's ratings switch ($forum->assesspublic) { case 0: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:viewanyrating', CAP_PREVENT, $studentrole->id, $context->id); } foreach ($teacherroles as $teacherrole) { assign_capability('mod/forum:viewanyrating', CAP_ALLOW, $teacherrole->id, $context->id); } break; case 1: foreach ($studentroles as $studentrole) { assign_capability('mod/forum:viewanyrating', CAP_ALLOW, $studentrole->id, $context->id); } foreach ($teacherroles as $teacherrole) { assign_capability('mod/forum:viewanyrating', CAP_ALLOW, $teacherrole->id, $context->id); } break; } if (empty($cm)) { $cm = $DB->get_record('course_modules', array('id' => $cmid)); } // $cm->groupmode: // 0 - No groups // 1 - Separate groups // 2 - Visible groups switch ($cm->groupmode) { case 0: break; case 1: foreach ($studentroles as $studentrole) { assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id); } foreach ($teacherroles as $teacherrole) { assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id); } break; case 2: foreach ($studentroles as $studentrole) { assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id); } foreach ($teacherroles as $teacherrole) { assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id); } break; } } return true; }
public function create_skillsmanagement($userid, $testing_mode) { global $DB, $CFG; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; require_once $CFG->dirroot . '/blocks/exacomp/lib/lib.php'; $user = $DB->get_record('user', ['id' => $userid]); if (!$user) { throw new moodle_exception('user not found'); } /*CREATE COURSE CATEGORY*/ //check if course category has already been created $category_already_exists = false; $max_sort = 0; $categoryid = 0; $category_sortoder = 0; $categorycontext = 0; $categorycontextpath = ''; $course_categories = $DB->get_records('course_categories'); foreach ($course_categories as $category) { if (strcmp($category->name, 'Skillmanagement') == 0) { $category_already_exists = true; $categoryid = $category->id; $category_sortoder = $category->sortorder; $context = $DB->get_record('context', array('instanceid' => $categoryid, 'contextlevel' => 40)); $categorycontext = $context->id; $categorycontextpath = $context->path; } elseif ($category->sortorder > $max_sort) { $max_sort = $category->sortorder; } } //if not->create if (!$category_already_exists) { /*INSERT IN COURSE_CATEGORIES*/ $insert = new stdClass(); $insert->name = 'Skillmanagement'; $insert->description = '<p>Dieser Kursbereich wird für automatisch generierte Kurse von Skillmanagement verwendet.</p>'; $insert->descriptionformat = 1; $insert->sortorder = $max_sort + 10000; $insert->timemodified = time(); $insert->depth = 1; $insertedid = $DB->insert_record('course_categories', $insert); $inserted = $DB->get_record('course_categories', array('id' => $insertedid)); $categoryid = $inserted->id; $category_sortoder = $inserted->sortorder; $update = new stdClass(); $update->id = $inserted->id; $update->path = '/' . $inserted->id; $DB->update_record('course_categories', $update); /*INSERT IN CONTEXT*/ $insert = new stdClass(); $insert->contextlevel = 40; $insert->instanceid = $inserted->id; $insert->depth = 2; $insertedid = $DB->insert_record('context', $insert); $inserted = $DB->get_record('context', array('id' => $insertedid)); $categorycontext = $inserted->id; $categorycontextpath = '/1/' . $inserted->id; $update = new stdClass(); $update->id = $inserted->id; $update->path = '/1/' . $inserted->id; $DB->update_record('context', $update); } /*TESTED AND WORKING CORRECTLY TILL HERE*/ $user_course = $DB->get_record('course', ['shortname' => 'SKILLSMGMT-' . $user->id]); if (!$user_course) { $categorycourses = $DB->get_records_sql('SELECT * FROM {course} WHERE category=?', array($categoryid)); /*CREATE COURSE*/ //insert in course-table $insert = new stdClass(); $insert->category = $categoryid; $insert->sortorder = $category_sortoder + count($categorycourses) + 1; $insert->fullname = 'Skillsmanagement_' . $user->id . '_' . $user->lastname; $insert->shortname = 'SKILLSMGMT-' . $user->id; $insert->format = 'weeks'; $insert->summaryformat = 1; $insert->startdate = time(); $insert->timecreated = time(); $insert->timemodified = time(); $insert->cacherev = time(); $user_course = create_course($insert); /*CREATE EXABIS BLOCK INSTANCES IN COURSE*/ $page = new moodle_page(); $page->set_course($user_course); $page->blocks->add_region('side-post'); $page->blocks->add_block('exacomp', 'side-post', 4, false, 'course-view-*'); $page->blocks->add_block('exaport', 'side-post', 4, false, 'course-view-*'); $page->blocks->add_block('exastud', 'side-post', 4, false, 'course-view-*'); /*CREATE COURSE DESCRIPTION*/ $label = new stdClass(); $label->intro = get_string('course_description', 'auth_skillmanagement'); $label->intro .= html_writer::empty_tag('br'); $label->intro .= html_writer::empty_tag('img', array('src' => new moodle_url('/auth/skillmanagement/pix/intro.png'), 'alt' => 'intro')); $label->course = $user_course->id; $label->introformat = 1; $labelid = label_add_instance($label); /*CREATE COURSE MODULE*/ $label_module = $DB->get_record('modules', array('name' => 'label')); $section = $DB->get_record('course_sections', array('course' => $user_course->id, 'section' => 0)); $cm = new stdClass(); $cm->course = $user_course->id; $cm->module = $label_module->id; $cm->instance = $labelid; $cm->section = $section->id; $cm->added = time(); $cmid = $DB->insert_record('course_modules', $cm); course_add_cm_to_section($user_course->id, $cmid, 0); $course_context = context_course::instance($user_course->id); } $source = $DB->get_record(\block_exacomp\DB_DATASOURCES, ['source' => 'SKILLSMGMT-' . $user->id]); if (!$source) { // import new for this user \block_exacomp\data_importer::do_import_file(__DIR__ . '/skills_mgmt_' . ($user->lang == 'de' ? 'de' : 'en') . '.xml'); // last imported source $source = $DB->get_record_sql("SELECT * FROM {" . \block_exacomp\DB_DATASOURCES . "} ORDER BY id DESC LIMIT 1"); // change source $source->source = 'SKILLSMGMT-' . $user->id; $source->name = 'Skills Management for ' . fullname($user); $DB->update_record(\block_exacomp\DB_DATASOURCES, $source); } // last imported schooltypes $schooltype_ids = $DB->get_records_menu(\block_exacomp\DB_SCHOOLTYPES, ['source' => $source->id], null, 'sourceid AS id, id AS val'); block_exacomp_set_mdltype($schooltype_ids, $user_course->id); $subjects = block_exacomp_get_subjects_for_schooltype($user_course->id, 0); /* if ($user->lang == 'de') { $subjects = block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[72]) + block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[73]); } else { $subjects = block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[492]) + block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[493]); } */ $coursetopics = array(); foreach ($subjects as $subject) { $topics = block_exacomp_get_all_topics($subject->id); foreach ($topics as $topic) { $coursetopics[] = $topic->id; } } block_exacomp_set_coursetopics($user_course->id, $coursetopics); /*DELETE OTHER MODULES FROM COURSE*/ //delete module recent activity /*$recent_activity = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'recent_activity')); course_delete_module($recent_activity->id); $search_forum = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'search_forums')); course_delete_module($search_forum->id); $news_items = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'news_items')); course_delete_module($news_items->id); $calendar = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'calendar_upcoming')); course_delete_module($calendar->id); /*CREATE SECOND USER WITH SAME PW*/ $user_student = $DB->get_record('user', array('username' => 'employee_' . $user->username)); if (!$user_student) { $user_student = new stdClass(); $user_student->firstname = get_string('firstname', 'auth_skillmanagement'); $user_student->lastname = get_string('lastname', 'auth_skillmanagement'); $user_student->confirmed = 1; $user_student->password = '******'; // will be overwritten later $user_student->email = $user->email; $user_student->auth = 'skillmanagement'; $user_student->username = '******' . $user->username; $user_student->lang = $user->lang; $user_student->mnethostid = 1; $user_student->id = user_create_user($user_student, false, false); profile_save_data($user_student); } $DB->update_record('user', ['confirmed' => 1, 'password' => $user->password, 'id' => $user_student->id]); /* $DB->update_record('user', [ 'confirmed' => 1, // 'idnumber' => $user_student->id, // not sure why?!? connect student to teacher?!? 'id' => $user->id, ]); */ /*ENROL user_trainer AND user_trainee to $user_course */ $enrolment = array('roleid' => 3, 'userid' => $user->id, 'courseid' => $user_course->id, 'timestart' => time(), 'timeend' => 0, 'suspend' => 0); $enrol = enrol_get_plugin('manual'); $enrolinstances = enrol_get_instances($enrolment['courseid'], true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } if (empty($instance)) { $errorparams = new stdClass(); $errorparams->courseid = $enrolment['courseid']; throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams); } // Check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin). if (!$enrol->allow_enrol($instance)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams); } $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['suspend']); //enrol participant $enrolment = array('roleid' => 5, 'userid' => $user_student->id, 'courseid' => $user_course->id, 'timestart' => time(), 'timeend' => 0, 'suspend' => 0); $enrol = enrol_get_plugin('manual'); $enrolinstances = enrol_get_instances($enrolment['courseid'], true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } if (empty($instance)) { $errorparams = new stdClass(); $errorparams->courseid = $enrolment['courseid']; throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams); } // Check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin). if (!$enrol->allow_enrol($instance)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams); } $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['suspend']); // elove if (!$DB->record_exists(\block_exacomp\DB_EXTERNAL_TRAINERS, array('trainerid' => $user->id, 'studentid' => $user_student->id))) { $DB->insert_record(\block_exacomp\DB_EXTERNAL_TRAINERS, array('trainerid' => $user->id, 'studentid' => $user_student->id)); } }