$coursecontext = $context; } require_login($course); $baseurl = 'override.php?contextid=' . $context->id; if (!empty($userid)) { $baseurl .= '&userid=' . $userid; } if ($courseid != SITEID) { $baseurl .= '&courseid=' . $courseid; } if ($cancel) { redirect($baseurl); } /// needed for tabs.php $overridableroles = get_overridable_roles($context); $assignableroles = get_assignable_roles($context); /// Get some language strings $strroletooverride = get_string('roletooverride', 'role'); $straction = get_string('overrideroles', 'role'); $strcurrentrole = get_string('currentrole', 'role'); $strparticipants = get_string('participants'); /// Make sure this user can override that role if ($roleid) { if (!user_can_override($context, $roleid)) { error('you can not override this role in this context'); } } if ($userid) { $user = get_record('user', 'id', $userid); $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context)); }
/** * Given one role, as loaded from XML, perform the best possible matching against the assignable * roles, using different fallback alternatives (shortname, archetype, editingteacher => teacher, defaultcourseroleid) * returning the id of the best matching role or 0 if no match is found */ protected static function get_best_assignable_role($role, $courseid, $userid, $samesite) { global $CFG, $DB; // Gather various information about roles $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); $allroles = $DB->get_records('role'); $assignablerolesshortname = get_assignable_roles($coursectx, ROLENAME_SHORT, false, $userid); // Note: under 1.9 we had one function restore_samerole() that performed one complete // matching of roles (all caps) and if match was found the mapping was availabe bypassing // any assignable_roles() security. IMO that was wrong and we must not allow such // mappings anymore. So we have left that matching strategy out in 2.0 // Empty assignable roles, mean no match possible if (empty($assignablerolesshortname)) { return 0; } // Match by shortname if ($match = array_search($role->shortname, $assignablerolesshortname)) { return $match; } // Match by archetype list($in_sql, $in_params) = $DB->get_in_or_equal(array_keys($assignablerolesshortname)); $params = array_merge(array($role->archetype), $in_params); if ($rec = $DB->get_record_select('role', "archetype = ? AND id {$in_sql}", $params, 'id', IGNORE_MULTIPLE)) { return $rec->id; } // Match editingteacher to teacher (happens a lot, from 1.9) if ($role->shortname == 'editingteacher' && in_array('teacher', $assignablerolesshortname)) { return array_search('teacher', $assignablerolesshortname); } // No match, return 0 return 0; }
function definition() { global $CFG, $DB; $mform = $this->_form; list($instance, $plugin, $course) = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); $groups = array(0 => get_string('none')); foreach (groups_get_all_groups($course->id) as $group) { $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext)); } $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort')); $mform->addElement('text', 'name', get_string('custominstancename', 'enrol')); $mform->setType('name', PARAM_TEXT); $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no')); $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options); if ($instance->id) { if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) { $cohorts = array($instance->customint1 => format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)))); } else { $cohorts = array($instance->customint1 => get_string('error')); } $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts); $mform->setConstant('customint1', $instance->customint1); $mform->hardFreeze('customint1', $instance->customint1); } else { $cohorts = array('' => get_string('choosedots')); $allcohorts = cohort_get_available_cohorts($coursecontext, 0, 0, 0); foreach ($allcohorts as $c) { $cohorts[$c->id] = format_string($c->name); } $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('customint1', get_string('required'), 'required', null, 'client'); } $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // Descending default sortorder. $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles); $mform->setDefault('roleid', $enrol->get_config('roleid')); if ($instance->id and !isset($roles[$instance->roleid])) { if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true); $roles[$instance->roleid] = role_get_name($role, $coursecontext); } else { $roles[$instance->roleid] = get_string('error'); } } $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups); $mform->addElement('hidden', 'courseid', null); $mform->setType('courseid', PARAM_INT); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); if ($instance->id) { $this->add_action_buttons(true); } else { $this->add_action_buttons(true, get_string('addinstance', 'enrol')); } $this->set_data($instance); }
function definition() { global $CFG; $mform = & $this->_form; $course = $this->_customdata['course']; $context = $this->_customdata['context']; // the upload manager is used directly in post precessing, moodleform::save_files() is not used yet //$this->set_upload_manager(new upload_manager('attachment')); $mform->addElement('header', 'general', ''); //fill in the data depending on page params //later using set_data $mform->addElement('filepicker', 'attachment', get_string('location', 'enrol_flatfile')); $mform->addRule('attachment', null, 'required'); $choices = csv_import_reader::get_delimiter_list(); $mform->addElement('select', 'delimiter_name', get_string('csvdelimiter', 'tool_uploaduser'), $choices); if (array_key_exists('cfg', $choices)) { $mform->setDefault('delimiter_name', 'cfg'); } else if (get_string('listsep', 'langconfig') == ';') { $mform->setDefault('delimiter_name', 'semicolon'); } else { $mform->setDefault('delimiter_name', 'comma'); } $choices = textlib::get_encodings(); $mform->addElement('select', 'encoding', get_string('encoding', 'tool_uploaduser'), $choices); $mform->setDefault('encoding', 'UTF-8'); $roles = get_assignable_roles($context); $mform->addElement('select', 'roleassign', get_string('roleassign', 'local_mass_enroll'), $roles); $mform->setDefault('roleassign', 5); //student $ids = array ( 'idnumber' => get_string('idnumber', 'local_mass_enroll'), 'username' => get_string('username', 'local_mass_enroll'), 'email' => get_string('email') ); $mform->addElement('select', 'firstcolumn', get_string('firstcolumn', 'local_mass_enroll'), $ids); $mform->setDefault('firstcolumn', 'idnumber'); $mform->addElement('selectyesno', 'creategroups', get_string('creategroups', 'local_mass_enroll')); $mform->setDefault('creategroups', 1); $mform->addElement('selectyesno', 'creategroupings', get_string('creategroupings', 'local_mass_enroll')); $mform->setDefault('creategroupings', 1); $mform->addElement('selectyesno', 'mailreport', get_string('mailreport', 'local_mass_enroll')); $mform->setDefault('mailreport', 1); //------------------------------------------------------------------------------- // buttons $this->add_action_buttons(true, get_string('enroll', 'local_mass_enroll')); $mform->addElement('hidden', 'id', $course->id); $mform->setType('id', PARAM_INT); }
function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata['course']; $enrol = $this->_customdata['enrol']; $service = $this->_customdata['service']; $coursecontext = context_course::instance($course->id); $subscribers = $service->get_remote_subscribers(); $hosts = array(0 => get_string('remotesubscribersall', 'enrol_mnet')); foreach ($subscribers as $hostid => $subscriber) { $hosts[$hostid] = $subscriber->appname . ': ' . $subscriber->hostname . ' (' . $subscriber->hosturl . ')'; } $roles = get_assignable_roles($coursecontext); $mform->addElement('header', 'general', get_string('pluginname', 'enrol_mnet')); $mform->addElement('select', 'hostid', get_string('remotesubscriber', 'enrol_mnet'), $hosts); $mform->addHelpButton('hostid', 'remotesubscriber', 'enrol_mnet'); $mform->addRule('hostid', get_string('required'), 'required', null, 'client'); $mform->addElement('select', 'roleid', get_string('roleforremoteusers', 'enrol_mnet'), $roles); $mform->addHelpButton('roleid', 'roleforremoteusers', 'enrol_mnet'); $mform->addRule('roleid', get_string('required'), 'required', null, 'client'); $mform->setDefault('roleid', $enrol->get_config('roleid')); $mform->addElement('text', 'name', get_string('instancename', 'enrol_mnet')); $mform->addHelpButton('name', 'instancename', 'enrol_mnet'); $mform->setType('name', PARAM_TEXT); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $this->add_action_buttons(); $this->set_data(array('id' => $course->id)); }
function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); $cohorts = array('' => get_string('choosedots')); list($sqlparents, $params) = $DB->get_in_or_equal(get_parent_contexts($coursecontext)); $sql = "SELECT id, name, contextid\n FROM {cohort}\n WHERE contextid {$sqlparents}\n ORDER BY name ASC"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $c) { $context = get_context_instance_by_id($c->contextid); if (!has_capability('moodle/cohort:view', $context)) { continue; } $cohorts[$c->id] = format_string($c->name); } $rs->close(); $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // descending default sortorder $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort')); $mform->addElement('select', 'cohortid', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('cohortid', get_string('required'), 'required', null, 'client'); $mform->addElement('select', 'roleid', get_string('role'), $roles); $mform->addRule('roleid', get_string('required'), 'required', null, 'client'); $mform->setDefault('roleid', $enrol->get_config('roleid')); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $this->add_action_buttons(true, get_string('addinstance', 'enrol')); $this->set_data(array('id' => $course->id)); }
/** * Enrolment of users. * * Function throw an exception at the first error encountered. * @param array $enrolments An array of user enrolment * @since Moodle 2.2 */ public static function enrol_users($enrolments) { global $DB, $CFG; require_once $CFG->libdir . '/enrollib.php'; $params = self::validate_parameters(self::enrol_users_parameters(), array('enrolments' => $enrolments)); $transaction = $DB->start_delegated_transaction(); // Rollback all enrolment if an error occurs // (except if the DB doesn't support it). // Retrieve the manual enrolment plugin. $enrol = enrol_get_plugin('manual'); if (empty($enrol)) { throw new moodle_exception('manualpluginnotinstalled', 'enrol_manual'); } foreach ($params['enrolments'] as $enrolment) { // Ensure the current user is allowed to run this function in the enrolment context. $context = context_course::instance($enrolment['courseid'], IGNORE_MISSING); self::validate_context($context); // Check that the user has the permission to manual enrol. require_capability('enrol/manual:enrol', $context); // Throw an exception if user is not able to assign the role. $roles = get_assignable_roles($context); if (!array_key_exists($enrolment['roleid'], $roles)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wsusercannotassign', 'enrol_manual', '', $errorparams); } // Check manual enrolment plugin instance is enabled/exist. $instance = null; $enrolinstances = enrol_get_instances($enrolment['courseid'], true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } if (empty($instance)) { $errorparams = new stdClass(); $errorparams->courseid = $enrolment['courseid']; throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams); } // Check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin). if (!$enrol->allow_enrol($instance)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams); } // Finally proceed the enrolment. $enrolment['timestart'] = isset($enrolment['timestart']) ? $enrolment['timestart'] : 0; $enrolment['timeend'] = isset($enrolment['timeend']) ? $enrolment['timeend'] : 0; $enrolment['status'] = isset($enrolment['suspend']) && !empty($enrolment['suspend']) ? ENROL_USER_SUSPENDED : ENROL_USER_ACTIVE; $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['status']); } $transaction->allow_commit(); }
public function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata['course']; $instance = $this->_customdata['instance']; $this->course = $course; $existing = array(); if ($instance) { $existing = $DB->get_records('enrol_metaplus', array('enrolid' => $instance->id), '', 'courseid, id'); } $courses = array(); $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = <<<SQL SELECT c.id, c.fullname, c.shortname, c.visible, {$select} FROM {course} c LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel) SQL; $rs = $DB->get_recordset_sql($sql, array('contextlevel' => CONTEXT_COURSE)); foreach ($rs as $c) { if ($c->id == SITEID || $c->id == $course->id) { continue; } context_helper::preload_from_record($c); $coursecontext = context_course::instance($c->id); if (!$c->visible && !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { continue; } if (!has_capability('enrol/meta:selectaslinked', $coursecontext)) { continue; } $courses[$c->id] = $coursecontext->get_context_name(false); } $rs->close(); $mform->addElement('header', 'general', get_string('pluginname', 'enrol_meta')); $mform->addElement('select', 'link', get_string('linkedcourse', 'enrol_metaplus'), $courses, array('multiple' => 'multiple', 'class' => 'chosen')); $mform->addRule('link', get_string('required'), 'required', null, 'server'); // Add role sync list. $coursecontext = \context_course::instance($course->id); $roles = get_assignable_roles($coursecontext); $mform->addElement('select', 'roleexclusions', get_string('roleexclusions', 'enrol_metaplus'), $roles, array('multiple' => 'multiple')); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $mform->addElement('hidden', 'enrolid'); $mform->setType('enrolid', PARAM_INT); $data = array('id' => $course->id); if ($instance) { $data['link'] = implode(',', array_keys($existing)); $data['enrolid'] = $instance->id; $data['roleexclusions'] = $instance->customtext1; $this->add_action_buttons(); } else { $this->add_add_buttons(); } $this->set_data($data); }
/** * Gets a list of roles that this user can assign for the course as the default for auto-enrolment. * * @param context $context the context. * @param integer $defaultrole the id of the role that is set as the default for auto-enrolment * @return array index is the role id, value is the role name */ function extend_assignable_roles($context, $defaultrole) { global $DB; $roles = get_assignable_roles($context, ROLENAME_BOTH); if (!isset($roles[$defaultrole])) { if ($role = $DB->get_record('role', array('id' => $defaultrole))) { $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH); } } return $roles; }
public function definition() { $mform =& $this->_form; $mform->addElement('checkbox', 'enabled', null, get_string('enabled', 'local_anonymousposting')); $mform->setDefault('enabled', 1); $context = context_course::instance(SITEID, MUST_EXIST); $assignableroles = get_assignable_roles($context); $mform->addElement('select', 'defaultcourserole', get_string('defaultcourserole', 'local_anonymousposting'), $assignableroles); $mform->setDefault('defaultcourserole', '5'); $mform->addElement('select', 'defaultactivityrole', get_string('defaultactivityrole', 'local_anonymousposting'), $assignableroles); $mform->setDefault('defaultactivityrole', '5'); $this->add_action_buttons(); }
/** * Core function for creation of form defined in block_panopto_edit_form class */ protected function specific_definition($mform) { global $COURSE, $CFG; // Construct the Panopto data proxy object. $panoptodata = new panopto_data($COURSE->id); if (!empty($panoptodata->servername) && !empty($panoptodata->instancename) && !empty($panoptodata->applicationkey)) { $mform->addElement('header', 'configheader', get_string('block_edit_header', 'block_panopto')); $params = new stdClass(); $params->course_id = $COURSE->id; $params->return_url = $_SERVER['REQUEST_URI']; $querystring = http_build_query($params, '', '&'); $provisionurl = "{$CFG->wwwroot}/blocks/panopto/provision_course.php?" . $querystring; $addtopanopto = get_string('add_to_panopto', 'block_panopto'); $or = get_string('or', 'block_panopto'); $mform->addElement('html', "<a href='{$provisionurl}'>{$addtopanopto}</a><br><br>-- {$or} --<br><br>"); $courselist = $panoptodata->get_course_options(); $mform->addElement('selectgroups', 'config_course', get_string('existing_course', 'block_panopto'), $courselist['courses']); $mform->setDefault('config_course', $courselist['selected']); // Set course context to get roles. $context = context_course::instance($COURSE->id); // Get current role mappings. $currentmappings = $panoptodata->get_course_role_mappings($COURSE->id); // Get roles that current user may assign in this course. $currentcourseroles = get_assignable_roles($context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null); while ($role = current($currentcourseroles)) { $rolearray[key($currentcourseroles)] = $currentcourseroles[key($currentcourseroles)]; next($currentcourseroles); } $mform->addElement('header', 'rolemapheader', get_string('role_map_header', 'block_panopto')); $mform->addElement('html', get_string('role_map_info_text', 'block_panopto')); $createselect = $mform->addElement('select', 'config_creator', get_string('creator', 'block_panopto'), $rolearray, null); $createselect->setMultiple(true); // Set default selected to previous setting. if (!empty($currentmappings['creator'])) { $createselect->setSelected($currentmappings['creator']); } $pubselect = $mform->addElement('select', 'config_publisher', get_string('publisher', 'block_panopto'), $rolearray, null); $pubselect->setMultiple(true); // Set default selected to previous setting. if (!empty($currentmappings['publisher'])) { $pubselect->setSelected($currentmappings['publisher']); } } else { $mform->addElement('static', 'error', '', get_string('block_edit_error', 'block_panopto')); } }
/** * Form definition */ public function definition() { global $DB; $mform =& $this->_form; $course = $this->_customdata['course']; $context = $this->_customdata['context']; $config = get_config('local_mass_enroll'); $mform->addElement('header', 'general', ''); // Fill in the data depending on page params. // Later using set_data. $mform->addElement('filepicker', 'attachment', get_string('location', 'enrol_flatfile')); $mform->addRule('attachment', null, 'required'); $choices = csv_import_reader::get_delimiter_list(); $mform->addElement('select', 'delimiter_name', get_string('csvdelimiter', 'tool_uploaduser'), $choices); if (array_key_exists('cfg', $choices)) { $mform->setDefault('delimiter_name', 'cfg'); } else { if (get_string('listsep', 'langconfig') == ';') { $mform->setDefault('delimiter_name', 'semicolon'); } else { $mform->setDefault('delimiter_name', 'comma'); } } $choices = \core_text::get_encodings(); $mform->addElement('select', 'encoding', get_string('encoding', 'tool_uploaduser'), $choices); $mform->setDefault('encoding', 'UTF-8'); $roles = get_assignable_roles($context); $mform->addElement('select', 'roleassign', get_string('roleassign', 'local_mass_enroll'), $roles); $studentrole = $DB->get_record('role', array('archetype' => 'student')); $mform->setDefault('roleassign', $studentrole->id); $ids = array('idnumber' => get_string('idnumber', 'local_mass_enroll'), 'username' => get_string('username', 'local_mass_enroll'), 'email' => get_string('email')); $mform->addElement('select', 'firstcolumn', get_string('firstcolumn', 'local_mass_enroll'), $ids); $mform->setDefault('firstcolumn', 'idnumber'); $mform->addElement('selectyesno', 'creategroups', get_string('creategroups', 'local_mass_enroll')); $mform->setDefault('creategroups', 1); $mform->addElement('selectyesno', 'creategroupings', get_string('creategroupings', 'local_mass_enroll')); $mform->setDefault('creategroupings', 1); $mform->addElement('selectyesno', 'mailreport', get_string('mailreport', 'local_mass_enroll')); $mform->setDefault('mailreport', (int) $config->mailreportdefault); // Buttons. $this->add_action_buttons(true, get_string('enroll', 'local_mass_enroll')); $mform->addElement('hidden', 'id', $course->id); $mform->setType('id', PARAM_INT); }
/** * Form definition. */ protected function definition() { global $DB; $mform = $this->_form; // Add student select box. $mform->addElement('select', 'users', 'Users', $DB->get_records_menu('user', array(), '', 'id,username'), array('class' => 'chosen', 'multiple' => 'multiple')); $mform->addRule('users', null, 'required', null, 'client'); // Add student select box. $courses = $DB->get_records_menu('course', array(), '', 'id,CONCAT(shortname, \': \', fullname)'); $mform->addElement('select', 'courses', 'Courses', $courses, array('class' => 'chosen', 'multiple' => 'multiple')); $mform->addRule('courses', null, 'required', null, 'client'); unset($courses); // Add role select box. $course = get_site(); $roles = get_assignable_roles(\context_course::instance($course->id)); $mform->addElement('select', 'roleid', 'Role', $roles); $mform->addRule('roleid', null, 'required', null, 'client'); $this->add_action_buttons(true, 'Enrol'); }
function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata; $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $enrol = enrol_get_plugin('jwc'); $roles = get_assignable_roles($coursecontext); $roles = array_reverse($roles, true); // descending default sortorder $mform->addElement('header', 'general', get_string('pluginname', 'enrol_jwc')); $mform->addElement('html', '与教务管理系统的学生选课同步。只有使用HITID登录的教师和学生才能享用此功能'); $mform->addElement('text', 'coursenumber', get_string('coursenumber', 'enrol_jwc')); $mform->setType('coursenumber', PARAM_ALPHANUM); $mform->addHelpButton('coursenumber', 'coursenumber', 'enrol_jwc'); $mform->addRule('coursenumber', get_string('required'), 'required', null, 'client'); $mform->addElement('hidden', 'roleid', $enrol->get_config('roleid')); $mform->setType('roleid', PARAM_INT); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $this->add_action_buttons(true, get_string('addinstance', 'enrol')); $this->set_data(array('id' => $course->id)); }
/** * Test returning of assignable roles in context. */ public function test_get_assignable_roles() { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST); $teacher = $this->getDataGenerator()->create_user(); role_assign($teacherrole->id, $teacher->id, $coursecontext); $teacherename = (object) array('roleid' => $teacherrole->id, 'name' => 'Učitel', 'contextid' => $coursecontext->id); $DB->insert_record('role_names', $teacherename); $studentrole = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST); $student = $this->getDataGenerator()->create_user(); role_assign($studentrole->id, $student->id, $coursecontext); $contexts = $DB->get_records('context'); $users = $DB->get_records('user'); $allroles = $DB->get_records('role'); // Evaluate all results for all users in all contexts. foreach ($users as $user) { $this->setUser($user); foreach ($contexts as $contextid => $unused) { $context = context_helper::instance_by_id($contextid); $roles = get_assignable_roles($context, ROLENAME_SHORT); foreach ($allroles as $roleid => $role) { if (isset($roles[$roleid])) { if (is_siteadmin()) { $this->assertTrue($DB->record_exists('role_context_levels', array('contextlevel' => $context->contextlevel, 'roleid' => $roleid))); } else { $this->assertTrue(user_can_assign($context, $roleid), "u:{$user->id} r:{$roleid}"); } $this->assertEquals($role->shortname, $roles[$roleid]); } else { $allowed = $DB->record_exists('role_context_levels', array('contextlevel' => $context->contextlevel, 'roleid' => $roleid)); if (is_siteadmin()) { $this->assertFalse($allowed); } else { $this->assertFalse($allowed and user_can_assign($context, $roleid), "u:{$user->id}, r:{$allroles[$roleid]->name}, c:{$context->contextlevel}"); } } } } } // Not-logged-in user. $this->setUser(0); foreach ($contexts as $contextid => $unused) { $context = context_helper::instance_by_id($contextid); $roles = get_assignable_roles($context, ROLENAME_SHORT); $this->assertSame(array(), $roles); } // Test current user. $this->setUser(0); $admin = $DB->get_record('user', array('username' => 'admin'), '*', MUST_EXIST); $roles1 = get_assignable_roles($coursecontext, ROLENAME_SHORT, false, $admin); $roles2 = get_assignable_roles($coursecontext, ROLENAME_SHORT, false, $admin->id); $this->setAdminUser(); $roles3 = get_assignable_roles($coursecontext, ROLENAME_SHORT); $this->assertSame($roles1, $roles3); $this->assertSame($roles2, $roles3); // Test parameter defaults. $this->setAdminUser(); $roles1 = get_assignable_roles($coursecontext); $roles2 = get_assignable_roles($coursecontext, ROLENAME_ALIAS, false, $admin); $this->assertEquals($roles2, $roles1); // Verify returned names - let's allow all roles everywhere to simplify this a bit. $alllevels = context_helper::get_all_levels(); $alllevels = array_keys($alllevels); foreach ($allroles as $roleid => $role) { set_role_contextlevels($roleid, $alllevels); } $alltypes = array(ROLENAME_ALIAS, ROLENAME_ALIAS_RAW, ROLENAME_BOTH, ROLENAME_ORIGINAL, ROLENAME_ORIGINALANDSHORT, ROLENAME_SHORT); foreach ($alltypes as $type) { $rolenames = role_fix_names($allroles, $coursecontext, $type); $roles = get_assignable_roles($coursecontext, $type, false, $admin); foreach ($roles as $roleid => $rolename) { $this->assertSame($rolenames[$roleid]->localname, $rolename); } } // Verify counts. $alltypes = array(ROLENAME_ALIAS, ROLENAME_ALIAS_RAW, ROLENAME_BOTH, ROLENAME_ORIGINAL, ROLENAME_ORIGINALANDSHORT, ROLENAME_SHORT); foreach ($alltypes as $type) { $roles = get_assignable_roles($coursecontext, $type, false, $admin); list($rolenames, $rolecounts, $nameswithcounts) = get_assignable_roles($coursecontext, $type, true, $admin); $this->assertEquals($roles, $rolenames); foreach ($rolenames as $roleid => $name) { if ($roleid == $teacherrole->id or $roleid == $studentrole->id) { $this->assertEquals(1, $rolecounts[$roleid]); } else { $this->assertEquals(0, $rolecounts[$roleid]); } $this->assertSame("{$name} ({$rolecounts[$roleid]})", $nameswithcounts[$roleid]); } } }
function definition() { global $CFG, $DB, $PAGE; $mform = $this->_form; list($instance, $plugin, $course) = $this->_customdata; $coursecontext = context_course::instance($course->id); $PAGE->requires->yui_module('moodle-enrol_ilios-groupchoosers', 'M.enrol_ilios.init_groupchoosers', array(array('formid' => $mform->getAttribute('id'), 'courseid' => $course->id))); $enrol = $plugin; $http = $plugin->get_http_client(); $mform->addElement('header', 'general', get_string('pluginname', 'enrol_ilios')); $mform->addElement('text', 'name', get_string('custominstancename', 'enrol')); $mform->setType('name', PARAM_TEXT); $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no')); $mform->addElement('select', 'status', get_string('status', 'enrol_ilios'), $options); $schooloptions = array('' => get_string('choosedots')); $programoptions = array('' => get_string('choosedots')); $cohortoptions = array('' => get_string('choosedots')); $learnergroupoptions = array('' => get_string('none')); $subgroupoptions = array('' => get_string('none')); if ($instance->id) { $synctype = $instance->customchar1; $syncid = $instance->customint1; $syncinfo = json_decode($instance->customtext1); $instance->schoolid = $syncinfo->school->id; $school = $http->getbyid('schools', $instance->schoolid); $instance->selectschoolindex = "{$instance->schoolid}:{$school->title}"; $schooloptions = array($instance->selectschoolindex => $school->title); $instance->programid = $syncinfo->program->id; $program = $http->getbyid('programs', $instance->programid); $instance->selectprogramindex = "{$instance->programid}:{$program->shortTitle}:{$program->title}"; $programoptions = array($instance->selectprogramindex => $program->title); $instance->cohortid = $syncinfo->cohort->id; $cohort = $http->getbyid('cohorts', $instance->cohortid); $instance->selectcohortindex = "{$instance->cohortid}:{$cohort->title}"; $cohortoptions = array($instance->selectcohortindex => $cohort->title); $instance->learnergroupid = ''; $instance->selectlearnergroupindex = ''; $instance->subgroupid = ''; $instance->selectsubgroupindex = ''; if ($synctype == 'learnerGroup') { $instance->learnergroupid = $syncid; $group = $http->getbyid('learnerGroups', $instance->learnergroupid); $instance->selectlearnergroupindex = "{$instance->learnergroupid}:{$group->title}"; $grouptitle = $group->title . ' (' . count($group->children) . ')' . ' (' . count($group->users) . ')'; $learnergroupoptions = array($instance->selectlearnergroupindex => $grouptitle); if (!empty($group->parent)) { $processparents = function ($child) use(&$processparents, &$learnergroupoptions, &$grouptitle, &$instance, $http) { $parentgroup = $http->getbyid('learnerGroups', $child->parent); $instance->learnergroupid = $parentgroup->id; $instance->selectlearnergroupindex = "{$instance->learnergroupid}:{$parentgroup->title}"; $learnergroupoptions = array("{$instance->learnergroupid}:{$parentgroup->title}" => $parentgroup->title); if (!empty($parentgroup->parent)) { $grouptitle = $parentgroup->title . ' / ' . $grouptitle; $processparents($parentgroup); } }; $processparents($group); $instance->subgroupid = $group->id; $instance->selectsubgroupindex = "{$group->id}:{$group->title}"; $subgroupoptions = array($instance->selectsubgroupindex => $grouptitle); } } } if ($instance->id) { $mform->addElement('select', 'selectschool', get_string('school', 'enrol_ilios'), $schooloptions); $mform->setConstant('selectschool', $instance->selectschoolindex); $mform->hardFreeze('selectschool', $instance->selectschoolindex); } else { $mform->addElement('select', 'selectschool', get_string('school', 'enrol_ilios'), $schooloptions); $mform->addRule('selectschool', get_string('required'), 'required', null, 'client'); $mform->addHelpButton('selectschool', 'school', 'enrol_ilios'); $mform->registerNoSubmitButton('updateschooloptions'); $mform->addElement('submit', 'updateschooloptions', get_string('schooloptionsupdate', 'enrol_ilios')); } if ($instance->id) { $mform->addElement('select', 'selectprogram', get_string('program', 'enrol_ilios'), $programoptions); $mform->setConstant('selectprogram', $instance->selectprogramindex); $mform->hardFreeze('selectprogram', $instance->selectprogramindex); } else { $mform->addElement('select', 'selectprogram', get_string('program', 'enrol_ilios'), $programoptions); $mform->addRule('selectprogram', get_string('required'), 'required', null, 'client'); $mform->addHelpButton('selectprogram', 'program', 'enrol_ilios'); $mform->disabledIf('selectprogram', 'selectschool', 'eq', ''); $mform->registerNoSubmitButton('updateprogramoptions'); $mform->addElement('submit', 'updateprogramoptions', get_string('programoptionsupdate', 'enrol_ilios')); } if ($instance->id) { $mform->addElement('select', 'selectcohort', get_string('cohort', 'enrol_ilios'), $cohortoptions); $mform->setConstant('selectcohort', $instance->selectcohortindex); $mform->hardFreeze('selectcohort', $instance->selectcohortindex); } else { $mform->addElement('select', 'selectcohort', get_string('cohort', 'enrol_ilios'), $cohortoptions); $mform->addRule('selectcohort', get_string('required'), 'required', null, 'client'); $mform->addHelpButton('selectcohort', 'cohort', 'enrol_ilios'); $mform->disabledIf('selectcohort', 'selectprogram', 'eq', ''); $mform->registerNoSubmitButton('updatecohortoptions'); $mform->addElement('submit', 'updatecohortoptions', get_string('cohortoptionsupdate', 'enrol_ilios')); } if ($instance->id) { $mform->addElement('select', 'selectlearnergroup', get_string('learnergroup', 'enrol_ilios'), $learnergroupoptions); $mform->setConstant('selectlearnergroup', $instance->selectlearnergroupindex); $mform->hardFreeze('selectlearnergroup', $instance->selectlearnergroupindex); } else { $mform->addElement('select', 'selectlearnergroup', get_string('learnergroup', 'enrol_ilios'), $learnergroupoptions); $mform->addHelpButton('selectlearnergroup', 'learnergroup', 'enrol_ilios'); $mform->disabledIf('selectlearnergroup', 'selectcohort', 'eq', ''); $mform->registerNoSubmitButton('updatelearnergroupoptions'); $mform->addElement('submit', 'updatelearnergroupoptions', get_string('learnergroupoptionsupdate', 'enrol_ilios')); } if ($instance->id) { $mform->addElement('select', 'selectsubgroup', get_string('subgroup', 'enrol_ilios'), $subgroupoptions); $mform->setConstant('selectsubgroup', $instance->selectsubgroupindex); $mform->hardFreeze('selectsubgroup', $instance->selectsubgroupindex); } else { $mform->addElement('select', 'selectsubgroup', get_string('subgroup', 'enrol_ilios'), $subgroupoptions); $mform->addHelpButton('selectsubgroup', 'subgroup', 'enrol_ilios'); $mform->disabledIf('selectsubgroup', 'selectlearnergroup', 'eq', ''); } $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // Descending default sortorder. $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_ilios'), $roles); $mform->setDefault('roleid', $enrol->get_config('roleid')); if ($instance->id and !isset($roles[$instance->roleid])) { if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true); $roles[$instance->roleid] = role_get_name($role, $coursecontext); } else { $roles[$instance->roleid] = get_string('error'); } } $groups = array(0 => get_string('none')); foreach (groups_get_all_groups($course->id) as $group) { $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext)); } $mform->addElement('select', 'customint6', get_string('addgroup', 'enrol_ilios'), $groups); $mform->addElement('hidden', 'courseid', null); $mform->setType('courseid', PARAM_INT); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); if ($instance->id) { $this->add_action_buttons(true); } else { $this->add_action_buttons(true, get_string('addinstance', 'enrol')); } $this->set_data($instance); $prog_el =& $mform->getElement('selectschool'); }
/** * Renders the process stage screen * * @throws restore_ui_exception * @param core_backup_renderer $renderer renderer instance to use * @return string HTML code */ public function display(core_backup_renderer $renderer) { global $PAGE; $html = ''; $haserrors = false; $url = new moodle_url($PAGE->url, array('restore' => $this->get_uniqueid(), 'stage' => restore_ui::STAGE_PROCESS, 'substage' => $this->substage, 'sesskey' => sesskey())); $html .= html_writer::start_tag('form', array('action' => $url->out_omit_querystring(), 'class' => 'backup-restore', 'enctype' => 'application/x-www-form-urlencoded', 'method' => 'post')); foreach ($url->params() as $name => $value) { $html .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $name, 'value' => $value)); } switch ($this->substage) { case self::SUBSTAGE_PRECHECKS: $results = $this->ui->get_controller()->get_precheck_results(); $info = $this->ui->get_controller()->get_info(); $haserrors = !empty($results['errors']); $html .= $renderer->precheck_notices($results); if (!empty($info->role_mappings->mappings)) { $context = context_course::instance($this->ui->get_controller()->get_courseid()); $assignableroles = get_assignable_roles($context, ROLENAME_ALIAS, false); $html .= $renderer->role_mappings($info->role_mappings->mappings, $assignableroles); } break; default: throw new restore_ui_exception('backup_ui_must_execute_first'); } $html .= $renderer->substage_buttons($haserrors); $html .= html_writer::end_tag('form'); return $html; }
public function definition() { global $USER, $CFG, $COURSE; $mform =& $this->_form; $templateuser = $USER; $context = $this->_customdata['context']; $mform->addElement('header', 'settingsheader', get_string('toolsettings', 'local_ltiprovider')); $tools = array(); $tools[$context->id] = get_string('course'); $modinfo = get_fast_modinfo($this->_customdata['courseid']); $mods = $modinfo->get_cms(); foreach ($mods as $mod) { $tools[$mod->context->id] = format_string($mod->name); } $mform->addElement('select', 'contextid', get_string('tooltobeprovide', 'local_ltiprovider'), $tools); $mform->setDefault('contextid', $context->id); $mform->addElement('checkbox', 'sendgrades', null, get_string('sendgrades', 'local_ltiprovider')); $mform->setDefault('sendgrades', 1); $mform->addElement('checkbox', 'forcenavigation', null, get_string('forcenavigation', 'local_ltiprovider')); $mform->setDefault('forcenavigation', 1); $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'local_ltiprovider'), array('optional' => true, 'defaultunit' => 86400)); $mform->setDefault('enrolperiod', 0); $mform->addHelpButton('enrolperiod', 'enrolperiod', 'local_ltiprovider'); $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate', 'local_ltiprovider'), array('optional' => true)); $mform->setDefault('enrolstartdate', 0); $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'local_ltiprovider'); $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate', 'local_ltiprovider'), array('optional' => true)); $mform->setDefault('enrolenddate', 0); $mform->addHelpButton('enrolenddate', 'enrolenddate', 'local_ltiprovider'); $mform->addElement('text', 'maxenrolled', get_string('maxenrolled', 'local_ltiprovider')); $mform->setDefault('maxenrolled', 0); $mform->addHelpButton('maxenrolled', 'maxenrolled', 'local_ltiprovider'); $mform->setType('maxenrolled', PARAM_INT); $assignableroles = get_assignable_roles($context); $mform->addElement('select', 'croleinst', get_string('courseroleinstructor', 'local_ltiprovider'), $assignableroles); $mform->setDefault('croleinst', '3'); $mform->setAdvanced('croleinst'); $mform->addElement('select', 'crolelearn', get_string('courserolelearner', 'local_ltiprovider'), $assignableroles); $mform->setDefault('crolelearn', '5'); $mform->setAdvanced('crolelearn'); $mform->addElement('select', 'aroleinst', get_string('activityroleinstructor', 'local_ltiprovider'), $assignableroles); $mform->disabledIf('aroleinst', 'contextid', 'eq', $context->id); $mform->setDefault('aroleinst', '3'); $mform->setAdvanced('aroleinst'); $mform->addElement('select', 'arolelearn', get_string('activityrolelearner', 'local_ltiprovider'), $assignableroles); $mform->disabledIf('arolelearn', 'contextid', 'eq', $context->id); $mform->setDefault('arolelearn', '5'); $mform->setAdvanced('arolelearn'); $mform->addElement('header', 'remotesystem', get_string('remotesystem', 'local_ltiprovider')); $mform->addElement('text', 'secret', get_string('secret', 'local_ltiprovider'), 'maxlength="64" size="25"'); $mform->setType('secret', PARAM_MULTILANG); $mform->setDefault('secret', md5(uniqid(rand(), 1))); $mform->addRule('secret', get_string('required'), 'required'); if (class_exists('textlib')) { $textlib = new textlib(); } else { try { // for older moodle instances $textlib = textlib_get_instance(); } catch (Exception $e) { // updated to use new core_text lib as required by Moodle 2.9 $textlib = new core_text(); } } $choices = $textlib->get_encodings(); $mform->addElement('select', 'encoding', get_string('remoteencoding', 'local_ltiprovider'), $choices); $mform->setDefault('encoding', 'UTF-8'); $mform->addElement('header', 'defaultheader', get_string('userdefaultvalues', 'local_ltiprovider')); $choices = array(0 => get_string('never'), 1 => get_string('always')); $mform->addElement('select', 'userprofileupdate', get_string('userprofileupdate', 'local_ltiprovider'), $choices); $userprofileupdate = get_config('local_ltiprovider', 'userprofileupdate'); if ($userprofileupdate != -1) { $mform->setDefault('userprofileupdate', $userprofileupdate); $mform->freeze('userprofileupdate'); } else { $mform->setDefault('userprofileupdate', 1); } $choices = array(0 => get_string('emaildisplayno'), 1 => get_string('emaildisplayyes'), 2 => get_string('emaildisplaycourse')); $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices); $mform->setDefault('maildisplay', 2); $mform->addElement('text', 'city', get_string('city'), 'maxlength="100" size="25"'); $mform->setType('city', PARAM_MULTILANG); if (empty($CFG->defaultcity)) { $mform->setDefault('city', $templateuser->city); } else { $mform->setDefault('city', $CFG->defaultcity); } $mform->addRule('city', get_string('required'), 'required'); $mform->addElement('select', 'country', get_string('selectacountry'), get_string_manager()->get_list_of_countries()); if (empty($CFG->country)) { $mform->setDefault('country', $templateuser->country); } else { $mform->setDefault('country', $CFG->country); } $mform->setAdvanced('country'); $choices = get_list_of_timezones(); $choices['99'] = get_string('serverlocaltime'); $mform->addElement('select', 'timezone', get_string('timezone'), $choices); $mform->setDefault('timezone', $templateuser->timezone); $mform->setAdvanced('timezone'); $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations()); $mform->setDefault('lang', $templateuser->lang); $mform->setAdvanced('lang'); $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"'); $mform->setType('institution', PARAM_MULTILANG); $mform->setDefault('institution', $templateuser->institution); $mform->setAdvanced('institution'); $mform->addElement('header', 'memberships', get_string('membershipsettings', 'local_ltiprovider')); $mform->addElement('checkbox', 'syncmembers', null, get_string('enablememberssync', 'local_ltiprovider')); $mform->disabledIf('syncmembers', 'contextid', 'neq', $context->id); $options = array(); $options[30 * 60] = '30 ' . get_string('minutes'); $options[60 * 60] = '1 ' . get_string('hour'); $options[2 * 60 * 60] = '2 ' . get_string('hours'); $options[6 * 60 * 60] = '6 ' . get_string('hours'); $options[12 * 60 * 60] = '12 ' . get_string('hours'); $options[24 * 60 * 60] = '24 ' . get_string('hours'); $mform->addElement('select', 'syncperiod', get_string('syncperiod', 'local_ltiprovider'), $options); $mform->setDefault('syncperiod', 30 * 60); $mform->disabledIf('syncperiod', 'contextid', 'neq', $context->id); $options = array(); $options[1] = get_string('enrolandunenrol', 'local_ltiprovider'); $options[2] = get_string('enrolnew', 'local_ltiprovider'); $options[3] = get_string('unenrolmissing', 'local_ltiprovider'); $mform->addElement('select', 'syncmode', get_string('syncmode', 'local_ltiprovider'), $options); $mform->setDefault('syncmode', 1); $mform->disabledIf('syncmode', 'contextid', 'neq', $context->id); $mform->addElement('header', 'layoutandcss', get_string('layoutandcss', 'local_ltiprovider')); $mform->addElement('checkbox', 'hidepageheader', null, get_string('hidepageheader', 'local_ltiprovider')); $mform->addElement('checkbox', 'hidepagefooter', null, get_string('hidepagefooter', 'local_ltiprovider')); $mform->addElement('checkbox', 'hideleftblocks', null, get_string('hideleftblocks', 'local_ltiprovider')); $mform->addElement('checkbox', 'hiderightblocks', null, get_string('hiderightblocks', 'local_ltiprovider')); $mform->setAdvanced('hideleftblocks'); $mform->setAdvanced('hiderightblocks'); $editoroptions = array(); $displayoptions = array('rows' => '4', 'cols' => ''); $mform->addElement('textarea', 'customcss', get_string('customcss', 'local_ltiprovider'), $displayoptions, $editoroptions); $mform->setAdvanced('customcss'); $mform->addElement('hidden', 'id'); $mform->setType('id', PARAM_INT); $mform->addElement('hidden', 'courseid'); $mform->setType('courseid', PARAM_INT); $this->add_action_buttons(); }
} } // Process incoming role unassignments if (optional_param('remove', false, PARAM_BOOL) && confirm_sesskey()) { $userstounassign = $currentuserselector->get_selected_users(); if (!empty($userstounassign)) { foreach ($userstounassign as $removeuser) { //unassign only roles that are added manually, no messing with other components!!! role_unassign($roleid, $removeuser->id, $context->id, ''); } $potentialuserselector->invalidate_selected_users(); $currentuserselector->invalidate_selected_users(); $rolename = $assignableroles[$roleid]; add_to_log($course->id, 'role', 'unassign', 'mod/adobeconnect/participant.php?contextid=' . $context->id . '&roleid=' . $roleid, $rolename, '', $USER->id); // Counts have changed, so reload. list($assignableroles, $assigncounts, $nameswithcounts) = get_assignable_roles($context, ROLENAME_BOTH, true); } } } $PAGE->set_pagelayout('admin'); $PAGE->set_title($title); switch ($context->contextlevel) { case CONTEXT_SYSTEM: admin_externalpage_setup('assignroles', '', array('contextid' => $contextid, 'roleid' => $roleid)); break; case CONTEXT_USER: $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context)); $PAGE->set_heading($fullname); $showroles = 1; break; case CONTEXT_COURSECAT:
$contexts[$conid]->children = array(); $contexts[$conid]->roleassignments = array(); } /// Put the contexts into a tree structure. foreach ($contexts as $conid => $con) { $context = context::instance_by_id($conid); $parentcontextid = get_parent_contextid($context); if ($parentcontextid) { $contexts[$parentcontextid]->children[] = $conid; } } /// Put the role capabilities into the context tree. foreach ($roleassignments as $ra) { $contexts[$ra->contextid]->roleassignments[$ra->roleid] = $ra; } $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); $overridableroles = get_overridable_roles($usercontext, ROLENAME_BOTH); /// Print the header $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $coursecontext)); $straction = get_string('thisusersroles', 'role'); $title = get_string('xroleassignments', 'role', $fullname); /// Course header $PAGE->set_title($title); if ($courseid != SITEID) { $PAGE->set_heading($fullname); } else { $PAGE->set_heading($course->fullname); } echo $OUTPUT->header(); echo $OUTPUT->heading($title, 3); echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthnormal');
/** * Gets all of the assignable roles for this course. * * @return array */ public function get_assignable_roles($otherusers = false) { if ($this->_assignableroles === null) { $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too } if ($otherusers) { if (!is_array($this->_assignablerolesothers)) { $this->_assignablerolesothers = array(); list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view'); foreach ($this->_assignableroles as $roleid => $role) { if (isset($courseviewroles[$roleid])) { $this->_assignablerolesothers[$roleid] = $role; } } } return $this->_assignablerolesothers; } else { return $this->_assignableroles; } }
/** * Returns mapping of all roles using short role name as index. * @return array */ function uu_allowed_roles_cache() { $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT); foreach ($allowedroles as $rid => $rname) { $rolecache[$rid] = new stdClass(); $rolecache[$rid]->id = $rid; $rolecache[$rid]->name = $rname; if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!! $rolecache[$rname] = new stdClass(); $rolecache[$rname]->id = $rid; $rolecache[$rname]->name = $rname; } } return $rolecache; }
function definition() { global $CFG, $DB; $mform = $this->_form; list($instance, $plugin, $course) = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('delayedcohort'); $groups = array(0 => get_string('none')); foreach (groups_get_all_groups($course->id) as $group) { $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext)); } $mform->addElement('header', 'general', get_string('pluginname', 'enrol_delayedcohort')); $mform->addElement('text', 'name', get_string('custominstancename', 'enrol')); $mform->setType('name', PARAM_TEXT); $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no')); $mform->addElement('select', 'status', get_string('status', 'enrol_delayedcohort'), $options); if ($instance->id) { if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) { $cohorts = array($instance->customint1 => format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)))); } else { $cohorts = array($instance->customint1 => get_string('error')); } $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts); $mform->setConstant('customint1', $instance->customint1); $mform->hardFreeze('customint1', $instance->customint1); } else { $cohorts = array('' => get_string('choosedots')); list($sqlparents, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids()); $sql = "SELECT id, name, idnumber, contextid\n FROM {cohort}\n WHERE contextid {$sqlparents}\n ORDER BY name ASC, idnumber ASC"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $c) { $context = context::instance_by_id($c->contextid); if (!has_capability('moodle/cohort:view', $context)) { continue; } $cohorts[$c->id] = format_string($c->name); } $rs->close(); $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('customint1', get_string('required'), 'required', null, 'client'); } $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // Descending default sortorder. $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_delayedcohort'), $roles); $mform->setDefault('roleid', $enrol->get_config('roleid')); if ($instance->id and !isset($roles[$instance->roleid])) { if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true); $roles[$instance->roleid] = role_get_name($role, $coursecontext); } else { $roles[$instance->roleid] = get_string('error'); } } $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_delayedcohort'), $groups); $mform->addElement('date_time_selector', 'customint3', get_string('triggerdate', 'enrol_delayedcohort'), array('optional' => true)); $mform->addElement('date_time_selector', 'customint4', get_string('enddate', 'enrol_delayedcohort'), array('optional' => true)); $mform->addElement('hidden', 'courseid', null); $mform->setType('courseid', PARAM_INT); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); if ($instance->id) { $this->add_action_buttons(true); } else { $this->add_action_buttons(true, get_string('addinstance', 'enrol')); } $this->set_data($instance); }
/** * Unassign roles from users * * @param array $unassignments An array of unassignment */ public static function unassign_roles($unassignments) { global $DB; // Do basic automatic PARAM checks on incoming data, using params description // If any problems are found then exceptions are thrown with helpful error messages $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments' => $unassignments)); $transaction = $DB->start_delegated_transaction(); foreach ($params['unassignments'] as $unassignment) { // Ensure the current user is allowed to run this function in the unassignment context $context = self::get_context_from_params($unassignment); self::validate_context($context); require_capability('moodle/role:assign', $context); // throw an exception if user is not able to unassign the role in this context $roles = get_assignable_roles($context, ROLENAME_SHORT); if (!array_key_exists($unassignment['roleid'], $roles)) { throw new invalid_parameter_exception('Can not unassign roleid=' . $unassignment['roleid'] . ' in contextid=' . $unassignment['contextid']); } role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id); } $transaction->allow_commit(); }
/** * Loads category specific settings in the navigation * * @return navigation_node */ protected function load_category_settings() { global $CFG; // We can land here while being in the context of a block, in which case we // should get the parent context which should be the category one. See self::initialise(). if ($this->context->contextlevel == CONTEXT_BLOCK) { $catcontext = $this->context->get_parent_context(); } else { $catcontext = $this->context; } // Let's make sure that we always have the right context when getting here. if ($catcontext->contextlevel != CONTEXT_COURSECAT) { throw new coding_exception('Unexpected context while loading category settings.'); } $categorynode = $this->add($catcontext->get_context_name(), null, null, null, 'categorysettings'); $categorynode->nodetype = navigation_node::NODETYPE_BRANCH; $categorynode->force_open(); if (can_edit_in_category($catcontext->instanceid)) { $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid)); $editstring = get_string('managecategorythis'); $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', '')); } if (has_capability('moodle/category:manage', $catcontext)) { $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid)); $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', '')); $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', '')); } // Assign local roles $assignableroles = get_assignable_roles($catcontext); if (!empty($assignableroles)) { $assignurl = new moodle_url('/' . $CFG->admin . '/roles/assign.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); } // Override roles if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) { $url = new moodle_url('/' . $CFG->admin . '/roles/permissions.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); } // Check role permissions if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $catcontext)) { $url = new moodle_url('/' . $CFG->admin . '/roles/check.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', '')); } // Cohorts if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) { $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); } // Manage filters if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) { $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', '')); } // Restore. if (has_capability('moodle/restore:restorecourse', $catcontext)) { $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', '')); } // Let plugins hook into category settings navigation. $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php'); foreach ($pluginsfunction as $plugintype => $plugins) { foreach ($plugins as $pluginfunction) { $pluginfunction($categorynode, $catcontext); } } return $categorynode; }
} else { if (!empty($courseid)) { // we need this for user tabs in user context if (!($course = get_record('course', 'id', $courseid))) { error('Invalid course id'); } } else { $courseid = SITEID; $course = clone $SITE; } } require_login($course); require_capability('moodle/role:assign', $context); /// needed for tabs.php $overridableroles = get_overridable_roles($context, 'name', ROLENAME_BOTH); $assignableroles = get_assignable_roles($context, 'name', ROLENAME_BOTH); /// Get some language strings $strpotentialusers = get_string('potentialusers', 'role'); $strexistingusers = get_string('existingusers', 'role'); $straction = get_string('assignroles', 'role'); $strroletoassign = get_string('roletoassign', 'role'); $strsearch = get_string('search'); $strshowall = get_string('showall'); $strparticipants = get_string('participants'); $strsearchresults = get_string('searchresults'); $unlimitedperiod = get_string('unlimited'); $defaultperiod = $course->enrolperiod; for ($i = 1; $i <= 365; $i++) { $seconds = $i * 86400; $periodmenu[$seconds] = get_string('numdays', '', $i); }
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); }
/** * Returns an array of available roles * @return array of availble roles */ function get_roles() { $context = get_context_instance(CONTEXT_SYSTEM); $roles = array(0 => get_string('anyrole', 'filters')) + get_assignable_roles($context); return $roles; }
/** * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out * what can be shown/done * * @param int $courseid The current course' id * @param int $userid The user id to load for * @param string $gstitle The string to pass to get_string for the branch title * @return navigation_node|false */ protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings') { global $DB, $CFG, $USER, $SITE; if ($courseid != $SITE->id) { if (!empty($this->page->course->id) && $this->page->course->id == $courseid) { $course = $this->page->course; } else { $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT c.*, {$select}\n FROM {course} c\n JOIN {context} ctx ON c.id = ctx.instanceid\n WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel"; $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE); $course = $DB->get_record_sql($sql, $params, MUST_EXIST); context_helper::preload_from_record($course); } } else { $course = $SITE; } $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context $systemcontext = get_system_context(); $currentuser = $USER->id == $userid; if ($currentuser) { $user = $USER; $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context } else { $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT u.*, {$select}\n FROM {user} u\n JOIN {context} ctx ON u.id = ctx.instanceid\n WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER); $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING); if (!$user) { return false; } context_helper::preload_from_record($user); // Check that the user can view the profile $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); if ($course->id == $SITE->id) { if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) return false; } } else { $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext); $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext); if (!$canviewusercourse && !$canviewuser || !can_access_course($course, $user->id)) { return false; } if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) { // If groups are in use, make sure we can see that group return false; } } } $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context)); $key = $gstitle; if ($gstitle != 'usercurrentsettings') { $key .= $userid; } // Add a user setting branch $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key); $usersetting->id = 'usersettings'; if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) { // Automatically start by making it active $usersetting->make_active(); } // Check if the user has been deleted if ($user->deleted) { if (!has_capability('moodle/user:update', $coursecontext)) { // We can't edit the user so just show the user deleted message $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING); } else { // We can edit the user so show the user deleted message and link it to the profile if ($course->id == $SITE->id) { $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id)); } else { $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id)); } $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); } return true; } $userauthplugin = false; if (!empty($user->auth)) { $userauthplugin = get_auth_plugin($user->auth); } // Add the profile edit link if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) { $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id)); $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING); } else { if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) { if ($userauthplugin && $userauthplugin->can_edit_profile()) { $url = $userauthplugin->edit_profile_url(); if (empty($url)) { $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id)); } $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING); } } } } // Change password link if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { $passwordchangeurl = $userauthplugin->change_password_url(); if (empty($passwordchangeurl)) { $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id)); } $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING); } // View the roles settings if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) { $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING); $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); if (!empty($assignableroles)) { $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); } if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) { $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); } $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); } // Portfolio if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) { require_once $CFG->libdir . '/portfoliolib.php'; if (portfolio_instances(true, false)) { $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id)); $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id)); $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); } } $enablemanagetokens = false; if (!empty($CFG->enablerssfeeds)) { $enablemanagetokens = true; } else { if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', get_system_context())) { $enablemanagetokens = true; } } // Security keys if ($currentuser && $enablemanagetokens) { $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey())); $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING); } // Repository if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) { if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) { require_once $CFG->dirroot . '/repository/lib.php'; $editabletypes = repository::get_editable_types($usercontext); $haseditabletypes = !empty($editabletypes); unset($editabletypes); $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes); } else { $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id}; } if ($haseditabletypes) { $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)); $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING); } } // Messaging if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) { $url = new moodle_url('/message/edit.php', array('id' => $user->id)); $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING); } // Blogs if ($currentuser && !empty($CFG->bloglevel)) { $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING); if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) { $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING); $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING); } } // Login as ... if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) { $url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'user' => $user->id, 'sesskey' => sesskey())); $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING); } return $usersetting; }
/** * Get the appropriate list of editing icons for a block. This is used * to set {@link block_contents::$controls} in {@link block_base::get_contents_for_output()}. * * @param $output The core_renderer to use when generating the output. (Need to get icon paths.) * @return an array in the format for {@link block_contents::$controls} */ public function edit_controls($block) { global $CFG; $controls = array(); $actionurl = $this->page->url->out(false, array('sesskey' => sesskey())); $blocktitle = $block->title; if (empty($blocktitle)) { $blocktitle = $block->arialabel; } if ($this->page->user_can_edit_blocks()) { // Move icon. $str = new lang_string('moveblock', 'block', $blocktitle); $controls[] = new action_menu_link_primary(new moodle_url($actionurl, array('bui_moveid' => $block->instance->id)), new pix_icon('t/move', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str, array('class' => 'editing_move')); } if ($this->page->user_can_edit_blocks() || $block->user_can_edit()) { // Edit config icon - always show - needed for positioning UI. $str = new lang_string('configureblock', 'block', $blocktitle); $controls[] = new action_menu_link_secondary(new moodle_url($actionurl, array('bui_editid' => $block->instance->id)), new pix_icon('t/edit', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str, array('class' => 'editing_edit')); } if ($this->page->user_can_edit_blocks() && $block->instance_can_be_hidden()) { // Show/hide icon. if ($block->instance->visible) { $str = new lang_string('hideblock', 'block', $blocktitle); $url = new moodle_url($actionurl, array('bui_hideid' => $block->instance->id)); $icon = new pix_icon('t/hide', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')); $attributes = array('class' => 'editing_hide'); } else { $str = new lang_string('showblock', 'block', $blocktitle); $url = new moodle_url($actionurl, array('bui_showid' => $block->instance->id)); $icon = new pix_icon('t/show', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')); $attributes = array('class' => 'editing_show'); } $controls[] = new action_menu_link_secondary($url, $icon, $str, $attributes); } // Display either "Assign roles" or "Permissions" or "Change permissions" icon (whichever first is available). $rolesurl = null; if (get_assignable_roles($block->context, ROLENAME_SHORT)) { $rolesurl = new moodle_url('/admin/roles/assign.php', array('contextid' => $block->context->id)); $str = new lang_string('assignrolesinblock', 'block', $blocktitle); $icon = 'i/assignroles'; } else { if (has_capability('moodle/role:review', $block->context) or get_overridable_roles($block->context)) { $rolesurl = new moodle_url('/admin/roles/permissions.php', array('contextid' => $block->context->id)); $str = get_string('permissions', 'role'); $icon = 'i/permissions'; } else { if (has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $block->context)) { $rolesurl = new moodle_url('/admin/roles/check.php', array('contextid' => $block->context->id)); $str = get_string('checkpermissions', 'role'); $icon = 'i/checkpermissions'; } } } if ($rolesurl) { // TODO: please note it is sloppy to pass urls through page parameters!! // it is shortened because some web servers (e.g. IIS by default) give // a 'security' error if you try to pass a full URL as a GET parameter in another URL. $return = $this->page->url->out(false); $return = str_replace($CFG->wwwroot . '/', '', $return); $rolesurl->param('returnurl', $return); $controls[] = new action_menu_link_secondary($rolesurl, new pix_icon($icon, $str, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str, array('class' => 'editing_roles')); } if ($this->user_can_delete_block($block)) { // Delete icon. $str = new lang_string('deleteblock', 'block', $blocktitle); $controls[] = new action_menu_link_secondary(new moodle_url($actionurl, array('bui_deleteid' => $block->instance->id)), new pix_icon('t/delete', $str, 'moodle', array('class' => 'iconsmall', 'title' => '')), $str, array('class' => 'editing_delete')); } return $controls; }