function test_is_enabled() { global $CFG; // Config alone $CFG->enablecompletion = COMPLETION_DISABLED; $this->assertEquals(COMPLETION_DISABLED, completion_info::is_enabled_for_site()); $CFG->enablecompletion = COMPLETION_ENABLED; $this->assertEquals(COMPLETION_ENABLED, completion_info::is_enabled_for_site()); // Course $course = (object)array('id' =>13); $c = new completion_info($course); $course->enablecompletion = COMPLETION_DISABLED; $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled()); $course->enablecompletion = COMPLETION_ENABLED; $this->assertEquals(COMPLETION_ENABLED, $c->is_enabled()); $CFG->enablecompletion = COMPLETION_DISABLED; $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled()); // Course and CM $cm = new stdClass(); $cm->completion = COMPLETION_TRACKING_MANUAL; $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled($cm)); $CFG->enablecompletion = COMPLETION_ENABLED; $course->enablecompletion = COMPLETION_DISABLED; $this->assertEquals(COMPLETION_DISABLED, $c->is_enabled($cm)); $course->enablecompletion = COMPLETION_ENABLED; $this->assertEquals(COMPLETION_TRACKING_MANUAL, $c->is_enabled($cm)); $cm->completion = COMPLETION_TRACKING_NONE; $this->assertEquals(COMPLETION_TRACKING_NONE, $c->is_enabled($cm)); $cm->completion = COMPLETION_TRACKING_AUTOMATIC; $this->assertEquals(COMPLETION_TRACKING_AUTOMATIC, $c->is_enabled($cm)); }
public function get_content() { global $CFG, $USER; // If content is cached if ($this->content !== NULL) { return $this->content; } // Create empty content $this->content = new stdClass(); // Can edit settings? $can_edit = has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $this->page->course->id)); // Get course completion data $info = new completion_info($this->page->course); // Don't display if completion isn't enabled! if (!completion_info::is_enabled_for_site()) { if ($can_edit) { $this->content->text = get_string('completionnotenabledforsite', 'completion'); } return $this->content; } else { if (!$info->is_enabled()) { if ($can_edit) { $this->content->text = get_string('completionnotenabledforcourse', 'completion'); } return $this->content; } } // Get this user's data $completion = $info->get_completion($USER->id, COMPLETION_CRITERIA_TYPE_SELF); // Check if self completion is one of this course's criteria if (empty($completion)) { if ($can_edit) { $this->content->text = get_string('selfcompletionnotenabled', 'block_selfcompletion'); } return $this->content; } // Check this user is enroled if (!$info->is_tracked_user($USER->id)) { $this->content->text = get_string('notenroled', 'completion'); return $this->content; } // Is course complete? if ($info->is_course_complete($USER->id)) { $this->content->text = get_string('coursealreadycompleted', 'completion'); return $this->content; // Check if the user has already marked themselves as complete } else { if ($completion->is_complete()) { $this->content->text = get_string('alreadyselfcompleted', 'block_selfcompletion'); return $this->content; // If user is not complete, or has not yet self completed } else { $this->content->text = ''; $this->content->footer = '<br /><a href="' . $CFG->wwwroot . '/course/togglecompletion.php?course=' . $this->page->course->id . '">'; $this->content->footer .= get_string('completecourse', 'block_selfcompletion') . '</a>...'; } } return $this->content; }
function definition() { global $USER, $CFG, $DB, $PAGE; $mform = $this->_form; $PAGE->requires->yui_module('moodle-course-formatchooser', 'M.course.init_formatchooser', array(array('formid' => $mform->getAttribute('id')))); $course = $this->_customdata['course']; // this contains the data of this form $category = $this->_customdata['category']; $editoroptions = $this->_customdata['editoroptions']; $returnto = $this->_customdata['returnto']; $systemcontext = context_system::instance(); $categorycontext = context_coursecat::instance($category->id); if (!empty($course->id)) { $coursecontext = context_course::instance($course->id); $context = $coursecontext; } else { $coursecontext = null; $context = $categorycontext; } $courseconfig = get_config('moodlecourse'); $this->course = $course; $this->context = $context; /// form definition with new course defaults //-------------------------------------------------------------------------------- $mform->addElement('header', 'general', get_string('general', 'form')); $mform->addElement('hidden', 'returnto', null); $mform->setType('returnto', PARAM_ALPHANUM); $mform->setConstant('returnto', $returnto); $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"'); $mform->addHelpButton('fullname', 'fullnamecourse'); $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client'); $mform->setType('fullname', PARAM_TEXT); if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) { $mform->hardFreeze('fullname'); $mform->setConstant('fullname', $course->fullname); } $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"'); $mform->addHelpButton('shortname', 'shortnamecourse'); $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client'); $mform->setType('shortname', PARAM_TEXT); if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) { $mform->hardFreeze('shortname'); $mform->setConstant('shortname', $course->shortname); } // Verify permissions to change course category or keep current. if (empty($course->id)) { if (has_capability('moodle/course:create', $categorycontext)) { $displaylist = coursecat::make_categories_list('moodle/course:create'); $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist); $mform->addHelpButton('category', 'coursecategory'); $mform->setDefault('category', $category->id); } else { $mform->addElement('hidden', 'category', null); $mform->setType('category', PARAM_INT); $mform->setConstant('category', $category->id); } } else { if (has_capability('moodle/course:changecategory', $coursecontext)) { $displaylist = coursecat::make_categories_list('moodle/course:create'); if (!isset($displaylist[$course->category])) { //always keep current $displaylist[$course->category] = coursecat::get($course->category)->get_formatted_name(); } $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist); $mform->addHelpButton('category', 'coursecategory'); } else { //keep current $mform->addElement('hidden', 'category', null); $mform->setType('category', PARAM_INT); $mform->setConstant('category', $course->category); } } $choices = array(); $choices['0'] = get_string('hide'); $choices['1'] = get_string('show'); $mform->addElement('select', 'visible', get_string('visible'), $choices); $mform->addHelpButton('visible', 'visible'); $mform->setDefault('visible', $courseconfig->visible); if (!has_capability('moodle/course:visibility', $context)) { $mform->hardFreeze('visible'); if (!empty($course->id)) { $mform->setConstant('visible', $course->visible); } else { $mform->setConstant('visible', $courseconfig->visible); } } $mform->addElement('date_selector', 'startdate', get_string('startdate')); $mform->addHelpButton('startdate', 'startdate'); $mform->setDefault('startdate', time() + 3600 * 24); $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100" size="10"'); $mform->addHelpButton('idnumber', 'idnumbercourse'); $mform->setType('idnumber', PARAM_RAW); if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) { $mform->hardFreeze('idnumber'); $mform->setConstants('idnumber', $course->idnumber); } // Description. $mform->addElement('header', 'descriptionhdr', get_string('description')); $mform->setExpanded('descriptionhdr'); $mform->addElement('editor', 'summary_editor', get_string('coursesummary'), null, $editoroptions); $mform->addHelpButton('summary_editor', 'coursesummary'); $mform->setType('summary_editor', PARAM_RAW); $summaryfields = 'summary_editor'; if ($overviewfilesoptions = course_overviewfiles_options($course)) { $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions); $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles'); $summaryfields .= ',overviewfiles_filemanager'; } if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) { // Remove the description header it does not contain anything any more. $mform->removeElement('descriptionhdr'); $mform->hardFreeze($summaryfields); } // Course format. $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin')); $courseformats = get_sorted_course_formats(true); $formcourseformats = array(); foreach ($courseformats as $courseformat) { $formcourseformats[$courseformat] = get_string('pluginname', "format_{$courseformat}"); } if (isset($course->format)) { $course->format = course_get_format($course)->get_format(); // replace with default if not found if (!in_array($course->format, $courseformats)) { // this format is disabled. Still display it in the dropdown $formcourseformats[$course->format] = get_string('withdisablednote', 'moodle', get_string('pluginname', 'format_' . $course->format)); } } $mform->addElement('select', 'format', get_string('format'), $formcourseformats); $mform->addHelpButton('format', 'format'); $mform->setDefault('format', $courseconfig->format); // Button to update format-specific options on format change (will be hidden by JavaScript). $mform->registerNoSubmitButton('updatecourseformat'); $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate')); // Just a placeholder for the course format options. $mform->addElement('hidden', 'addcourseformatoptionshere'); $mform->setType('addcourseformatoptionshere', PARAM_BOOL); // Appearance. $mform->addElement('header', 'appearancehdr', get_string('appearance')); if (!empty($CFG->allowcoursethemes)) { $themeobjects = get_list_of_themes(); $themes = array(); $themes[''] = get_string('forceno'); foreach ($themeobjects as $key => $theme) { if (empty($theme->hidefromselector)) { $themes[$key] = get_string('pluginname', 'theme_' . $theme->name); } } $mform->addElement('select', 'theme', get_string('forcetheme'), $themes); } $languages = array(); $languages[''] = get_string('forceno'); $languages += get_string_manager()->get_list_of_translations(); $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages); $mform->setDefault('lang', $courseconfig->lang); $options = range(0, 10); $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options); $mform->addHelpButton('newsitems', 'newsitemsnumber'); $mform->setDefault('newsitems', $courseconfig->newsitems); $mform->addElement('selectyesno', 'showgrades', get_string('showgrades')); $mform->addHelpButton('showgrades', 'showgrades'); $mform->setDefault('showgrades', $courseconfig->showgrades); $mform->addElement('selectyesno', 'showreports', get_string('showreports')); $mform->addHelpButton('showreports', 'showreports'); $mform->setDefault('showreports', $courseconfig->showreports); // Files and uploads. $mform->addElement('header', 'filehdr', get_string('filesanduploads')); if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) { if (empty($course->legacyfiles)) { //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet $choices = array('0' => get_string('no'), '2' => get_string('yes')); } else { $choices = array('1' => get_string('no'), '2' => get_string('yes')); } $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices); $mform->addHelpButton('legacyfiles', 'courselegacyfiles'); if (!isset($courseconfig->legacyfiles)) { // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses $courseconfig->legacyfiles = 0; } $mform->setDefault('legacyfiles', $courseconfig->legacyfiles); } // Handle non-existing $course->maxbytes on course creation. $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes; // Let's prepare the maxbytes popup. $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes); $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices); $mform->addHelpButton('maxbytes', 'maximumupload'); $mform->setDefault('maxbytes', $courseconfig->maxbytes); // Completion tracking. if (completion_info::is_enabled_for_site()) { $mform->addElement('header', 'completionhdr', get_string('completion', 'completion')); $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion')); $mform->setDefault('enablecompletion', $courseconfig->enablecompletion); $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion'); } else { $mform->addElement('hidden', 'enablecompletion'); $mform->setType('enablecompletion', PARAM_INT); $mform->setDefault('enablecompletion', 0); } //-------------------------------------------------------------------------------- enrol_course_edit_form($mform, $course, $context); //-------------------------------------------------------------------------------- $mform->addElement('header', 'groups', get_string('groups', 'group')); $choices = array(); $choices[NOGROUPS] = get_string('groupsnone', 'group'); $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group'); $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group'); $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices); $mform->addHelpButton('groupmode', 'groupmode', 'group'); $mform->setDefault('groupmode', $courseconfig->groupmode); $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group')); $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group'); $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce); //default groupings selector $options = array(); $options[0] = get_string('none'); $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options); //-------------------------------------------------------------------------------- /// customizable role names in this course //-------------------------------------------------------------------------------- $mform->addElement('header', 'rolerenaming', get_string('rolerenaming')); $mform->addHelpButton('rolerenaming', 'rolerenaming'); if ($roles = get_all_roles()) { $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL); $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE); foreach ($roles as $role) { $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->localname)); $mform->setType('role_' . $role->id, PARAM_TEXT); } } //-------------------------------------------------------------------------------- $this->add_action_buttons(); //-------------------------------------------------------------------------------- $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); /// finally set the current form data //-------------------------------------------------------------------------------- $this->set_data($course); }
/** * Used to notify the completion system (if necessary) that a user's grade * has changed, and clear up a possible score cache. * * @param bool $deleted True if grade was actually deleted */ protected function notify_changed($deleted) { global $CFG; // Condition code may cache the grades for conditional availability of // modules or sections. (This code should use a hook for communication // with plugin, but hooks are not implemented at time of writing.) if (!empty($CFG->enableavailability) && class_exists('\\availability_grade\\callbacks')) { \availability_grade\callbacks::grade_changed($this->userid); } require_once $CFG->libdir . '/completionlib.php'; // Bail out immediately if completion is not enabled for site (saves loading // grade item & requiring the restore stuff). if (!completion_info::is_enabled_for_site()) { return; } // Ignore during restore, as completion data will be updated anyway and // doing it now will result in incorrect dates (it will say they got the // grade completion now, instead of the correct time). if (class_exists('restore_controller', false) && restore_controller::is_executing()) { return; } // Load information about grade item $this->load_grade_item(); // Only course-modules have completion data if ($this->grade_item->itemtype != 'mod') { return; } // Use $COURSE if available otherwise get it via item fields $course = get_course($this->grade_item->courseid, false); // Bail out if completion is not enabled for course $completion = new completion_info($course); if (!$completion->is_enabled()) { return; } // Get course-module $cm = get_coursemodule_from_instance($this->grade_item->itemmodule, $this->grade_item->iteminstance, $this->grade_item->courseid); // If the course-module doesn't exist, display a warning... if (!$cm) { // ...unless the grade is being deleted in which case it's likely // that the course-module was just deleted too, so that's okay. if (!$deleted) { debugging("Couldn't find course-module for module '" . $this->grade_item->itemmodule . "', instance '" . $this->grade_item->iteminstance . "', course '" . $this->grade_item->courseid . "'"); } return; } // Pass information on to completion system $completion->inform_grade_changed($cm, $this->grade_item, $this, $deleted); }
public function get_content() { global $USER, $CFG, $DB, $COURSE; // If content is cached if ($this->content !== NULL) { return $this->content; } // Create empty content $this->content = new stdClass(); // Can edit settings? $can_edit = has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $this->page->course->id)); // Get course completion data $info = new completion_info($this->page->course); // Don't display if completion isn't enabled! if (!completion_info::is_enabled_for_site()) { if ($can_edit) { $this->content->text = get_string('completionnotenabledforsite', 'completion'); } return $this->content; } else { if (!$info->is_enabled()) { if ($can_edit) { $this->content->text = get_string('completionnotenabledforcourse', 'completion'); } return $this->content; } } // Load criteria to display $completions = $info->get_completions($USER->id); // Check if this course has any criteria if (empty($completions)) { if ($can_edit) { $this->content->text = get_string('nocriteriaset', 'completion'); } return $this->content; } // Check this user is enroled if (!$info->is_tracked_user($USER->id)) { // If not enrolled, but are can view the report: if (has_capability('report/completion:view', get_context_instance(CONTEXT_COURSE, $COURSE->id))) { $this->content->text = '<a href="' . $CFG->wwwroot . '/report/completion/index.php?course=' . $COURSE->id . '">' . get_string('viewcoursereport', 'completion') . '</a>'; return $this->content; } // Otherwise, show error $this->content->text = get_string('notenroled', 'completion'); return $this->content; } // Generate markup for criteria statuses $shtml = ''; // For aggregating activity completion $activities = array(); $activities_complete = 0; // For aggregating course prerequisites $prerequisites = array(); $prerequisites_complete = 0; // Flag to set if current completion data is inconsistent with // what is stored in the database $pending_update = false; // Loop through course criteria foreach ($completions as $completion) { $criteria = $completion->get_criteria(); $complete = $completion->is_complete(); if (!$pending_update && $criteria->is_pending($completion)) { $pending_update = true; } // Activities are a special case, so cache them and leave them till last if ($criteria->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) { $activities[$criteria->moduleinstance] = $complete; if ($complete) { $activities_complete++; } continue; } // Prerequisites are also a special case, so cache them and leave them till last if ($criteria->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) { $prerequisites[$criteria->courseinstance] = $complete; if ($complete) { $prerequisites_complete++; } continue; } $shtml .= '<tr><td>'; $shtml .= $criteria->get_title(); $shtml .= '</td><td style="text-align: right">'; $shtml .= $completion->get_status(); $shtml .= '</td></tr>'; } // Aggregate activities if (!empty($activities)) { $shtml .= '<tr><td>'; $shtml .= get_string('activitiescompleted', 'completion'); $shtml .= '</td><td style="text-align: right">'; $a = new stdClass(); $a->first = $activities_complete; $a->second = count($activities); $shtml .= get_string('firstofsecond', 'block_completionstatus', $a); $shtml .= '</td></tr>'; } // Aggregate prerequisites if (!empty($prerequisites)) { $phtml = '<tr><td>'; $phtml .= get_string('prerequisitescompleted', 'completion'); $phtml .= '</td><td style="text-align: right">'; $a = new stdClass(); $a->first = $prerequisites_complete; $a->second = count($prerequisites); $shtml .= get_string('firstofsecond', 'block_completionstatus', $a); $phtml .= '</td></tr>'; $shtml = $phtml . $shtml; } // Display completion status $this->content->text = '<table width="100%" style="font-size: 90%;"><tbody>'; $this->content->text .= '<tr><td colspan="2"><b>' . get_string('status') . ':</b> '; // Is course complete? $coursecomplete = $info->is_course_complete($USER->id); // Load course completion $params = array('userid' => $USER->id, 'course' => $COURSE->id); $ccompletion = new completion_completion($params); // Has this user completed any criteria? $criteriacomplete = $info->count_course_user_data($USER->id); if ($pending_update) { $this->content->text .= '<i>' . get_string('pending', 'completion') . '</i>'; } else { if ($coursecomplete) { $this->content->text .= get_string('complete'); } else { if (!$criteriacomplete && !$ccompletion->timestarted) { $this->content->text .= '<i>' . get_string('notyetstarted', 'completion') . '</i>'; } else { $this->content->text .= '<i>' . get_string('inprogress', 'completion') . '</i>'; } } } $this->content->text .= '</td></tr>'; $this->content->text .= '<tr><td colspan="2">'; // Get overall aggregation method $overall = $info->get_aggregation_method(); if ($overall == COMPLETION_AGGREGATION_ALL) { $this->content->text .= get_string('criteriarequiredall', 'completion'); } else { $this->content->text .= get_string('criteriarequiredany', 'completion'); } $this->content->text .= ':</td></tr>'; $this->content->text .= '<tr><td><b>' . get_string('requiredcriteria', 'completion') . '</b></td><td style="text-align: right"><b>' . get_string('status') . '</b></td></tr>'; $this->content->text .= $shtml . '</tbody></table>'; // Display link to detailed view $this->content->footer = '<br><a href="' . $CFG->wwwroot . '/blocks/completionstatus/details.php?course=' . $COURSE->id . '">' . get_string('moredetails', 'completion') . '</a>'; return $this->content; }
function definition() { global $USER, $CFG, $DB; $mform = $this->_form; $course = $this->_customdata['course']; // this contains the data of this form $category = $this->_customdata['category']; $editoroptions = $this->_customdata['editoroptions']; $returnto = $this->_customdata['returnto']; $systemcontext = get_context_instance(CONTEXT_SYSTEM); $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id); if (!empty($course->id)) { $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $context = $coursecontext; } else { $coursecontext = null; $context = $categorycontext; } $courseconfig = get_config('moodlecourse'); $this->course = $course; $this->context = $context; /// form definition with new course defaults //-------------------------------------------------------------------------------- $mform->addElement('header','general', get_string('general', 'form')); $mform->addElement('hidden', 'returnto', null); $mform->setType('returnto', PARAM_ALPHANUM); $mform->setConstant('returnto', $returnto); // verify permissions to change course category or keep current if (empty($course->id)) { if (has_capability('moodle/course:create', $categorycontext)) { $displaylist = array(); $parentlist = array(); make_categories_list($displaylist, $parentlist, 'moodle/course:create'); $mform->addElement('select', 'category', get_string('category'), $displaylist); $mform->addHelpButton('category', 'category'); $mform->setDefault('category', $category->id); } else { $mform->addElement('hidden', 'category', null); $mform->setType('category', PARAM_INT); $mform->setConstant('category', $category->id); } } else { if (has_capability('moodle/course:changecategory', $coursecontext)) { $displaylist = array(); $parentlist = array(); make_categories_list($displaylist, $parentlist, 'moodle/course:create'); if (!isset($displaylist[$course->category])) { //always keep current $displaylist[$course->category] = format_string($DB->get_field('course_categories', 'name', array('id'=>$course->category))); } $mform->addElement('select', 'category', get_string('category'), $displaylist); $mform->addHelpButton('category', 'category'); } else { //keep current $mform->addElement('hidden', 'category', null); $mform->setType('category', PARAM_INT); $mform->setConstant('category', $course->category); } } $mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"'); $mform->addHelpButton('fullname', 'fullnamecourse'); $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client'); $mform->setType('fullname', PARAM_MULTILANG); if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) { $mform->hardFreeze('fullname'); $mform->setConstant('fullname', $course->fullname); } $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"'); $mform->addHelpButton('shortname', 'shortnamecourse'); $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client'); $mform->setType('shortname', PARAM_MULTILANG); if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) { $mform->hardFreeze('shortname'); $mform->setConstant('shortname', $course->shortname); } $mform->addElement('text','idnumber', get_string('idnumbercourse'),'maxlength="100" size="10"'); $mform->addHelpButton('idnumber', 'idnumbercourse'); $mform->setType('idnumber', PARAM_RAW); if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) { $mform->hardFreeze('idnumber'); $mform->setConstants('idnumber', $course->idnumber); } $mform->addElement('editor','summary_editor', get_string('coursesummary'), null, $editoroptions); $mform->addHelpButton('summary_editor', 'coursesummary'); $mform->setType('summary_editor', PARAM_RAW); if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) { $mform->hardFreeze('summary_editor'); } $courseformats = get_plugin_list('format'); $formcourseformats = array(); foreach ($courseformats as $courseformat => $formatdir) { $formcourseformats[$courseformat] = get_string('pluginname', "format_$courseformat"); } $mform->addElement('select', 'format', get_string('format'), $formcourseformats); $mform->addHelpButton('format', 'format'); $mform->setDefault('format', $courseconfig->format); for ($i=1; $i<=52; $i++) { $sectionmenu[$i] = "$i"; } $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu); $mform->setDefault('numsections', $courseconfig->numsections); $mform->addElement('date_selector', 'startdate', get_string('startdate')); $mform->addHelpButton('startdate', 'startdate'); $mform->setDefault('startdate', time() + 3600 * 24); $choices = array(); $choices['0'] = get_string('hiddensectionscollapsed'); $choices['1'] = get_string('hiddensectionsinvisible'); $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices); $mform->addHelpButton('hiddensections', 'hiddensections'); $mform->setDefault('hiddensections', $courseconfig->hiddensections); $options = range(0, 10); $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options); $mform->addHelpButton('newsitems', 'newsitemsnumber'); $mform->setDefault('newsitems', $courseconfig->newsitems); $mform->addElement('selectyesno', 'showgrades', get_string('showgrades')); $mform->addHelpButton('showgrades', 'showgrades'); $mform->setDefault('showgrades', $courseconfig->showgrades); $mform->addElement('selectyesno', 'showreports', get_string('showreports')); $mform->addHelpButton('showreports', 'showreports'); $mform->setDefault('showreports', $courseconfig->showreports); $choices = get_max_upload_sizes($CFG->maxbytes); $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices); $mform->addHelpButton('maxbytes', 'maximumupload'); $mform->setDefault('maxbytes', $courseconfig->maxbytes); if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) { if (empty($course->legacyfiles)) { //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet $choices = array('0'=>get_string('no'), '2'=>get_string('yes')); } else { $choices = array('1'=>get_string('no'), '2'=>get_string('yes')); } $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices); $mform->addHelpButton('legacyfiles', 'courselegacyfiles'); if (!isset($courseconfig->legacyfiles)) { // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses $courseconfig->legacyfiles = 0; } $mform->setDefault('legacyfiles', $courseconfig->legacyfiles); } if (!empty($CFG->allowcoursethemes)) { $themeobjects = get_list_of_themes(); $themes=array(); $themes[''] = get_string('forceno'); foreach ($themeobjects as $key=>$theme) { $themes[$key] = $theme->name; } $mform->addElement('select', 'theme', get_string('forcetheme'), $themes); } //-------------------------------------------------------------------------------- enrol_course_edit_form($mform, $course, $context); //-------------------------------------------------------------------------------- $mform->addElement('header','', get_string('groups', 'group')); $choices = array(); $choices[NOGROUPS] = get_string('groupsnone', 'group'); $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group'); $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group'); $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices); $mform->addHelpButton('groupmode', 'groupmode', 'group'); $mform->setDefault('groupmode', $courseconfig->groupmode); $choices = array(); $choices['0'] = get_string('no'); $choices['1'] = get_string('yes'); $mform->addElement('select', 'groupmodeforce', get_string('groupmodeforce', 'group'), $choices); $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group'); $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce); //default groupings selector $options = array(); $options[0] = get_string('none'); $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options); //-------------------------------------------------------------------------------- $mform->addElement('header','', get_string('availability')); $choices = array(); $choices['0'] = get_string('courseavailablenot'); $choices['1'] = get_string('courseavailable'); $mform->addElement('select', 'visible', get_string('availability'), $choices); $mform->addHelpButton('visible', 'availability'); $mform->setDefault('visible', $courseconfig->visible); if (!has_capability('moodle/course:visibility', $context)) { $mform->hardFreeze('visible'); if (!empty($course->id)) { $mform->setConstant('visible', $course->visible); } else { $mform->setConstant('visible', $category->visible); } } //-------------------------------------------------------------------------------- $mform->addElement('header','', get_string('language')); $languages=array(); $languages[''] = get_string('forceno'); $languages += get_string_manager()->get_list_of_translations(); $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages); $mform->setDefault('lang', $courseconfig->lang); //-------------------------------------------------------------------------------- if (completion_info::is_enabled_for_site()) { $mform->addElement('header','', get_string('progress','completion')); $mform->addElement('select', 'enablecompletion', get_string('completion','completion'), array(0=>get_string('completiondisabled','completion'), 1=>get_string('completionenabled','completion'))); $mform->setDefault('enablecompletion', $courseconfig->enablecompletion); $mform->addElement('checkbox', 'completionstartonenrol', get_string('completionstartonenrol', 'completion')); $mform->setDefault('completionstartonenrol', $courseconfig->completionstartonenrol); $mform->disabledIf('completionstartonenrol', 'enablecompletion', 'eq', 0); } else { $mform->addElement('hidden', 'enablecompletion'); $mform->setType('enablecompletion', PARAM_INT); $mform->setDefault('enablecompletion',0); $mform->addElement('hidden', 'completionstartonenrol'); $mform->setType('completionstartonenrol', PARAM_INT); $mform->setDefault('completionstartonenrol',0); } //-------------------------------------------------------------------------------- if (has_capability('moodle/site:config', $systemcontext)) { if (((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) { $mform->addElement('header', '', get_string('restrictmodules')); $options = array(); $options['0'] = get_string('no'); $options['1'] = get_string('yes'); $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options); if (!empty($CFG->restrictbydefault)) { $mform->setDefault('restrictmodules', 1); } $mods = array(0=>get_string('allownone')); $mods += $DB->get_records_menu('modules', array('visible'=>1), 'name', 'id, name'); $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple'=>'multiple', 'size'=>'10')); $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0); // defaults are already in $course } else { // remove any mod restriction $mform->addElement('hidden', 'restrictmodules', 0); $mform->setType('restrictmodules', PARAM_INT); } } else { $mform->addElement('hidden', 'restrictmodules'); $mform->setType('restrictmodules', PARAM_INT); if (empty($course->id)) { $mform->setConstant('restrictmodules', (int)($CFG->restrictmodulesfor == 'all')); } else { // keep previous $mform->setConstant('restrictmodules', $course->restrictmodules); } } /// customizable role names in this course //-------------------------------------------------------------------------------- $mform->addElement('header','rolerenaming', get_string('rolerenaming')); $mform->addHelpButton('rolerenaming', 'rolerenaming'); if ($roles = get_all_roles()) { if ($coursecontext) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW); } $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE); foreach ($roles as $role) { $mform->addElement('text', 'role_'.$role->id, get_string('yourwordforx', '', $role->name)); if (isset($role->localname)) { $mform->setDefault('role_'.$role->id, $role->localname); } $mform->setType('role_'.$role->id, PARAM_TEXT); if (!in_array($role->id, $assignableroles)) { $mform->setAdvanced('role_'.$role->id); } } } //-------------------------------------------------------------------------------- $this->add_action_buttons(); //-------------------------------------------------------------------------------- $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); /// finally set the current form data //-------------------------------------------------------------------------------- $this->set_data($course); }
/** * Used to notify the completion system (if necessary) that a user's grade * has changed, and clear up a possible score cache. * * @param bool $deleted True if grade was actually deleted */ function notify_changed($deleted) { global $CFG; // Ignore during restore // TODO There should be a proper way to determine when we are in restore // so that this hack looking for a $restore global is not needed. global $restore; if (!empty($restore->backup_unique_code)) { return; } // Inform conditionlib since it may cache the grades for conditional availability of modules or sections. if (!empty($CFG->enableavailability)) { require_once $CFG->libdir . '/conditionlib.php'; condition_info_base::inform_grade_changed($this, $deleted); } require_once $CFG->libdir . '/completionlib.php'; // Bail out immediately if completion is not enabled for site (saves loading // grade item below) if (!completion_info::is_enabled_for_site()) { return; } // Load information about grade item $this->load_grade_item(); // Only course-modules have completion data if ($this->grade_item->itemtype != 'mod') { return; } // Use $COURSE if available otherwise get it via item fields $course = get_course($this->grade_item->courseid, false); // Bail out if completion is not enabled for course $completion = new completion_info($course); if (!$completion->is_enabled()) { return; } // Get course-module $cm = get_coursemodule_from_instance($this->grade_item->itemmodule, $this->grade_item->iteminstance, $this->grade_item->courseid); // If the course-module doesn't exist, display a warning... if (!$cm) { // ...unless the grade is being deleted in which case it's likely // that the course-module was just deleted too, so that's okay. if (!$deleted) { debugging("Couldn't find course-module for module '" . $this->grade_item->itemmodule . "', instance '" . $this->grade_item->iteminstance . "', course '" . $this->grade_item->courseid . "'"); } return; } // Pass information on to completion system $completion->inform_grade_changed($cm, $this->grade_item, $this, $deleted); }
/** * Update courses * * @param array $courses * @since Moodle 2.5 */ public static function update_courses($courses) { global $CFG, $DB; require_once($CFG->dirroot . "/course/lib.php"); $warnings = array(); $params = self::validate_parameters(self::update_courses_parameters(), array('courses' => $courses)); $availablethemes = core_component::get_plugin_list('theme'); $availablelangs = get_string_manager()->get_list_of_translations(); foreach ($params['courses'] as $course) { // Catch any exception while updating course and return as warning to user. try { // Ensure the current user is allowed to run this function. $context = context_course::instance($course['id'], MUST_EXIST); self::validate_context($context); $oldcourse = course_get_format($course['id'])->get_course(); require_capability('moodle/course:update', $context); // Check if user can change category. if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) { require_capability('moodle/course:changecategory', $context); $course['category'] = $course['categoryid']; } // Check if the user can change fullname. if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) { require_capability('moodle/course:changefullname', $context); } // Check if the user can change shortname. if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) { require_capability('moodle/course:changeshortname', $context); } // Check if the user can change the idnumber. if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) { require_capability('moodle/course:changeidnumber', $context); } // Check if user can change summary. if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) { require_capability('moodle/course:changesummary', $context); } // Summary format. if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) { require_capability('moodle/course:changesummary', $context); $course['summaryformat'] = external_validate_format($course['summaryformat']); } // Check if user can change visibility. if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) { require_capability('moodle/course:visibility', $context); } // Make sure lang is valid. if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) { throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang'); } // Make sure theme is valid. if (array_key_exists('forcetheme', $course)) { if (!empty($CFG->allowcoursethemes)) { if (empty($availablethemes[$course['forcetheme']])) { throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme'); } else { $course['theme'] = $course['forcetheme']; } } } // Make sure completion is enabled before setting it. if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) { $course['enabledcompletion'] = 0; } // Make sure maxbytes are less then CFG->maxbytes. if (array_key_exists('maxbytes', $course)) { $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']); } if (!empty($course['courseformatoptions'])) { foreach ($course['courseformatoptions'] as $option) { if (isset($option['name']) && isset($option['value'])) { $course[$option['name']] = $option['value']; } } } // Update course if user has all required capabilities. update_course((object) $course); } catch (Exception $e) { $warning = array(); $warning['item'] = 'course'; $warning['itemid'] = $course['id']; if ($e instanceof moodle_exception) { $warning['warningcode'] = $e->errorcode; } else { $warning['warningcode'] = $e->getCode(); } $warning['message'] = $e->getMessage(); $warnings[] = $warning; } } $result = array(); $result['warnings'] = $warnings; return $result; }
/** * Form definition. */ function definition() { global $CFG, $PAGE,$USER,$DB; $mform = $this->_form; $PAGE->requires->yui_module('moodle-course-formatchooser', 'M.course.init_formatchooser', array(array('formid' => $mform->getAttribute('id')))); $course = $this->_customdata['course']; // this contains the data of this form //print_object($course); $category = $this->_customdata['category']; $editoroptions = $this->_customdata['editoroptions']; $returnto = $this->_customdata['returnto']; $systemcontext = context_system::instance(); $categorycontext = context_coursecat::instance($category->id); if (!empty($course->id)) { $coursecontext = context_course::instance($course->id); $context = $coursecontext; } else { $coursecontext = null; $context = $categorycontext; } $courseconfig = get_config('moodlecourse'); $this->course = $course; $this->context = $context; // Form definition with new course defaults. $mform->addElement('header','general', get_string('general', 'form')); $mform->addElement('hidden', 'returnto', null); $mform->setType('returnto', PARAM_ALPHANUM); $mform->setConstant('returnto', $returnto); /* * EA_NK23-02-2015 * Added cost center field */ $is_manager = $DB->record_exists_sql("SELECT ra.userid FROM {role_assignments} as ra JOIN {role} as r ON ra.roleid=r.id WHERE r.archetype='manager' AND ra.userid={$USER->id}"); if(is_siteadmin()) { /*==================strated by raju.t for admin created courses goes to HR department on 9-11-2015=============*/ $admincostcenters=user_wise_department(); //print_object($admincostcenters); $mform->addElement('select', 'costcenter', get_string('pluginname', 'local_costcenter'), $admincostcenters); /*==================Ended by raju.t for admin created courses goes to HR department on 9-11-2015=============*/ }elseif(!is_siteadmin()){ $admincostcenters=user_wise_department(); $mform->addElement('select', 'costcenter', get_string('pluginname', 'local_costcenter'), $admincostcenters); } //$costcenter = $DB->get_records_sql_menu("SELECT cc.id,cc.fullname FROM mdl_local_userdata ud JOIN mdl_local_costcenter cc ON ud.costcenterid=cc.id WHERE ud.userid={$USER->id}"); //$mform->addElement('hidden','costcenter'); //$mform->setDefault('costcenter',$costcenter->id); //$mform->addElement('static', 'costcenterid', get_string('pluginname', 'local_costcenter'), $costcenter->fullname); $mform->setType('costcenter', PARAM_RAW); /* EA_NK23-02-2015 Customization ends here */ $mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"'); $mform->addHelpButton('fullname', 'fullnamecourse'); $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client'); $mform->setType('fullname', PARAM_TEXT); if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) { $mform->hardFreeze('fullname'); $mform->setConstant('fullname', $course->fullname); } $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"'); $mform->addHelpButton('shortname', 'shortnamecourse'); $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client'); $mform->setType('shortname', PARAM_TEXT); if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) { $mform->hardFreeze('shortname'); $mform->setConstant('shortname', $course->shortname); } // Verify permissions to change course category or keep current. if (empty($course->id)) { if (has_capability('moodle/course:create', $categorycontext)) { $displaylist = coursecat::make_categories_list('moodle/course:create'); /*======================Started By Raju.T for Disaply Course Categories based on training manager deparment on 9-11-2015============*/ if(is_siteadmin()){ $admincoursecategory=department_category_course(); $mform->addElement('select', 'category', get_string('coursecategory'), $admincoursecategory); /*==================Ended by raju.t for admin created courses goes to HR department on 9-11-2015=============*/ }else{ /*======================Ended By Raju.T for Disaply Course Categories based on training manager deparment on 9-11-2015============*/ $admincoursecategory=department_category_course(); $mform->addElement('select', 'category', get_string('coursecategory'), $admincoursecategory); $userdepartment_exist=$DB->record_exists('local_userdata',array('userid'=>$USER->id)); if($userdepartment_exist==1){ $userdepartment=$DB->get_record('local_userdata',array('userid'=>$USER->id)); if($userdepartment->lms_category=="AST" || $userdepartment->lms_category=="AST-EXT"){ $trainer_type_options=array(null=>'----Select to----',T=>'Trainer',SM=>'Sales Manager'); $mform->addElement('select', 'assignedto', get_string('assigne_to'), $trainer_type_options); //$mform->setConstant('category', $category->id); //$mform->setDefault('assignedto', $course->assignedto); } } /*==================strated by raju.t for admin created courses goes to HR department on 9-11-2015=============*/ } $mform->addHelpButton('category', 'coursecategory'); $mform->setDefault('category', $category->id); $mform->addElement('text','duration',get_string('course_duration'),'maxlength="100" size="10"'); if(!empty($course->assignedto)){ $mform->setDefault('duration', $course->duration); }else{ $mform->setDefault('duration','0'); } $mform->setType('duration', PARAM_RAW); $mform->addRule('duration', get_string('possitiveonly'), 'regex', '#^(0|[1-9][0-9]*)$#'); } else { $mform->addElement('hidden', 'category', null); $mform->setType('category', PARAM_INT); $mform->setConstant('category', $category->id); } } else { if (has_capability('moodle/course:changecategory', $coursecontext)) { $admincoursecategory=department_category_course(); $mform->addElement('select', 'category', get_string('coursecategory'), $admincoursecategory); } else { //keep current $mform->addElement('hidden', 'category', null); $mform->setType('category', PARAM_INT); $mform->setConstant('category', $course->category); } $userdepartment_exist=$DB->record_exists('local_userdata',array('userid'=>$USER->id)); if($userdepartment_exist==1){ $userdepartment=$DB->get_record('local_userdata',array('userid'=>$USER->id)); if($userdepartment->lms_category=="AST" || $userdepartment->lms_category=="AST-EXT"){ $trainer_type_options=array(null=>'----Select to----',T=>'Trainer',SM=>'Sales Manager'); $mform->addElement('select', 'assignedto', get_string('assigne_to'), $trainer_type_options); //$mform->setConstant('category', $category->id); //$mform->setDefault('assignedto', $course->assignedto); } } /*==================strated by raju.t for admin created courses goes to HR department on 9-11-2015=============*/ $mform->addElement('text','duration',get_string('course_duration'),'maxlength="100" size="10"'); if(!empty($course->assignedto)){ $mform->setDefault('duration', $course->duration); }else{ $mform->setDefault('duration','0'); } $mform->setType('duration', PARAM_RAW); $mform->addRule('duration', get_string('possitiveonly'), 'regex', '#^(0|[1-9][0-9]*)$#'); } $choices = array(); $choices['0'] = get_string('hide'); $choices['1'] = get_string('show'); $mform->addElement('select', 'visible', get_string('visible'), $choices); $mform->addHelpButton('visible', 'visible'); $mform->setDefault('visible', $courseconfig->visible); if (!empty($course->id)) { if (!has_capability('moodle/course:visibility', $coursecontext)) { $mform->hardFreeze('visible'); $mform->setConstant('visible', $course->visible); } } else { if (!guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext)) { $mform->hardFreeze('visible'); $mform->setConstant('visible', $courseconfig->visible); } } $mform->addElement('date_selector', 'startdate', get_string('startdate')); $mform->addHelpButton('startdate', 'startdate'); $mform->setDefault('startdate', time() + 3600 * 24); $mform->addElement('text','idnumber', get_string('idnumbercourse'),'maxlength="100" size="10"'); $mform->addHelpButton('idnumber', 'idnumbercourse'); $mform->setType('idnumber', PARAM_RAW); if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) { $mform->hardFreeze('idnumber'); $mform->setConstants('idnumber', $course->idnumber); } // Description. $mform->addElement('header', 'descriptionhdr', get_string('description')); $mform->setExpanded('descriptionhdr'); $mform->addElement('editor','summary_editor', get_string('coursesummary'), null, $editoroptions); $mform->addHelpButton('summary_editor', 'coursesummary'); $mform->setType('summary_editor', PARAM_RAW); $summaryfields = 'summary_editor'; if ($overviewfilesoptions = course_overviewfiles_options($course)) { $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions); $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles'); $summaryfields .= ',overviewfiles_filemanager'; } if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) { // Remove the description header it does not contain anything any more. $mform->removeElement('descriptionhdr'); $mform->hardFreeze($summaryfields); } // Course format. $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin')); $courseformats = get_sorted_course_formats(true); $formcourseformats = array(); foreach ($courseformats as $courseformat) { $formcourseformats[$courseformat] = get_string('pluginname', "format_$courseformat"); } if (isset($course->format)) { $course->format = course_get_format($course)->get_format(); // replace with default if not found if (!in_array($course->format, $courseformats)) { // this format is disabled. Still display it in the dropdown $formcourseformats[$course->format] = get_string('withdisablednote', 'moodle', get_string('pluginname', 'format_'.$course->format)); } } $mform->addElement('select', 'format', get_string('format'), $formcourseformats); $mform->addHelpButton('format', 'format'); $mform->setDefault('format', $courseconfig->format); // Button to update format-specific options on format change (will be hidden by JavaScript). $mform->registerNoSubmitButton('updatecourseformat'); $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate')); // Just a placeholder for the course format options. $mform->addElement('hidden', 'addcourseformatoptionshere'); $mform->setType('addcourseformatoptionshere', PARAM_BOOL); // Appearance. $mform->addElement('header', 'appearancehdr', get_string('appearance')); if (!empty($CFG->allowcoursethemes)) { $themeobjects = get_list_of_themes(); $themes=array(); $themes[''] = get_string('forceno'); foreach ($themeobjects as $key=>$theme) { if (empty($theme->hidefromselector)) { $themes[$key] = get_string('pluginname', 'theme_'.$theme->name); } } $mform->addElement('select', 'theme', get_string('forcetheme'), $themes); } $languages=array(); $languages[''] = get_string('forceno'); $languages += get_string_manager()->get_list_of_translations(); $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages); $mform->setDefault('lang', $courseconfig->lang); // Multi-Calendar Support - see MDL-18375. $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types(); // We do not want to show this option unless there is more than one calendar type to display. if (count($calendartypes) > 1) { $calendars = array(); $calendars[''] = get_string('forceno'); $calendars += $calendartypes; $mform->addElement('select', 'calendartype', get_string('forcecalendartype', 'calendar'), $calendars); } $options = range(0, 10); $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options); $mform->addHelpButton('newsitems', 'newsitemsnumber'); $mform->setDefault('newsitems', $courseconfig->newsitems); $mform->addElement('selectyesno', 'showgrades', get_string('showgrades')); $mform->addHelpButton('showgrades', 'showgrades'); $mform->setDefault('showgrades', $courseconfig->showgrades); $mform->addElement('selectyesno', 'showreports', get_string('showreports')); $mform->addHelpButton('showreports', 'showreports'); $mform->setDefault('showreports', $courseconfig->showreports); // Files and uploads. $mform->addElement('header', 'filehdr', get_string('filesanduploads')); if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) { if (empty($course->legacyfiles)) { //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet $choices = array('0'=>get_string('no'), '2'=>get_string('yes')); } else { $choices = array('1'=>get_string('no'), '2'=>get_string('yes')); } $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices); $mform->addHelpButton('legacyfiles', 'courselegacyfiles'); if (!isset($courseconfig->legacyfiles)) { // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses $courseconfig->legacyfiles = 0; } $mform->setDefault('legacyfiles', $courseconfig->legacyfiles); } // Handle non-existing $course->maxbytes on course creation. $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes; // Let's prepare the maxbytes popup. $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes); $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices); $mform->addHelpButton('maxbytes', 'maximumupload'); $mform->setDefault('maxbytes', $courseconfig->maxbytes); // Completion tracking. if (completion_info::is_enabled_for_site()) { $mform->addElement('header', 'completionhdr', get_string('completion', 'completion')); $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion')); $mform->setDefault('enablecompletion', $courseconfig->enablecompletion); $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion'); } else { $mform->addElement('hidden', 'enablecompletion'); $mform->setType('enablecompletion', PARAM_INT); $mform->setDefault('enablecompletion', 0); } enrol_course_edit_form($mform, $course, $context); $mform->addElement('header','groups', get_string('groupsettingsheader', 'group')); $choices = array(); $choices[NOGROUPS] = get_string('groupsnone', 'group'); $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group'); $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group'); $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices); $mform->addHelpButton('groupmode', 'groupmode', 'group'); $mform->setDefault('groupmode', $courseconfig->groupmode); $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group')); $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group'); $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce); //default groupings selector $options = array(); $options[0] = get_string('none'); $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options); // Customizable role names in this course. $mform->addElement('header','rolerenaming', get_string('rolerenaming')); $mform->addHelpButton('rolerenaming', 'rolerenaming'); if ($roles = get_all_roles()) { $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL); $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE); foreach ($roles as $role) { $mform->addElement('text', 'role_'.$role->id, get_string('yourwordforx', '', $role->localname)); $mform->setType('role_'.$role->id, PARAM_TEXT); } } $this->add_action_buttons(); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); // Finally set the current form data $this->set_data($course); }
public function get_content() { global $USER; $rows = array(); $srows = array(); $prows = array(); // If content is cached. if ($this->content !== null) { return $this->content; } $course = $this->page->course; $context = context_course::instance($course->id); // Create empty content. $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; // Can edit settings? $can_edit = has_capability('moodle/course:update', $context); // Get course completion data. $info = new completion_info($course); // Don't display if completion isn't enabled! if (!completion_info::is_enabled_for_site()) { if ($can_edit) { $this->content->text .= get_string('completionnotenabledforsite', 'completion'); } return $this->content; } else { if (!$info->is_enabled()) { if ($can_edit) { $this->content->text .= get_string('completionnotenabledforcourse', 'completion'); } return $this->content; } } // Load criteria to display. $completions = $info->get_completions($USER->id); // Check if this course has any criteria. if (empty($completions)) { if ($can_edit) { $this->content->text .= get_string('nocriteriaset', 'completion'); } return $this->content; } // Check this user is enroled. if ($info->is_tracked_user($USER->id)) { // Generate markup for criteria statuses. $data = ''; // For aggregating activity completion. $activities = array(); $activities_complete = 0; // For aggregating course prerequisites. $prerequisites = array(); $prerequisites_complete = 0; // Flag to set if current completion data is inconsistent with what is stored in the database. $pending_update = false; // Loop through course criteria. foreach ($completions as $completion) { $criteria = $completion->get_criteria(); $complete = $completion->is_complete(); if (!$pending_update && $criteria->is_pending($completion)) { $pending_update = true; } // Activities are a special case, so cache them and leave them till last. if ($criteria->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) { $activities[$criteria->moduleinstance] = $complete; if ($complete) { $activities_complete++; } continue; } // Prerequisites are also a special case, so cache them and leave them till last. if ($criteria->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) { $prerequisites[$criteria->courseinstance] = $complete; if ($complete) { $prerequisites_complete++; } continue; } $row = new html_table_row(); $row->cells[0] = new html_table_cell($criteria->get_title()); $row->cells[1] = new html_table_cell($completion->get_status()); $row->cells[1]->style = 'text-align: right;'; $srows[] = $row; } // Aggregate activities. if (!empty($activities)) { $a = new stdClass(); $a->first = $activities_complete; $a->second = count($activities); $row = new html_table_row(); $row->cells[0] = new html_table_cell(get_string('activitiescompleted', 'completion')); $row->cells[1] = new html_table_cell(get_string('firstofsecond', 'block_completionstatus', $a)); $row->cells[1]->style = 'text-align: right;'; $srows[] = $row; } // Aggregate prerequisites. if (!empty($prerequisites)) { $a = new stdClass(); $a->first = $prerequisites_complete; $a->second = count($prerequisites); $row = new html_table_row(); $row->cells[0] = new html_table_cell(get_string('dependenciescompleted', 'completion')); $row->cells[1] = new html_table_cell(get_string('firstofsecond', 'block_completionstatus', $a)); $row->cells[1]->style = 'text-align: right;'; $prows[] = $row; $srows = array_merge($prows, $srows); } // Display completion status. $table = new html_table(); $table->width = '100%'; $table->attributes = array('style' => 'font-size: 90%;', 'class' => ''); $row = new html_table_row(); $content = html_writer::tag('b', get_string('status') . ': '); // Is course complete? $coursecomplete = $info->is_course_complete($USER->id); // Load course completion. $params = array('userid' => $USER->id, 'course' => $course->id); $ccompletion = new completion_completion($params); // Has this user completed any criteria? $criteriacomplete = $info->count_course_user_data($USER->id); if ($pending_update) { $content .= html_writer::tag('i', get_string('pending', 'completion')); } else { if ($coursecomplete) { $content .= get_string('complete'); } else { if (!$criteriacomplete && !$ccompletion->timestarted) { $content .= html_writer::tag('i', get_string('notyetstarted', 'completion')); } else { $content .= html_writer::tag('i', get_string('inprogress', 'completion')); } } } $row->cells[0] = new html_table_cell($content); $row->cells[0]->colspan = '2'; $rows[] = $row; $row = new html_table_row(); $content = ""; // Get overall aggregation method. $overall = $info->get_aggregation_method(); if ($overall == COMPLETION_AGGREGATION_ALL) { $content .= get_string('criteriarequiredall', 'completion'); } else { $content .= get_string('criteriarequiredany', 'completion'); } $content .= ':'; $row->cells[0] = new html_table_cell($content); $row->cells[0]->colspan = '2'; $rows[] = $row; $row = new html_table_row(); $row->cells[0] = new html_table_cell(html_writer::tag('b', get_string('requiredcriteria', 'completion'))); $row->cells[1] = new html_table_cell(html_writer::tag('b', get_string('status'))); $row->cells[1]->style = 'text-align: right;'; $rows[] = $row; // Array merge $rows and $data here. $rows = array_merge($rows, $srows); $table->data = $rows; $this->content->text .= html_writer::table($table); // Display link to detailed view. $details = new moodle_url('/blocks/completionstatus/details.php', array('course' => $course->id)); $this->content->footer .= html_writer::link($details, get_string('moredetails', 'completion')); } else { // If user is not enrolled, show error. $this->content->text = get_string('nottracked', 'completion'); } if (has_capability('report/completion:view', $context)) { $report = new moodle_url('/report/completion/index.php', array('course' => $course->id)); if (empty($this->content->footer)) { $this->content->footer = ''; } $this->content->footer .= html_writer::empty_tag('br'); $this->content->footer .= html_writer::link($report, get_string('viewcoursereport', 'completion')); } return $this->content; }
function moodle_course_create_courses($client) { global $DB, $CFG; ///Test data $courseconfig = get_config('moodlecourse'); $themeobjects = get_list_of_themes(); $theme = key($themeobjects); $categoryid = $DB->get_record('course_categories', array(), '*', IGNORE_MULTIPLE)->id; $categoryid = empty($categoryid) ? 0 : $categoryid; $course1 = new stdClass(); $course1->fullname = 'Test Data create course 1'; $course1->shortname = 'testdatacourse1'; $course1->categoryid = $categoryid; $course1->idnumber = '328327982372342343234'; $course1->summary = 'This is a summary'; $course1->summaryformat = FORMAT_HTML; $course1->format = $courseconfig->format; $course1->showgrades = $courseconfig->showgrades; $course1->showreports = $courseconfig->showreports; $course1->newsitems = $courseconfig->newsitems; $course1->startdate = time(); $course1->numsections = $courseconfig->numsections; $course1->maxbytes = $courseconfig->maxbytes; $course1->visible = $courseconfig->visible; $course1->hiddensections = $courseconfig->hiddensections; $course1->groupmode = $courseconfig->groupmode; $course1->groupmodeforce = $courseconfig->groupmodeforce; $course1->defaultgroupingid = 0; if (!empty($courseconfig->lang)) { $course1->lang = $courseconfig->lang; } $course1->enablecompletion = $courseconfig->enablecompletion; $course1->completionstartonenrol = $courseconfig->completionstartonenrol; $course1->completionnotify = 0; $course1->forcetheme = $theme; $course2 = new stdClass(); $course2->fullname = 'Test Data create course 2'; $course2->shortname = 'testdatacourse2'; $course2->categoryid = $categoryid; $courses = array($course1, $course2); //do not run the test if course1 or course2 already exists $existingcourses = $DB->get_records_list('course', 'fullname', array($course1->fullname, $course2->fullname)); if (!empty($existingcourses)) { throw new moodle_exception('testdatacoursesalreadyexist'); } $function = 'moodle_course_create_courses'; $params = array('courses' => $courses); $resultcourses = $client->call($function, $params); $this->assertEqual(count($courses), count($resultcourses)); //retrieve user1 from the DB and check values $dbcourse1 = $DB->get_record('course', array('fullname' => $course1->fullname)); $this->assertEqual($dbcourse1->fullname, $course1->fullname); $this->assertEqual($dbcourse1->shortname, $course1->shortname); $this->assertEqual($dbcourse1->category, $course1->categoryid); $this->assertEqual($dbcourse1->idnumber, $course1->idnumber); $this->assertEqual($dbcourse1->summary, $course1->summary); $this->assertEqual($dbcourse1->summaryformat, $course1->summaryformat); $this->assertEqual($dbcourse1->format, $course1->format); $this->assertEqual($dbcourse1->showgrades, $course1->showgrades); $this->assertEqual($dbcourse1->showreports, $course1->showreports); $this->assertEqual($dbcourse1->newsitems, $course1->newsitems); $this->assertEqual($dbcourse1->startdate, $course1->startdate); $this->assertEqual($dbcourse1->numsections, $course1->numsections); $this->assertEqual($dbcourse1->maxbytes, $course1->maxbytes); $this->assertEqual($dbcourse1->visible, $course1->visible); $this->assertEqual($dbcourse1->hiddensections, $course1->hiddensections); $this->assertEqual($dbcourse1->groupmode, $course1->groupmode); $this->assertEqual($dbcourse1->groupmodeforce, $course1->groupmodeforce); $this->assertEqual($dbcourse1->defaultgroupingid, $course1->defaultgroupingid); if (!empty($courseconfig->lang)) { $this->assertEqual($dbcourse1->lang, $course1->lang); } if (completion_info::is_enabled_for_site()) { $this->assertEqual($dbcourse1->enablecompletion, $course1->enablecompletion); $this->assertEqual($dbcourse1->completionstartonenrol, $course1->completionstartonenrol); } $this->assertEqual($dbcourse1->completionnotify, $course1->completionnotify); if (!empty($CFG->allowcoursethemes)) { $this->assertEqual($dbcourse1->theme, $course1->forcetheme); } //retrieve user2 from the DB and check values $dbcourse2 = $DB->get_record('course', array('fullname' => $course2->fullname)); $this->assertEqual($dbcourse2->fullname, $course2->fullname); $this->assertEqual($dbcourse2->shortname, $course2->shortname); $this->assertEqual($dbcourse2->category, $course2->categoryid); $this->assertEqual($dbcourse2->summaryformat, FORMAT_MOODLE); $this->assertEqual($dbcourse2->format, $courseconfig->format); $this->assertEqual($dbcourse2->showgrades, $courseconfig->showgrades); $this->assertEqual($dbcourse2->showreports, $courseconfig->showreports); $this->assertEqual($dbcourse2->newsitems, $courseconfig->newsitems); $this->assertEqual($dbcourse2->numsections, $courseconfig->numsections); $this->assertEqual($dbcourse2->maxbytes, $courseconfig->maxbytes); $this->assertEqual($dbcourse2->visible, $courseconfig->visible); $this->assertEqual($dbcourse2->hiddensections, $courseconfig->hiddensections); $this->assertEqual($dbcourse2->groupmode, $courseconfig->groupmode); $this->assertEqual($dbcourse2->groupmodeforce, $courseconfig->groupmodeforce); $this->assertEqual($dbcourse2->defaultgroupingid, 0); //delete users from DB $DB->delete_records_list('course', 'id', array($dbcourse1->id, $dbcourse2->id)); }
/** * Test create_courses */ public function test_create_courses() { global $DB; $this->resetAfterTest(true); // Set the required capabilities by the external function $contextid = context_system::instance()->id; $roleid = $this->assignUserCapability('moodle/course:create', $contextid); $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid); $category = self::getDataGenerator()->create_category(); // Create base categories. $course1['fullname'] = 'Test course 1'; $course1['shortname'] = 'Testcourse1'; $course1['categoryid'] = $category->id; $course2['fullname'] = 'Test course 2'; $course2['shortname'] = 'Testcourse2'; $course2['categoryid'] = $category->id; $course2['idnumber'] = 'testcourse2idnumber'; $course2['summary'] = 'Description for course 2'; $course2['summaryformat'] = FORMAT_MOODLE; $course2['format'] = 'weeks'; $course2['showgrades'] = 1; $course2['newsitems'] = 3; $course2['startdate'] = 1420092000; // 01/01/2015 $course2['numsections'] = 4; $course2['maxbytes'] = 100000; $course2['showreports'] = 1; $course2['visible'] = 0; $course2['hiddensections'] = 0; $course2['groupmode'] = 0; $course2['groupmodeforce'] = 0; $course2['defaultgroupingid'] = 0; $course2['enablecompletion'] = 1; $course2['completionstartonenrol'] = 1; $course2['completionnotify'] = 1; $course2['lang'] = 'en'; $course2['forcetheme'] = 'base'; $courses = array($course1, $course2); $createdcourses = core_course_external::create_courses($courses); // Check that right number of courses were created. $this->assertEquals(2, count($createdcourses)); // Check that the courses were correctly created. foreach ($createdcourses as $createdcourse) { $dbcourse = $DB->get_record('course', array('id' => $createdcourse['id'])); if ($createdcourse['shortname'] == $course2['shortname']) { $this->assertEquals($dbcourse->fullname, $course2['fullname']); $this->assertEquals($dbcourse->shortname, $course2['shortname']); $this->assertEquals($dbcourse->category, $course2['categoryid']); $this->assertEquals($dbcourse->idnumber, $course2['idnumber']); $this->assertEquals($dbcourse->summary, $course2['summary']); $this->assertEquals($dbcourse->summaryformat, $course2['summaryformat']); $this->assertEquals($dbcourse->format, $course2['format']); $this->assertEquals($dbcourse->showgrades, $course2['showgrades']); $this->assertEquals($dbcourse->newsitems, $course2['newsitems']); $this->assertEquals($dbcourse->startdate, $course2['startdate']); $this->assertEquals($dbcourse->numsections, $course2['numsections']); $this->assertEquals($dbcourse->maxbytes, $course2['maxbytes']); $this->assertEquals($dbcourse->showreports, $course2['showreports']); $this->assertEquals($dbcourse->visible, $course2['visible']); $this->assertEquals($dbcourse->hiddensections, $course2['hiddensections']); $this->assertEquals($dbcourse->groupmode, $course2['groupmode']); $this->assertEquals($dbcourse->groupmodeforce, $course2['groupmodeforce']); $this->assertEquals($dbcourse->defaultgroupingid, $course2['defaultgroupingid']); $this->assertEquals($dbcourse->completionnotify, $course2['completionnotify']); $this->assertEquals($dbcourse->lang, $course2['lang']); if (!empty($CFG->allowcoursethemes)) { $this->assertEquals($dbcourse->theme, $course2['forcetheme']); } if (completion_info::is_enabled_for_site()) { $this->assertEquals($dbcourse->enablecompletion, $course2['enabledcompletion']); $this->assertEquals($dbcourse->completionstartonenrol, $course2['completionstartonenrol']); } else { $this->assertEquals($dbcourse->enablecompletion, 0); $this->assertEquals($dbcourse->completionstartonenrol, 0); } } else { if ($createdcourse['shortname'] == $course1['shortname']) { $courseconfig = get_config('moodlecourse'); $this->assertEquals($dbcourse->fullname, $course1['fullname']); $this->assertEquals($dbcourse->shortname, $course1['shortname']); $this->assertEquals($dbcourse->category, $course1['categoryid']); $this->assertEquals($dbcourse->summaryformat, FORMAT_HTML); $this->assertEquals($dbcourse->format, $courseconfig->format); $this->assertEquals($dbcourse->showgrades, $courseconfig->showgrades); $this->assertEquals($dbcourse->newsitems, $courseconfig->newsitems); $this->assertEquals($dbcourse->numsections, $courseconfig->numsections); $this->assertEquals($dbcourse->maxbytes, $courseconfig->maxbytes); $this->assertEquals($dbcourse->showreports, $courseconfig->showreports); $this->assertEquals($dbcourse->hiddensections, $courseconfig->hiddensections); $this->assertEquals($dbcourse->groupmode, $courseconfig->groupmode); $this->assertEquals($dbcourse->groupmodeforce, $courseconfig->groupmodeforce); $this->assertEquals($dbcourse->defaultgroupingid, 0); } else { throw moodle_exception('Unexpected shortname'); } } } // Call without required capability $this->unassignUserCapability('moodle/course:create', $contextid, $roleid); $this->setExpectedException('required_capability_exception'); $createdsubcats = core_course_external::create_courses($courses); }
/** * Used to notify the completion system (if necessary) that a user's grade * has changed, and clear up a possible score cache. * * @param bool $deleted True if grade was actually deleted */ function notify_changed($deleted) { global $USER, $SESSION, $CFG, $COURSE, $DB; // Grades may be cached in user session if ($USER->id == $this->userid) { unset($SESSION->gradescorecache[$this->itemid]); } require_once $CFG->libdir . '/completionlib.php'; // Bail out immediately if completion is not enabled for site (saves loading // grade item & requiring the restore stuff). if (!completion_info::is_enabled_for_site()) { return; } // Ignore during restore, as completion data will be updated anyway and // doing it now will result in incorrect dates (it will say they got the // grade completion now, instead of the correct time). if (class_exists('restore_controller', false) && restore_controller::is_executing()) { return; } // Load information about grade item $this->load_grade_item(); // Only course-modules have completion data if ($this->grade_item->itemtype != 'mod') { return; } // Use $COURSE if available otherwise get it via item fields if (!empty($COURSE) && $COURSE->id == $this->grade_item->courseid) { $course = $COURSE; } else { $course = $DB->get_record('course', array('id' => $this->grade_item->courseid)); } // Bail out if completion is not enabled for course $completion = new completion_info($course); if (!$completion->is_enabled()) { return; } // Get course-module $cm = get_coursemodule_from_instance($this->grade_item->itemmodule, $this->grade_item->iteminstance, $this->grade_item->courseid); // If the course-module doesn't exist, display a warning... if (!$cm) { // ...unless the grade is being deleted in which case it's likely // that the course-module was just deleted too, so that's okay. if (!$deleted) { debugging("Couldn't find course-module for module '" . $this->grade_item->itemmodule . "', instance '" . $this->grade_item->iteminstance . "', course '" . $this->grade_item->courseid . "'"); } return; } // Pass information on to completion system $completion->inform_grade_changed($cm, $this->grade_item, $this, $deleted); }
function xmldb_core_install() { global $CFG, $DB, $SITE; // switch to new default theme set_config('theme', 'standard'); $dbman = $DB->get_manager(); // loads ddl manager and xmldb classes $systemcontext = context_system::instance(); // add coursetype and icon fields to course table $table = new xmldb_table('course'); $field = new xmldb_field('coursetype'); if (!$dbman->field_exists($table, $field)) { $field->set_attributes(XMLDB_TYPE_INTEGER, '4', null, null, null, null, null); $dbman->add_field($table, $field); } $field = new xmldb_field('icon'); if (!$dbman->field_exists($table, $field)) { $field->set_attributes(XMLDB_TYPE_CHAR, '255', null, null, null, null); $dbman->add_field($table, $field); } // rename the moodle 'manager' fullname to "Site Manager" to make it // distinct from the "Staff Manager" if ($managerroleid = $DB->get_field('role', 'id', array('shortname' => 'manager', 'name' => get_string('manager', 'role')))) { $todb = new stdClass(); $todb->id = $managerroleid; $todb->name = get_string('sitemanager', 'local_core'); $DB->update_record('role', $todb); } // Create roles. $manager = $DB->get_record('role', array('shortname' => 'manager')); $managerrole = $manager->id; $staffmanagerrole = create_role('', 'staffmanager', '', 'staffmanager'); $assessorrole = create_role('', 'assessor', '', 'assessor'); $regionalmanagerrole = create_role('', 'regionalmanager', ''); $regionaltrainerrole = create_role('', 'regionaltrainer', ''); $defaultallowassigns = array( array($managerrole, $staffmanagerrole), array($managerrole, $assessorrole), array($managerrole, $regionalmanagerrole), array($managerrole, $regionaltrainerrole) ); foreach ($defaultallowassigns as $allow) { list($fromroleid, $toroleid) = $allow; allow_assign($fromroleid, $toroleid); } $defaultallowoverrides = array( array($managerrole, $staffmanagerrole), array($managerrole, $assessorrole), array($managerrole, $regionalmanagerrole), array($managerrole, $regionaltrainerrole) ); foreach ($defaultallowoverrides as $allow) { list($fromroleid, $toroleid) = $allow; allow_override($fromroleid, $toroleid); // There is a rant about this in MDL-15841. } $defaultallowswitch = array( array($managerrole, $staffmanagerrole), ); foreach ($defaultallowswitch as $allow) { list($fromroleid, $toroleid) = $allow; allow_switch($fromroleid, $toroleid); } set_role_contextlevels($staffmanagerrole, get_default_contextlevels('staffmanager')); assign_capability('moodle/user:viewdetails', CAP_ALLOW, $staffmanagerrole, $systemcontext->id, true); assign_capability('moodle/user:viewuseractivitiesreport', CAP_ALLOW, $staffmanagerrole, $systemcontext->id, true); assign_capability('moodle/cohort:view', CAP_ALLOW, $staffmanagerrole, $systemcontext->id, true); assign_capability('moodle/comment:view', CAP_ALLOW, $staffmanagerrole, $systemcontext->id, true); assign_capability('moodle/comment:delete', CAP_ALLOW, $staffmanagerrole, $systemcontext->id, true); assign_capability('moodle/comment:post', CAP_ALLOW, $staffmanagerrole, $systemcontext->id, true); $systemcontext->mark_dirty(); set_role_contextlevels($assessorrole, get_default_contextlevels('teacher')); $role_to_modify = array( 'editingteacher' => 'editingtrainer', 'teacher' => 'trainer', 'student' => 'learner' ); $DB->update_record('role', array('id' => $assessorrole, 'archetype' => 'assessor')); assign_capability('moodle/user:editownprofile', CAP_ALLOW, $assessorrole, $systemcontext->id, true); assign_capability('moodle/user:editownprofile', CAP_ALLOW, $regionalmanagerrole, $systemcontext->id, true); assign_capability('moodle/user:editownprofile', CAP_ALLOW, $regionaltrainerrole, $systemcontext->id, true); foreach ($role_to_modify as $old => $new) { if ($old_role = $DB->get_record('role', array('shortname' => $old))) { $new_role = new stdClass(); $new_role->id = $old_role->id; $new_role->name = ''; $new_role->description = ''; $DB->update_record('role', $new_role); } } // Set up frontpage. set_config('frontpage', ''); set_config('frontpageloggedin', ''); require_once($CFG->dirroot . '/lib/completionlib.php'); if(!completion_info::is_enabled_for_site()){ set_config('coreinstallation', 1); set_config('enablecompletion', 1); set_config('enablecompletion', 1, 'moodlecourse'); set_config('completionstartonenrol', 1, 'moodlecourse'); } // Add completionstartonenrol column to course table. $table = new xmldb_table('course'); // Define field completionstartonenrol to be added to course. $field = new xmldb_field('completionstartonenrol', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0'); // Conditionally launch add field completionstartonenrol. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Add RPL column to course_completions table $table = new xmldb_table('course_completions'); // Define field rpl to be added to course_completions $field = new xmldb_field('rpl', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'reaggregate'); // Conditionally launch add field rpl if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Define field rplgrade to be added to course_completions $field = new xmldb_field('rplgrade', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null, 'rpl'); // Conditionally launch add field rpl if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Add RPL column to course_completion_crit_compl table $table = new xmldb_table('course_completion_crit_compl'); // Define field rpl to be added to course_completion_crit_compl $field = new xmldb_field('rpl', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'unenroled'); // Conditionally launch add field rpl if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Define fields status and renewalstatus to be added to course_completions. $table = new xmldb_table('course_completions'); $field = new xmldb_field('status', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0'); // Conditionally launch add field status. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } $field = new xmldb_field('renewalstatus', XMLDB_TYPE_INTEGER, '2', null, null, null, '0'); // Conditionally launch add field renewalstatus. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } rebuild_course_cache($SITE->id, true); // readd specific course completion changes for anyone // upgrading from moodle 2.2.2+ require_once($CFG->dirroot . '/local/core/db/utils.php'); local_readd_course_completion_changes(); // remove any references to "complete on unenrolment" critiera type // these could exist in an upgrade from moodle 2.2 but the criteria $DB->delete_records('course_completion_criteria', array('criteriatype' => 3)); //disable autoupdate notifications from Moodle set_config('disableupdatenotifications', '1'); set_config('disableupdateautodeploy', '1'); set_config('updateautodeploy', false); set_config('updateautocheck', false); set_config('updatenotifybuilds', false); // Disable editing execpaths by default for security. set_config('preventexecpath', '1'); // Then provide default values to prevent them appearing on the upgradesettings page. set_config('geoipfile', $CFG->dataroot . 'geoip/GeoLiteCity.dat'); set_config('location', '', 'enrol_flatfile'); set_config('filter_tex_pathlatex', '/usr/bin/latex'); set_config('filter_tex_pathdvips', '/usr/bin/dvips'); set_config('filter_tex_pathconvert', '/usr/bin/convert'); set_config('pathtodu', ''); set_config('pathtoclam', ''); set_config('aspellpath', ''); set_config('pathtodot', ''); set_config('quarantinedir', ''); set_config('backup_auto_destination', '', 'backup'); // Adding some upgrade code from lib/db/upgrade.php to // avoid conflicts every time we upgrade moodle. // This can be removed once we reach the verion of Moodle that // includes this functionality. E.g. 2.5 for badges, 2.6? for // course completion. // Add openbadges tables. // Define table 'badge' to be created $table = new xmldb_table('badge'); // Adding fields to table 'badge' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'id'); $table->add_field('description', XMLDB_TYPE_TEXT, null, null, null, null, null, 'name'); $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'description'); $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated'); $table->add_field('usercreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'timemodified'); $table->add_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'usercreated'); $table->add_field('issuername', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'usermodified'); $table->add_field('issuerurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'issuername'); $table->add_field('issuercontact', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'issuerurl'); $table->add_field('expiredate', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'issuercontact'); $table->add_field('expireperiod', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'expiredate'); $table->add_field('type', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'expireperiod'); $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'type'); $table->add_field('message', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'courseid'); $table->add_field('messagesubject', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'message'); $table->add_field('attachment', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'messagesubject'); $table->add_field('notification', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'attachment'); $table->add_field('status', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'notification'); $table->add_field('nextcron', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'status'); // Adding keys to table 'badge' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id')); $table->add_key('fk_usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id')); $table->add_key('fk_usercreated', XMLDB_KEY_FOREIGN, array('usercreated'), 'user', array('id')); // Adding indexes to table 'badge' $table->add_index('type', XMLDB_INDEX_NOTUNIQUE, array('type')); // Set the comment for the table 'badge'. $table->setComment('Defines badge'); // Conditionally launch create table for 'badge' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define table 'badge_criteria' to be created $table = new xmldb_table('badge_criteria'); // Adding fields to table 'badge_criteria' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id'); $table->add_field('criteriatype', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'badgeid'); $table->add_field('method', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'criteriatype'); // Adding keys to table 'badge_criteria' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id')); // Adding indexes to table 'badge_criteria' $table->add_index('criteriatype', XMLDB_INDEX_NOTUNIQUE, array('criteriatype')); $table->add_index('badgecriteriatype', XMLDB_INDEX_UNIQUE, array('badgeid', 'criteriatype')); // Set the comment for the table 'badge_criteria'. $table->setComment('Defines criteria for issuing badges'); // Conditionally launch create table for 'badge_criteria' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define table 'badge_criteria_param' to be created $table = new xmldb_table('badge_criteria_param'); // Adding fields to table 'badge_criteria_param' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('critid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'critid'); $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'name'); // Adding keys to table 'badge_criteria_param' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_critid', XMLDB_KEY_FOREIGN, array('critid'), 'badge_criteria', array('id')); // Set the comment for the table 'badge_criteria_param'. $table->setComment('Defines parameters for badges criteria'); // Conditionally launch create table for 'badge_criteria_param' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define table 'badge_issued' to be created $table = new xmldb_table('badge_issued'); // Adding fields to table 'badge_issued' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id'); $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'badgeid'); $table->add_field('uniquehash', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'userid'); $table->add_field('dateissued', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'uniquehash'); $table->add_field('dateexpire', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'dateissued'); $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'dateexpire'); $table->add_field('issuernotified', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'visible'); // Adding keys to table 'badge_issued' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id')); $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); // Adding indexes to table 'badge_issued' $table->add_index('badgeuser', XMLDB_INDEX_UNIQUE, array('badgeid', 'userid')); // Set the comment for the table 'badge_issued'. $table->setComment('Defines issued badges'); // Conditionally launch create table for 'badge_issued' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define table 'badge_criteria_met' to be created $table = new xmldb_table('badge_criteria_met'); // Adding fields to table 'badge_criteria_met' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('issuedid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'id'); $table->add_field('critid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuedid'); $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'critid'); $table->add_field('datemet', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'userid'); // Adding keys to table 'badge_criteria_met' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_critid', XMLDB_KEY_FOREIGN, array('critid'), 'badge_criteria', array('id')); $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); $table->add_key('fk_issuedid', XMLDB_KEY_FOREIGN, array('issuedid'), 'badge_issued', array('id')); // Set the comment for the table 'badge_criteria_met'. $table->setComment('Defines criteria that were met for an issued badge'); // Conditionally launch create table for 'badge_criteria_met' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define table 'badge_manual_award' to be created $table = new xmldb_table('badge_manual_award'); // Adding fields to table 'badge_manual_award' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id'); $table->add_field('recipientid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'badgeid'); $table->add_field('issuerid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'recipientid'); $table->add_field('issuerrole', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuerid'); $table->add_field('datemet', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuerrole'); // Adding keys to table 'badge_manual_award' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id')); $table->add_key('fk_recipientid', XMLDB_KEY_FOREIGN, array('recipientid'), 'user', array('id')); $table->add_key('fk_issuerid', XMLDB_KEY_FOREIGN, array('issuerid'), 'user', array('id')); $table->add_key('fk_issuerrole', XMLDB_KEY_FOREIGN, array('issuerrole'), 'role', array('id')); // Set the comment for the table 'badge_manual_award'. $table->setComment('Track manual award criteria for badges'); // Conditionally launch create table for 'badge_manual_award' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define table 'badge_backpack' to be created $table = new xmldb_table('badge_backpack'); // Adding fields to table 'badge_backpack' $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id'); $table->add_field('email', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'userid'); $table->add_field('backpackurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'email'); $table->add_field('backpackuid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackurl'); $table->add_field('backpackgid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackuid'); $table->add_field('autosync', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'backpackgid'); $table->add_field('password', XMLDB_TYPE_CHAR, '50', null, null, null, null, 'autosync'); // Adding keys to table 'badge_backpack' $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); // Set the comment for the table 'badge_backpack'. $table->setComment('Defines settings for connecting external backpack'); // Conditionally launch create table for 'badge_backpack' if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Create a new 'badge_external' table first. // Define table 'badge_external' to be created. $table = new xmldb_table('badge_external'); // Adding fields to table 'badge_external'. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('backpackid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id'); $table->add_field('collectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackid'); // Adding keys to table 'badge_external'. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('fk_backpackid', XMLDB_KEY_FOREIGN, array('backpackid'), 'badge_backpack', array('id')); // Set the comment for the table 'badge_external'. $table->setComment('Setting for external badges display'); // Conditionally launch create table for 'badge_external'. if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Define field backpackgid to be dropped from 'badge_backpack'. $table = new xmldb_table('badge_backpack'); $field = new xmldb_field('backpackgid'); if ($dbman->field_exists($table, $field)) { // Perform user data migration. $usercollections = $DB->get_records('badge_backpack'); foreach ($usercollections as $usercollection) { $collection = new stdClass(); $collection->backpackid = $usercollection->id; $collection->collectionid = $usercollection->backpackgid; $DB->insert_record('badge_external', $collection); } // Launch drop field backpackgid. $dbman->drop_field($table, $field); } // Create missing badgeid foreign key on badge_manual_award. $table = new xmldb_table('badge_manual_award'); $key = new xmldb_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('id'), 'badge', array('id')); $dbman->drop_key($table, $key); $key->set_attributes(XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id')); $dbman->add_key($table, $key); // Drop unused badge image field. $table = new xmldb_table('badge'); $field = new xmldb_field('image', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'description'); // Conditionally launch drop field eventtype. if ($dbman->field_exists($table, $field)) { $dbman->drop_field($table, $field); } // Define field completionprogressonview to be added to course. $table = new xmldb_table('course'); $field = new xmldb_field('completionprogressonview', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 0, 'enablecompletion'); // Conditionally launch add field completionprogressonview. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } $field = new xmldb_field('audiencevisible', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, 2); // Conditionally launch add field audiencevisible to course table. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Define field invalidatecache to be added to course_completions. $table = new xmldb_table('course_completions'); $field = new xmldb_field('invalidatecache', XMLDB_TYPE_INTEGER, '1', null, null, null, '0'); // Conditionally launch add field invalidatecache. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Backporting MDL-41914 to add new webservice core_user_add_user_device. $table = new xmldb_table('user_devices'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null); $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id'); $table->add_field('appid', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, 'userid'); $table->add_field('name', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'appid'); $table->add_field('model', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'name'); $table->add_field('platform', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'model'); $table->add_field('version', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'platform'); $table->add_field('pushid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'version'); $table->add_field('uuid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'pushid'); $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'uuid'); $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'timecreated'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_key('pushid-userid', XMLDB_KEY_UNIQUE, array('pushid', 'userid')); $table->add_key('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform')); $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id')); if (!$dbman->table_exists($table)) { $dbman->create_table($table); } // Add timecompleted for module completion. $table = new xmldb_table('course_modules_completion'); $field = new xmldb_field('timecompleted', XMLDB_TYPE_INTEGER, '10'); if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } return true; }
/** * Utility function for checking if the logged in user can view * another's completion data for a particular course * * @access public * @param int $userid Completion data's owner * @param mixed $course Course object or Course ID (optional) * @return boolean */ function completion_can_view_data($userid, $course = null) { global $USER; if (!isloggedin()) { return false; } if (!is_object($course)) { $cid = $course; $course = new object(); $course->id = $cid; } // Check if this is the site course if ($course->id == SITEID) { $course = null; } // Check if completion is enabled if ($course) { $cinfo = new completion_info($course); if (!$cinfo->is_enabled()) { return false; } } else { if (!completion_info::is_enabled_for_site()) { return false; } } // Is own user's data? if ($USER->id == $userid) { return true; } // Check capabilities $personalcontext = context_user::instance($userid); if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) { return true; } elseif (has_capability('report/completion:view', $personalcontext)) { return true; } if ($course->id) { $coursecontext = context_course::instance($course->id); } else { $coursecontext = context_system::instance(); } if (has_capability('report/completion:view', $coursecontext)) { return true; } return false; }
/** * Test update_courses */ public function test_update_courses() { global $DB, $CFG, $USER, $COURSE; // Get current $COURSE to be able to restore it later (defaults to $SITE). We need this // trick because we are both updating and getting (for testing) course information // in the same request and core_course_external::update_courses() // is overwriting $COURSE all over the time with OLD values, so later // use of get_course() fetches those OLD values instead of the updated ones. // See MDL-39723 for more info. $origcourse = clone $COURSE; $this->resetAfterTest(true); // Set the required capabilities by the external function. $contextid = context_system::instance()->id; $roleid = $this->assignUserCapability('moodle/course:update', $contextid); $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid); $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid); $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid); $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid); $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid); $this->assignUserCapability('moodle/course:visibility', $contextid, $roleid); $this->assignUserCapability('moodle/course:viewhiddencourses', $contextid, $roleid); // Create category and course. $category1 = self::getDataGenerator()->create_category(); $category2 = self::getDataGenerator()->create_category(); $originalcourse1 = self::getDataGenerator()->create_course(); self::getDataGenerator()->enrol_user($USER->id, $originalcourse1->id, $roleid); $originalcourse2 = self::getDataGenerator()->create_course(); self::getDataGenerator()->enrol_user($USER->id, $originalcourse2->id, $roleid); // Course values to be updated. $course1['id'] = $originalcourse1->id; $course1['fullname'] = 'Updated test course 1'; $course1['shortname'] = 'Udestedtestcourse1'; $course1['categoryid'] = $category1->id; $course2['id'] = $originalcourse2->id; $course2['fullname'] = 'Updated test course 2'; $course2['shortname'] = 'Updestedtestcourse2'; $course2['categoryid'] = $category2->id; $course2['idnumber'] = 'Updatedidnumber2'; $course2['summary'] = 'Updaated description for course 2'; $course2['summaryformat'] = FORMAT_HTML; $course2['format'] = 'topics'; $course2['showgrades'] = 1; $course2['newsitems'] = 3; $course2['startdate'] = 1420092000; // 01/01/2015. $course2['numsections'] = 4; $course2['maxbytes'] = 100000; $course2['showreports'] = 1; $course2['visible'] = 0; $course2['hiddensections'] = 0; $course2['groupmode'] = 0; $course2['groupmodeforce'] = 0; $course2['defaultgroupingid'] = 0; $course2['enablecompletion'] = 1; $course2['lang'] = 'en'; $course2['forcetheme'] = 'base'; $courses = array($course1, $course2); $updatedcoursewarnings = core_course_external::update_courses($courses); $COURSE = $origcourse; // Restore $COURSE. Instead of using the OLD one set by the previous line. // Check that right number of courses were created. $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); // Check that the courses were correctly created. foreach ($courses as $course) { $courseinfo = course_get_format($course['id'])->get_course(); if ($course['id'] == $course2['id']) { $this->assertEquals($course2['fullname'], $courseinfo->fullname); $this->assertEquals($course2['shortname'], $courseinfo->shortname); $this->assertEquals($course2['categoryid'], $courseinfo->category); $this->assertEquals($course2['idnumber'], $courseinfo->idnumber); $this->assertEquals($course2['summary'], $courseinfo->summary); $this->assertEquals($course2['summaryformat'], $courseinfo->summaryformat); $this->assertEquals($course2['format'], $courseinfo->format); $this->assertEquals($course2['showgrades'], $courseinfo->showgrades); $this->assertEquals($course2['newsitems'], $courseinfo->newsitems); $this->assertEquals($course2['startdate'], $courseinfo->startdate); $this->assertEquals($course2['numsections'], $courseinfo->numsections); $this->assertEquals($course2['maxbytes'], $courseinfo->maxbytes); $this->assertEquals($course2['showreports'], $courseinfo->showreports); $this->assertEquals($course2['visible'], $courseinfo->visible); $this->assertEquals($course2['hiddensections'], $courseinfo->hiddensections); $this->assertEquals($course2['groupmode'], $courseinfo->groupmode); $this->assertEquals($course2['groupmodeforce'], $courseinfo->groupmodeforce); $this->assertEquals($course2['defaultgroupingid'], $courseinfo->defaultgroupingid); $this->assertEquals($course2['lang'], $courseinfo->lang); if (!empty($CFG->allowcoursethemes)) { $this->assertEquals($course2['forcetheme'], $courseinfo->theme); } if (completion_info::is_enabled_for_site()) { $this->assertEquals($course2['enabledcompletion'], $courseinfo->enablecompletion); } } else { if ($course['id'] == $course1['id']) { $this->assertEquals($course1['fullname'], $courseinfo->fullname); $this->assertEquals($course1['shortname'], $courseinfo->shortname); $this->assertEquals($course1['categoryid'], $courseinfo->category); $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat); $this->assertEquals('topics', $courseinfo->format); $this->assertEquals(5, $courseinfo->numsections); $this->assertEquals(0, $courseinfo->newsitems); $this->assertEquals(FORMAT_MOODLE, $courseinfo->summaryformat); } else { throw moodle_exception('Unexpected shortname'); } } } $courses = array($course1); // Try update course without update capability. $user = self::getDataGenerator()->create_user(); $this->setUser($user); $this->unassignUserCapability('moodle/course:update', $contextid, $roleid); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course category without capability. $this->assignUserCapability('moodle/course:update', $contextid, $roleid); $this->unassignUserCapability('moodle/course:changecategory', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $course1['categoryid'] = $category2->id; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course fullname without capability. $this->assignUserCapability('moodle/course:changecategory', $contextid, $roleid); $this->unassignUserCapability('moodle/course:changefullname', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); $course1['fullname'] = 'Testing fullname without permission'; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course shortname without capability. $this->assignUserCapability('moodle/course:changefullname', $contextid, $roleid); $this->unassignUserCapability('moodle/course:changeshortname', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); $course1['shortname'] = 'Testing shortname without permission'; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course idnumber without capability. $this->assignUserCapability('moodle/course:changeshortname', $contextid, $roleid); $this->unassignUserCapability('moodle/course:changeidnumber', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); $course1['idnumber'] = 'NEWIDNUMBER'; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course summary without capability. $this->assignUserCapability('moodle/course:changeidnumber', $contextid, $roleid); $this->unassignUserCapability('moodle/course:changesummary', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); $course1['summary'] = 'New summary'; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course with invalid summary format. $this->assignUserCapability('moodle/course:changesummary', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); $course1['summaryformat'] = 10; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); // Try update course visibility without capability. $this->unassignUserCapability('moodle/course:visibility', $contextid, $roleid); $user = self::getDataGenerator()->create_user(); $this->setUser($user); self::getDataGenerator()->enrol_user($user->id, $course1['id'], $roleid); $course1['summaryformat'] = FORMAT_MOODLE; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(0, count($updatedcoursewarnings['warnings'])); $course1['visible'] = 0; $courses = array($course1); $updatedcoursewarnings = core_course_external::update_courses($courses); $this->assertEquals(1, count($updatedcoursewarnings['warnings'])); }
/** * Create courses * * @param array $courses * @return array courses (id and shortname only) * @since Moodle 2.2 */ public static function create_courses($courses) { global $CFG, $DB; require_once $CFG->dirroot . "/course/lib.php"; require_once $CFG->libdir . '/completionlib.php'; $params = self::validate_parameters(self::create_courses_parameters(), array('courses' => $courses)); $availablethemes = get_plugin_list('theme'); $availablelangs = get_string_manager()->get_list_of_translations(); $transaction = $DB->start_delegated_transaction(); foreach ($params['courses'] as $course) { // Ensure the current user is allowed to run this function $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING); try { self::validate_context($context); } catch (Exception $e) { $exceptionparam = new stdClass(); $exceptionparam->message = $e->getMessage(); $exceptionparam->catid = $course['categoryid']; throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam); } require_capability('moodle/course:create', $context); // Make sure lang is valid if (key_exists('lang', $course) and empty($availablelangs[$course['lang']])) { throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang'); } // Make sure theme is valid if (key_exists('forcetheme', $course)) { if (!empty($CFG->allowcoursethemes)) { if (empty($availablethemes[$course['forcetheme']])) { throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme'); } else { $course['theme'] = $course['forcetheme']; } } } //force visibility if ws user doesn't have the permission to set it $category = $DB->get_record('course_categories', array('id' => $course['categoryid'])); if (!has_capability('moodle/course:visibility', $context)) { $course['visible'] = $category->visible; } //set default value for completion $courseconfig = get_config('moodlecourse'); if (completion_info::is_enabled_for_site()) { if (!key_exists('enablecompletion', $course)) { $course['enablecompletion'] = $courseconfig->enablecompletion; } if (!key_exists('completionstartonenrol', $course)) { $course['completionstartonenrol'] = $courseconfig->completionstartonenrol; } } else { $course['enablecompletion'] = 0; $course['completionstartonenrol'] = 0; } $course['category'] = $course['categoryid']; // Summary format. $course['summaryformat'] = external_validate_format($course['summaryformat']); //Note: create_course() core function check shortname, idnumber, category $course['id'] = create_course((object) $course)->id; $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']); } $transaction->allow_commit(); return $resultcourses; }
/** * Used to notify the completion system (if necessary) that a user's grade * has changed, and clear up a possible score cache. * @param bool deleted True if grade was actually deleted */ function notify_changed($deleted) { global $USER, $SESSION, $CFG, $COURSE, $DB; // Grades may be cached in user session if ($USER->id == $this->userid) { unset($SESSION->gradescorecache[$this->itemid]); } // Ignore during restore // TODO There should be a proper way to determine when we are in restore // so that this hack looking for a $restore global is not needed. global $restore; if (!empty($restore->backup_unique_code)) { return; } require_once $CFG->libdir . '/completionlib.php'; // Bail out immediately if completion is not enabled for site (saves loading // grade item below) if (!completion_info::is_enabled_for_site()) { return; } // Load information about grade item $this->load_grade_item(); // Only course-modules have completion data if ($this->grade_item->itemtype != 'mod') { return; } // Use $COURSE if available otherwise get it via item fields if (!empty($COURSE) && $COURSE->id == $this->grade_item->courseid) { $course = $COURSE; } else { $course = $DB->get_record('course', array('id' => $this->grade_item->courseid)); } // Bail out if completion is not enabled for course $completion = new completion_info($course); if (!$completion->is_enabled()) { return; } // Get course-module $cm = get_coursemodule_from_instance($this->grade_item->itemmodule, $this->grade_item->iteminstance, $this->grade_item->courseid); if (!$cm) { debugging("Couldn't find course-module for module\n '{$this->grade_item->itemmodule}', instance '{$this->grade_item->iteminstance}',\n course '{$this->grade_item->courseid}'"); return; } // Pass information on to completion system $completion->inform_grade_changed($cm, $this->grade_item, $this, $deleted); }
function definition() { global $USER, $CFG, $DB; $courseconfig = get_config('moodlecourse'); $mform =& $this->_form; $course = $this->_customdata['course']; $category = $this->_customdata['category']; $systemcontext = get_context_instance(CONTEXT_SYSTEM); $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id); $disable_meta = false; // basic meta course state protection; server-side security checks not needed if (!empty($course)) { $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $context = $coursecontext; if (course_in_meta($course)) { $disable_meta = get_string('metaalreadyinmeta'); } else { if ($course->metacourse) { if ($DB->count_records('course_meta', array('parent_course' => $course->id)) > 0) { $disable_meta = get_string('metaalreadyhascourses'); } } else { // if users already enrolled directly into coures, do not allow switching to meta, // users with metacourse manage permission are exception // please note that we do not need exact results - anything unexpected here prevents metacourse $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id'); $enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext); if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) { foreach ($users as $user) { if (!isset($managers[$user->id])) { $disable_meta = get_string('metaalreadyhasenrolments'); break; } } } unset($managers); unset($users); unset($enrolroles); } } } else { $coursecontext = null; $context = $categorycontext; } /// form definition with new course defaults //-------------------------------------------------------------------------------- $mform->addElement('header', 'general', get_string('general', 'form')); // Must have create course capability in both categories in order to move course if (has_capability('moodle/course:create', $categorycontext)) { $displaylist = array(); $parentlist = array(); make_categories_list($displaylist, $parentlist, 'moodle/course:create'); $mform->addElement('select', 'category', get_string('category'), $displaylist); } else { $mform->addElement('hidden', 'category', null); } $mform->setHelpButton('category', array('coursecategory', get_string('category'))); $mform->setDefault('category', $category->id); $mform->setType('category', PARAM_INT); $fullname = get_string('defaultcoursefullname'); $shortname = get_string('defaultcourseshortname'); while ($DB->record_exists('course', array('fullname' => $fullname)) or $DB->record_exists('course', array('fullname' => $fullname))) { $fullname++; $shortname++; } $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"'); $mform->setHelpButton('fullname', array('coursefullname', get_string('fullnamecourse')), true); $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client'); $mform->setType('fullname', PARAM_MULTILANG); if ($course and !has_capability('moodle/course:changefullname', $coursecontext)) { $mform->hardFreeze('fullname'); $mform->setConstant('fullname', $course->fullname); } $mform->setDefault('fullname', $fullname); $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"'); $mform->setHelpButton('shortname', array('courseshortname', get_string('shortnamecourse')), true); $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client'); $mform->setType('shortname', PARAM_MULTILANG); if ($course and !has_capability('moodle/course:changeshortname', $coursecontext)) { $mform->hardFreeze('shortname'); $mform->setConstant('shortname', $course->shortname); } $mform->setDefault('shortname', $shortname); $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100" size="10"'); $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true); $mform->setType('idnumber', PARAM_RAW); if ($course and !has_capability('moodle/course:changeidnumber', $coursecontext)) { $mform->hardFreeze('idnumber'); $mform->setConstants('idnumber', $course->idnumber); } $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65')); $mform->setHelpButton('summary', array('text2', get_string('helptext')), true); $mform->setType('summary', PARAM_RAW); $courseformats = get_list_of_plugins('course/format'); $formcourseformats = array(); foreach ($courseformats as $courseformat) { $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}"); if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") { $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}"); } } $mform->addElement('select', 'format', get_string('format'), $formcourseformats); $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true); $mform->setDefault('format', $courseconfig->format); for ($i = 1; $i <= 52; $i++) { $sectionmenu[$i] = "{$i}"; } $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu); $mform->setDefault('numsections', $courseconfig->numsections); $mform->addElement('date_selector', 'startdate', get_string('startdate')); $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true); $mform->setDefault('startdate', time() + 3600 * 24); $choices = array(); $choices['0'] = get_string('hiddensectionscollapsed'); $choices['1'] = get_string('hiddensectionsinvisible'); $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices); $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true); $mform->setDefault('hiddensections', $courseconfig->hiddensections); $options = range(0, 10); $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options); $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true); $mform->setDefault('newsitems', $courseconfig->newsitems); $mform->addElement('selectyesno', 'showgrades', get_string('showgrades')); $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true); $mform->setDefault('showgrades', $courseconfig->showgrades); $mform->addElement('selectyesno', 'showreports', get_string('showreports')); $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true); $mform->setDefault('showreports', $courseconfig->showreports); $choices = get_max_upload_sizes($CFG->maxbytes); $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices); $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true); $mform->setDefault('maxbytes', $courseconfig->maxbytes); if (!empty($CFG->allowcoursethemes)) { $themes = array(); $themes[''] = get_string('forceno'); $themes += get_list_of_themes(); $mform->addElement('select', 'theme', get_string('forcetheme'), $themes); } $meta = array(); $meta[0] = get_string('no'); $meta[1] = get_string('yes'); if ($disable_meta === false) { $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta); $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true); $mform->setDefault('metacourse', $courseconfig->metacourse); } else { // no metacourse element - we do not want to change it anyway! $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} "); $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true); } //-------------------------------------------------------------------------------- $mform->addElement('header', 'enrolhdr', get_string('enrolments')); $choices = array(); $modules = explode(',', $CFG->enrol_plugins_enabled); foreach ($modules as $module) { $name = get_string('enrolname', "enrol_{$module}"); $plugin = enrolment_factory::factory($module); if (method_exists($plugin, 'print_entry')) { $choices[$name] = $module; } } asort($choices); $choices = array_flip($choices); $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices); $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices); $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true); $mform->setDefault('enrol', $courseconfig->enrol); $roles = get_assignable_roles($context); if (!empty($course)) { // add current default role, so that it is selectable even when user can not assign it if ($current_role = $DB->get_record('role', array('id' => $course->defaultrole))) { $roles[$current_role->id] = strip_tags(format_string($current_role->name, true)); } } $choices = array(); if ($sitedefaultrole = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) { $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')'; } else { $choices[0] = get_string('sitedefault'); } $choices = $choices + $roles; // fix for MDL-9197 foreach ($choices as $choiceid => $choice) { $choices[$choiceid] = format_string($choice); } $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices); $mform->setDefault('defaultrole', 0); $radio = array(); $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0); $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1); $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2); $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false); $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true); $mform->setDefault('enrollable', $courseconfig->enrollable); $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true)); $mform->setDefault('enrolstartdate', 0); $mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2); $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true)); $mform->setDefault('enrolenddate', 0); $mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2); $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400)); $mform->setDefault('enrolperiod', $courseconfig->enrolperiod); //-------------------------------------------------------------------------------- $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify')); $choices = array(); $choices['0'] = get_string('no'); $choices['1'] = get_string('yes'); $mform->addElement('select', 'expirynotify', get_string('notify'), $choices); $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true); $mform->setDefault('expirynotify', $courseconfig->expirynotify); $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices); $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true); $mform->setDefault('notifystudents', $courseconfig->notifystudents); $thresholdmenu = array(); for ($i = 1; $i <= 30; $i++) { $seconds = $i * 86400; $thresholdmenu[$seconds] = get_string('numdays', '', $i); } $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu); $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true); $mform->setDefault('expirythreshold', $courseconfig->expirythreshold); //-------------------------------------------------------------------------------- $mform->addElement('header', '', get_string('groups', 'group')); $choices = array(); $choices[NOGROUPS] = get_string('groupsnone', 'group'); $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group'); $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group'); $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices); $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true); $mform->setDefault('groupmode', $courseconfig->groupmode); $choices = array(); $choices['0'] = get_string('no'); $choices['1'] = get_string('yes'); $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices); $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true); $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce); if (!empty($CFG->enablegroupings)) { //default groupings selector $options = array(); $options[0] = get_string('none'); $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options); } //-------------------------------------------------------------------------------- $mform->addElement('header', '', get_string('availability')); $choices = array(); $choices['0'] = get_string('courseavailablenot'); $choices['1'] = get_string('courseavailable'); $mform->addElement('select', 'visible', get_string('availability'), $choices); $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true); $mform->setDefault('visible', $courseconfig->visible); if ($course and !has_capability('moodle/course:visibility', $coursecontext)) { $mform->hardFreeze('visible'); $mform->setConstant('visible', $course->visible); } $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"'); $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true); $mform->setDefault('enrolpassword', ''); $mform->setDefault('enrolpassword', $courseconfig->enrolpassword); $mform->setType('enrolpassword', PARAM_RAW); if (empty($course) or $course->password !== '' and $course->id != SITEID) { // do not require password in existing courses that do not have password yet - backwards compatibility ;-) if (!empty($CFG->enrol_manual_requirekey)) { $mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client'); } } $choices = array(); $choices['0'] = get_string('guestsno'); $choices['1'] = get_string('guestsyes'); $choices['2'] = get_string('guestskey'); $mform->addElement('select', 'guest', get_string('opentoguests'), $choices); $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true); $mform->setDefault('guest', $courseconfig->guest); // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here $enrol_object = $CFG; if (!empty($course)) { $enrol_object = $course; } // If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || empty($enrol_object->enrol) && $CFG->enrol == 'manual')) { $costgroup = array(); $currencies = get_list_of_currencies(); $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"'); $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies); $mform->addGroup($costgroup, 'costgrp', get_string('cost'), ' ', false); //defining a rule for a form element within a group : $costgrprules = array(); //set the message to null to tell Moodle to use a default message //available for most rules, fetched from language pack (err_{rulename}). $costgrprules['cost'][] = array(null, 'numeric', null, 'client'); $mform->addGroupRule('costgrp', $costgrprules); $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true); $mform->setDefault('cost', ''); $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency); } //-------------------------------------------------------------------------------- $mform->addElement('header', '', get_string('language')); $languages = array(); $languages[''] = get_string('forceno'); $languages += get_list_of_languages(); $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages); $mform->setDefault('lang', $courseconfig->lang); //-------------------------------------------------------------------------------- require_once $CFG->libdir . '/completionlib.php'; if (completion_info::is_enabled_for_site()) { $mform->addElement('header', '', get_string('progress', 'completion')); $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion'))); $mform->setDefault('enablecompletion', $courseconfig->enablecompletion); } else { $mform->addElement('hidden', 'enablecompletion'); $mform->setDefault('enablecompletion', 0); } //-------------------------------------------------------------------------------- if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) { $mform->addElement('header', '', get_string('restrictmodules')); $options = array(); $options['0'] = get_string('no'); $options['1'] = get_string('yes'); $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options); $mods = array(0 => get_string('allownone')); $mods += $DB->get_records_menu('modules', array(), 'name', 'id, name'); $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10')); $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0); } else { $mform->addElement('hidden', 'restrictmodules', null); } if ($CFG->restrictmodulesfor == 'all') { $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules)); if (!empty($CFG->restrictbydefault)) { $mform->setDefault('restrictmodules', 1); } } $mform->setType('restrictmodules', PARAM_INT); /// customizable role names in this course //-------------------------------------------------------------------------------- $mform->addElement('header', 'rolerenaming', get_string('rolerenaming')); $mform->setHelpButton('rolerenaming', array('rolerenaming', get_string('rolerenaming')), true); if ($roles = get_all_roles()) { if ($coursecontext) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW); } $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE); foreach ($roles as $role) { $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name)); if (isset($role->localname)) { $mform->setDefault('role_' . $role->id, $role->localname); } $mform->setType('role_' . $role->id, PARAM_TEXT); if (!in_array($role->id, $assignableroles)) { $mform->setAdvanced('role_' . $role->id); } } } //-------------------------------------------------------------------------------- $this->add_action_buttons(); //-------------------------------------------------------------------------------- $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); }
/** * Get user information * * @param string $username EBS username, could be 8-digit int or string. * @return array An array describing targets (and metadata) for that user for all leapcore_* courses. */ public static function get_targets_by_username($username) { global $CFG, $DB; $params = self::validate_parameters(self::get_targets_by_username_parameters(), array('username' => $username)); if ($params['username'] == '') { header($_SERVER["SERVER_PROTOCOL"] . ' 422 Unprocessable Entity ($params[\'username\'] empty.)', true, 422); exit(1); } // Require for the course completion code. require_once $CFG->libdir . '/completionlib.php'; // Could do with knowing what this user's {user}.id is. $sql = "SELECT id from {user} WHERE username LIKE ?;"; if (!($user = $DB->get_record_sql($sql, array($params['username'] . '%')))) { header($_SERVER["SERVER_PROTOCOL"] . ' 422 Unprocessable Entity ($params[\'username\'] could not be matched against a valid user.)', true, 422); exit(1); } $cores = array('core' => 'leapcore_core', 'english' => 'leapcore_english', 'maths' => 'leapcore_maths', 'ppd' => 'leapcore_ppd', 'test' => 'leapcore_test', 'a2_artdes' => 'leapcore_a2_artdes', 'a2_artdesphoto' => 'leapcore_a2_artdesphoto', 'a2_artdestext' => 'leapcore_a2_artdestext', 'a2_biology' => 'leapcore_a2_biology', 'a2_busstud' => 'leapcore_a2_busstud', 'a2_chemistry' => 'leapcore_a2_chemistry', 'a2_englishlang' => 'leapcore_a2_englishlang', 'a2_englishlit' => 'leapcore_a2_englishlit', 'a2_envsci' => 'leapcore_a2_envsci', 'a2_envstud' => 'leapcore_a2_envstud', 'a2_filmstud' => 'leapcore_a2_filmstud', 'a2_geography' => 'leapcore_a2_geography', 'a2_govpoli' => 'leapcore_a2_govpoli', 'a2_history' => 'leapcore_a2_history', 'a2_humanbiology' => 'leapcore_a2_humanbiology', 'a2_law' => 'leapcore_a2_law', 'a2_maths' => 'leapcore_a2_maths', 'a2_mathsfurther' => 'leapcore_a2_mathsfurther', 'a2_media' => 'leapcore_a2_media', 'a2_philosophy' => 'leapcore_a2_philosophy', 'a2_physics' => 'leapcore_a2_physics', 'a2_psychology' => 'leapcore_a2_psychology', 'a2_sociology' => 'leapcore_a2_sociology', 'btecex_applsci' => 'leapcore_btecex_applsci', 'gcse_english' => 'leapcore_gcse_english', 'gcse_maths' => 'leapcore_gcse_maths'); // Define the target's names. $targets = array('TAG', 'L3VA', 'MAG'); $courses = array(); foreach ($cores as $core => $coresql) { $courses[$core]['leapcore'] = $core; // Checking for user enrolled as student role, manual enrolments only. $sql = "SELECT DISTINCT c.id AS courseid, c.shortname AS shortname, c.fullname AS fullname, username\n FROM mdl_user u\n JOIN mdl_user_enrolments ue ON ue.userid = u.id\n JOIN mdl_enrol e ON e.id = ue.enrolid\n -- AND e.enrol = 'manual'\n JOIN mdl_role_assignments ra ON ra.userid = u.id\n JOIN mdl_context ct ON ct.id = ra.contextid\n AND ct.contextlevel = 50\n JOIN mdl_course c ON c.id = ct.instanceid\n AND e.courseid = c.id\n JOIN mdl_role r ON r.id = ra.roleid\n AND r.shortname = 'student'\n WHERE c.idnumber LIKE '%|" . $coresql . "|%'\n AND u.username LIKE '" . $params['username'] . "%'\n AND e.status = 0\n AND u.suspended = 0\n AND u.deleted = 0\n AND (\n ue.timeend = 0\n OR ue.timeend > NOW()\n )\n AND ue.status = 0;"; // There is potential here for a user to have more than one 'leapcore_core' course, but it's pretty unlikely. // We probably need to handle this better (at the moment the below function expects 0 or 1 results and fails). if (!($result = $DB->get_record_sql($sql))) { unset($courses[$core]); continue; } else { $courses[$core]['course_shortname'] = $result->shortname; $courses[$core]['course_fullname'] = $result->fullname; $courses[$core]['course_id'] = $result->courseid; } // Walk through a fair few objects to get the course's time modified, final grade and named grade. $gi = new grade_item(); // The course item is actually the right one to use, even if it is null. $gi_item = $gi::fetch(array('courseid' => $courses[$core]['course_id'], 'itemtype' => 'course')); // This may get changed further down the script as we want the most recently changed item's date. $courses[$core]['course_total_modified'] = $gi_item->timemodified; $gg = new grade_grade(); $gg_grade = $gg::fetch(array('itemid' => $gi_item->id, 'userid' => $user->id)); // If the scale is going to be a U (or Refer, or Fail etc) as the L3VA is 0, pass null. if ($gg_grade && $gg_grade->finalgrade > 0) { $courses[$core]['course_total'] = $gg_grade->finalgrade; $gs = new grade_scale(); $gs_scale = $gs::fetch(array('id' => $gi_item->scaleid)); if ($gi_item->display != 0) { // Check first for a non-zero 'display' variable, and run with that if found. $courses[$core]['course_total_display'] = grade_format_gradevalue($gg_grade->finalgrade, $gi_item, true, $gi_item->display); } else { if ($gs_scale) { // See if we have a scale and use that if found. $courses[$core]['course_total_display'] = $gs_scale->get_nearest_item($gg_grade->finalgrade); } else { if (is_numeric($gg_grade->finalgrade)) { $courses[$core]['course_total_display'] = round($courses[$core]['course_total'], 0, PHP_ROUND_HALF_UP); } else { $courses[$core]['course_total_display'] = $courses[$core]['course_total']; } } } } else { $courses[$core]['course_total'] = 0; $courses[$core]['course_total_display'] = null; } // For each target, same as above. foreach ($targets as $target) { $gi = new grade_item(); $gi_item = $gi::fetch(array('courseid' => $courses[$core]['course_id'], 'itemtype' => 'manual', 'itemname' => $target)); $gg = new grade_grade(); $gg_grade = $gg::fetch(array('itemid' => $gi_item->id, 'userid' => $user->id)); $courses[$core][strtolower($target)] = $gg_grade->finalgrade; // Get the named result (e.g. 'merit') only for targets which are not L3VA. if ($target != 'L3VA') { $gs = new grade_scale(); $gs_scale = $gs::fetch(array('id' => $gi_item->scaleid)); // Updating the most recently modified date if it's newer. if ($gi_item->timemodified > $courses[$core]['course_total_modified']) { $courses[$core]['course_total_modified'] = $gi_item->timemodified; } // If the scale is going to be a U (or Refer, or Fail etc) as the L3VA is 0, pass null. if ($gg_grade->finalgrade > 0) { // If there's no scale, just pass the data across. if ($gs_scale) { $courses[$core][strtolower($target) . '_display'] = $gs_scale->get_nearest_item($gg_grade->finalgrade); } else { $courses[$core][strtolower($target) . '_display'] = $gg_grade->finalgrade; } } else { $courses[$core][strtolower($target) . '_display'] = null; } } else { $courses[$core][strtolower($target) . '_display'] = $courses[$core][strtolower($target)]; } // Rounding. if (is_numeric($courses[$core][strtolower($target) . '_display'])) { $courses[$core][strtolower($target) . '_display'] = round($courses[$core][strtolower($target) . '_display'], 2, PHP_ROUND_HALF_UP); } } // Default both of these to null. $courses[$core]['course_completion_total'] = null; $courses[$core]['course_completion_completed'] = null; // We could do with a course object to use. $sql = "SELECT id from {course} WHERE id LIKE ?;"; if (!($thiscourse = $DB->get_record_sql($sql, array($courses[$core]['course_id'])))) { exit(1); } if (completion_info::is_enabled_for_site()) { $info = new completion_info($thiscourse); $completions = $info->get_completions($user->id); // If there's no completions, none have been configured so do nothing. if (!empty($completions)) { $courses[$core]['course_completion_total'] = count($completions); $courses[$core]['course_completion_completed'] = $info->count_course_user_data($user->id); // Loop through each timecompleted value, ignore if null, update if more recent. foreach ($completions as $completion) { if (!is_null($completion->timecompleted) && $completion->timecompleted > $courses[$core]['course_total_modified']) { $courses[$core]['course_total_modified'] = $completion->timecompleted; } } } } // END completion info enabled for site check. // Stress reduction code. $courses[$core]['meaning_of_life'] = '42'; $courses[$core]['smiley_face'] = ':)'; // Incomplete course check. // TODO: make this better. We scan through all four 'leapcore_' tags (and all the new A2 ones) and get the results, // but sometimes there aren't any. So for the tags with no associated courses, we remove them. if (!isset($courses[$core]['course_shortname'])) { unset($courses[$core]); } } // END foreach $courses. if (!empty($courses)) { return $courses; } }