';
foreach ($courses as $course) {
- if ($course->visible == 1
- || has_capability('moodle/course:viewhiddencourses',$course->context)) {
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+ if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
echo '';
print_course($course);
echo " \n";
@@ -2151,11 +2151,7 @@ function print_courses($category) {
function print_course($course, $highlightterms = '') {
global $CFG, $USER, $DB, $OUTPUT;
- if (isset($course->context)) {
- $context = $course->context;
- } else {
- $context = get_context_instance(CONTEXT_COURSE, $course->id);
- }
+ $context = get_context_instance(CONTEXT_COURSE, $course->id);
// Rewrite file URLs so that they are correct
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', $course->id);
@@ -2172,7 +2168,6 @@ function print_course($course, $highlightterms = '') {
if (!empty($CFG->coursemanager)) {
$managerroles = split(',', $CFG->coursemanager);
- $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
$namesarray = array();
if (isset($course->managers)) {
if (count($course->managers)) {
@@ -2194,27 +2189,20 @@ function print_course($course, $highlightterms = '') {
}
$usersshown[] = $ra->user->id;
- if ($ra->hidden == 0 || $canseehidden) {
- $fullname = fullname($ra->user, $canviewfullnames);
- if ($ra->hidden == 1) {
- $status = " pix_url('t/show') . "\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
- } else {
- $status = '';
- }
+ $fullname = fullname($ra->user, $canviewfullnames);
- if (isset($aliasnames[$ra->roleid])) {
- $ra->rolename = $aliasnames[$ra->roleid]->name;
- }
-
- $namesarray[] = format_string($ra->rolename)
- . ': '
- . $fullname . ' ' . $status;
+ if (isset($aliasnames[$ra->roleid])) {
+ $ra->rolename = $aliasnames[$ra->roleid]->name;
}
+
+ $namesarray[] = format_string($ra->rolename)
+ . ': '
+ . $fullname . ' ';
}
}
} else {
$rusers = get_role_users($managerroles, $context,
- true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
+ true, '', 'r.sortorder ASC, u.lastname ASC');
if (is_array($rusers) && count($rusers)) {
$canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
@@ -2268,7 +2256,7 @@ function print_course($course, $highlightterms = '') {
function print_my_moodle() {
global $USER, $CFG, $DB, $OUTPUT;
- if (empty($USER->id)) {
+ if (!isloggedin() or isguestuser()) {
print_error('nopermissions', '', '', 'See My Moodle');
}
@@ -3402,43 +3390,6 @@ function update_course($data) {
return false;
}
-/**
- * Return all course participant for a given course
- * @global object $DB
- * @param integer $courseid
- * @return array of user
- */
-function get_course_participants ($courseid) {
- global $DB;
- $users = get_users_by_capability(
- get_context_instance(CONTEXT_COURSE, $courseid),
- 'moodle/course:view');
- return $users;
-}
-
-
-/**
- * Return true if the user is a participant for a given course
- * @global object $DB
- * @param integer $userid
- * @param integer $courseid
- * @return boolean
- */
-function is_course_participant ($userid, $courseid) {
- global $DB;
- $users = get_users_by_capability(
- get_context_instance(CONTEXT_COURSE, $courseid),
- 'moodle/course:view','u.id');
-
- foreach($users as $user) {
- if ($user->id == $userid) {
- return true;
- }
- }
-
- return false;
-}
-
function get_course_by_id ($id) {
global $DB;
return $DB->get_record('course', array('id' => $id));
@@ -3759,8 +3710,8 @@ class course_request {
if ($course->id) {
$course = $DB->get_record('course', array('id' => $course->id));
blocks_add_default_course_blocks($course);
- $course->context = get_context_instance(CONTEXT_COURSE, $course->id);
- role_assign($CFG->creatornewroleid, $this->properties->requester, 0, $course->context->id); // assing teacher role
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+ role_assign($CFG->creatornewroleid, $this->properties->requester, 0, $coursecontext->id); // assing teacher role
if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
// if we're all or requested we're ok.
$allowedmods = explode(',',$CFG->defaultallowedmodules);
@@ -3823,8 +3774,9 @@ class course_request {
$fs = get_file_storage();
$files = $fs->get_area_files(self::summary_editor_context()->id, self::summary_editor_filearea(), $this->properties->id);
foreach ($files as $file) {
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
if (!$file->is_directory()) {
- $filerecord = array('contextid'=>$course->context->id, 'filearea'=>'course_summary', 'itemid'=>$course->id, 'filepath'=>$file->get_filepath(), 'filename'=>$file->get_filename());
+ $filerecord = array('contextid'=>$coursecontext->id, 'filearea'=>'course_summary', 'itemid'=>$course->id, 'filepath'=>$file->get_filepath(), 'filename'=>$file->get_filename());
$fs->create_file_from_storedfile($filerecord, $file);
}
}
diff --git a/course/loginas.php b/course/loginas.php
index 29723e43b01..7714fe085a7 100644
--- a/course/loginas.php
+++ b/course/loginas.php
@@ -49,19 +49,19 @@
require_login();
if (has_capability('moodle/user:loginas', $systemcontext)) {
- if (has_capability('moodle/site:doanything', $systemcontext, $userid, false)) {
+ if (is_siteadmin($userid)) {
print_error('nologinas');
}
$context = $systemcontext;
} else {
require_login($course);
require_capability('moodle/user:loginas', $coursecontext);
- if (!has_capability('moodle/course:view', $coursecontext, $userid, false)) {
- print_error('usernotincourse');
- }
- if (has_capability('moodle/site:doanything', $coursecontext, $userid, false)) {
+ if (is_siteadmin($userid)) {
print_error('nologinas');
}
+ if (!is_enrolled($coursecontext, $userid)) {
+ print_error('usernotincourse');
+ }
$context = $coursecontext;
}
diff --git a/course/recent_form.php b/course/recent_form.php
index d90048a5c66..dc76b14e32c 100644
--- a/course/recent_form.php
+++ b/course/recent_form.php
@@ -52,14 +52,14 @@ class recent_form extends moodleform {
if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS) {
$groups = groups_get_user_groups($COURSE->id);
- $groups = $groups[0];
+ $group = $groups[0];
} else {
- $groups = '';
+ $group = '';
}
- if ($courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.id, u.firstname, u.lastname', 'lastname ASC, firstname DESC', '', '', $groups)) {
- foreach ($courseusers as $courseuser) {
- $options[$courseuser->id] = fullname($courseuser, $viewfullnames);
+ if ($enrolled = get_enrolled_users($context, null, $group, user_picture::fields('u'))) {
+ foreach ($enrolled as $euser) {
+ $options[$euser->id] = fullname($euser, $viewfullnames);
}
}
$mform->addElement('select', 'user', get_string('participants'), $options);
diff --git a/course/report/log/db/access.php b/course/report/log/db/access.php
index 18f079a0fcf..dbd4dab2aad 100644
--- a/course/report/log/db/access.php
+++ b/course/report/log/db/access.php
@@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
@@ -45,7 +45,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
@@ -58,7 +58,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
diff --git a/course/report/log/lib.php b/course/report/log/lib.php
index 336093d2cef..c9beb58265f 100644
--- a/course/report/log/lib.php
+++ b/course/report/log/lib.php
@@ -88,7 +88,7 @@ function print_mnet_log_selector_form($hostid, $course, $selecteduser=0, $select
// If looking at a different host, we're interested in all our site users
if ($hostid == $CFG->mnet_localhost_id && $course->id != SITEID) {
- $courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', $limitfrom, $limitnum, $selectedgroup,'', false);
+ $courseusers = get_users_by_capability($context, 'moodle/course:participate', 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', $limitfrom, $limitnum, $selectedgroup,'', false);
} else {
// this may be a lot of users :-(
$courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber', $limitfrom, $limitnum);
@@ -357,7 +357,7 @@ function print_log_selector_form($course, $selecteduser=0, $selecteddate='today'
$users = array();
if ($course->id != SITEID) {
- $courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', '','',$selectedgroup,null, false);
+ $courseusers = get_users_by_capability($context, 'moodle/course:participate', 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', '','',$selectedgroup,null, false);
} else {
// this may be a lot of users :-(
$courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber');
diff --git a/course/report/outline/db/access.php b/course/report/outline/db/access.php
index 328d0c70c4c..7e666ed521f 100644
--- a/course/report/outline/db/access.php
+++ b/course/report/outline/db/access.php
@@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
diff --git a/course/report/participation/db/access.php b/course/report/participation/db/access.php
index 5edafb640d4..341b5861674 100644
--- a/course/report/participation/db/access.php
+++ b/course/report/participation/db/access.php
@@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
diff --git a/course/report/participation/index.php b/course/report/participation/index.php
index ac588ebc37f..b8c81eddfe0 100644
--- a/course/report/participation/index.php
+++ b/course/report/participation/index.php
@@ -101,6 +101,7 @@
}
$roleoptions = array();
+ // TODO: we need a new list of roles that are visible here
if ($roles = get_roles_used_in_context($context)) {
foreach ($roles as $r) {
$roleoptions[$r->id] = $r->name;
diff --git a/course/report/progress/db/access.php b/course/report/progress/db/access.php
index 0e89482b70c..83035a34ad4 100644
--- a/course/report/progress/db/access.php
+++ b/course/report/progress/db/access.php
@@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
diff --git a/course/report/stats/db/access.php b/course/report/stats/db/access.php
index f99352889f1..25414ba1b75 100644
--- a/course/report/stats/db/access.php
+++ b/course/report/stats/db/access.php
@@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:viewreports',
diff --git a/course/search.php b/course/search.php
index 158779198aa..e28281fc372 100644
--- a/course/search.php
+++ b/course/search.php
@@ -225,11 +225,7 @@
if (!$adminediting) {
foreach ($courses as $course) {
- if (isset($course->context)) {
- $coursecontext = $course->context;
- } else {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- }
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$course->summary .= "";
$course->summary .= "$strcategory: category\">";
@@ -253,11 +249,7 @@
foreach ($courses as $course) {
- if (isset($course->context)) {
- $coursecontext = $course->context;
- } else {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- }
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$linkcss = $course->visible ? "" : " class=\"dimmed\" ";
diff --git a/course/user.php b/course/user.php
index 414bac2fd46..419b5fc4d60 100644
--- a/course/user.php
+++ b/course/user.php
@@ -54,7 +54,7 @@ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$personalcontext = get_context_instance(CONTEXT_USER, $user->id);
require_login();
-if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !has_capability('moodle/course:view', $coursecontext)) {
+if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !has_capability('moodle/course:participate', $coursecontext)) {
// do not require parents to be enrolled in courses ;-)
$PAGE->set_course($course);
} else {
diff --git a/enrol/authorize/db/access.php b/enrol/authorize/db/access.php
index 26973c2dba1..483ca77f56c 100644
--- a/enrol/authorize/db/access.php
+++ b/enrol/authorize/db/access.php
@@ -7,7 +7,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -16,7 +16,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/enrol/authorize/index.php b/enrol/authorize/index.php
index 7df2b8d538d..3fd83a85cd1 100644
--- a/enrol/authorize/index.php
+++ b/enrol/authorize/index.php
@@ -31,7 +31,7 @@
/// Only SITE users can access to this page
require_login(); // Don't use $courseid! User may want to see old orders.
- if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), $USER->id, false)) {
+ if (isguestuser()) {
print_error('noguest');
}
diff --git a/enrol/flatfile/enrol.php b/enrol/flatfile/enrol.php
index b91774220a3..e6a71073e94 100644
--- a/enrol/flatfile/enrol.php
+++ b/enrol/flatfile/enrol.php
@@ -197,12 +197,10 @@ function get_access_icons($course) {
if ($fields[1] == "student") {
- if ($teachers = get_users_by_capability($context, 'moodle/course:update', 'u.*,ra.hidden', 'ra.sortorder ASC')) {
+ // TODO: replace this with check for $CFG->couremanager, 'moodle/course:update' is definitely wrong
+ if ($teachers = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'ra.sortorder ASC')) {
foreach ($teachers as $u) {
- if (!$u->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) {
- $teacher = $u;
- break;
- }
+ $teacher = $u;
}
}
@@ -233,22 +231,19 @@ function get_access_icons($course) {
if (!empty($CFG->enrol_mailteachers) && $teachers) {
foreach($teachers as $teacher) {
+ $a->course = "$course->fullname";
+ $a->user = fullname($user);
- if (!$u->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) {
- $a->course = "$course->fullname";
- $a->user = fullname($user);
-
- $eventdata = new object();
- $eventdata->modulename = 'moodle';
- $eventdata->userfrom = $user;
- $eventdata->userto = $teacher;
- $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
- $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
- $eventdata->fullmessageformat = FORMAT_PLAIN;
- $eventdata->fullmessagehtml = '';
- $eventdata->smallmessage = '';
- message_send($eventdata);
- }
+ $eventdata = new object();
+ $eventdata->modulename = 'moodle';
+ $eventdata->userfrom = $user;
+ $eventdata->userto = $teacher;
+ $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
+ $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
+ $eventdata->fullmessageformat = FORMAT_PLAIN;
+ $eventdata->fullmessagehtml = '';
+ $eventdata->smallmessage = '';
+ message_send($eventdata);
}
}
}
diff --git a/enrol/manual/enrol.php b/enrol/manual/enrol.php
index 4f209c079cf..eeff29346ce 100644
--- a/enrol/manual/enrol.php
+++ b/enrol/manual/enrol.php
@@ -62,7 +62,7 @@ function print_entry($course) {
if ($course->password == '') { // no password, so enrol
- if (has_capability('moodle/legacy:guest', $context, $USER->id, false)) {
+ if (isguestuser()) {
add_to_log($course->id, 'course', 'guest', 'view.php?id='.$course->id, getremoteaddr());
} else if (empty($_GET['confirm']) && empty($_GET['cancel'])) {
@@ -404,19 +404,16 @@ function get_access_icons($course) {
* A bit clunky because I didn't want to change the standard strings
*/
function print_enrolmentkeyfrom($course) {
- global $CFG;
- global $USER;
+ global $CFG, $USER;
$context = get_context_instance(CONTEXT_SYSTEM);
- $guest = has_capability('moodle/legacy:guest', $context, $USER->id, false);
// if a keyholder role is defined we list teachers in that role (if any exist)
$contactslisted = false;
- $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
if (!empty($CFG->enrol_manual_keyholderrole)) {
- if ($contacts = get_role_users($CFG->enrol_manual_keyholderrole, get_context_instance(CONTEXT_COURSE, $course->id),true,'','u.lastname ASC',$canseehidden )) {
+ if ($contacts = get_role_users($CFG->enrol_manual_keyholderrole, get_context_instance(CONTEXT_COURSE, $course->id),true,'','u.lastname ASC')) {
// guest user has a slightly different message
- if ($guest) {
+ if (isguestuser()) {
print_string('enrolmentkeyfromguest', '', ': ' );
}
else {
@@ -444,7 +441,7 @@ function print_enrolmentkeyfrom($course) {
}
// guest user has a slightly different message
- if ($guest) {
+ if (isguestuser()) {
print_string('enrolmentkeyfromguest', '', $teachername );
}
else {
diff --git a/enrol/paypal/return.php b/enrol/paypal/return.php
index e4dc86bd89c..80c207280f2 100644
--- a/enrol/paypal/return.php
+++ b/enrol/paypal/return.php
@@ -25,7 +25,7 @@
$destination = "$CFG->wwwroot/course/view.php?id=$course->id";
}
- if (has_capability('moodle/course:view', $context)) {
+ if (has_capability('moodle/course:participate', $context)) {
redirect($destination, get_string('paymentthanks', '', $course->fullname));
} else { /// Somehow they aren't enrolled yet! :-(
diff --git a/filter/censor/filter.php b/filter/censor/filter.php
index 2a0fe1bbd2e..72b8c2ef08b 100644
--- a/filter/censor/filter.php
+++ b/filter/censor/filter.php
@@ -13,17 +13,11 @@
/// options to be filtered (In HTML form).
class censor_filter extends moodle_text_filter {
private function _canseecensor() {
- $cansee = false;
- $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
- if (has_capability('moodle/site:doanything', $context)) {
- $cansee = true;
- }
- return $cansee;
+ return is_siteadmin(); //TODO: add proper access control
}
function hash(){
$cap = "mod/filter:censor";
- $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
- if (has_capability('moodle/site:doanything', $context)) {
+ if (is_siteadmin()) { //TODO: add proper access control
$cap = "mod/filter:seecensor";
}
return $cap;
diff --git a/grade/export/ods/db/access.php b/grade/export/ods/db/access.php
index e160cd32e18..ba248d6b559 100644
--- a/grade/export/ods/db/access.php
+++ b/grade/export/ods/db/access.php
@@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/grade/export/txt/db/access.php b/grade/export/txt/db/access.php
index 3a9ba9e92b3..f3f8b11c5f0 100644
--- a/grade/export/txt/db/access.php
+++ b/grade/export/txt/db/access.php
@@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/grade/export/xls/db/access.php b/grade/export/xls/db/access.php
index cacc0b14766..c8242c4a084 100644
--- a/grade/export/xls/db/access.php
+++ b/grade/export/xls/db/access.php
@@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/grade/export/xml/db/access.php b/grade/export/xml/db/access.php
index 1c0aa516248..4843ffa233e 100644
--- a/grade/export/xml/db/access.php
+++ b/grade/export/xml/db/access.php
@@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/grade/import/csv/db/access.php b/grade/import/csv/db/access.php
index fc70ede19a8..b7791bf11c5 100644
--- a/grade/import/csv/db/access.php
+++ b/grade/import/csv/db/access.php
@@ -22,7 +22,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
);
diff --git a/grade/import/xml/db/access.php b/grade/import/xml/db/access.php
index 12124fb76dd..48cfe29163a 100644
--- a/grade/import/xml/db/access.php
+++ b/grade/import/xml/db/access.php
@@ -22,7 +22,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -30,7 +30,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
);
diff --git a/grade/report/grader/db/access.php b/grade/report/grader/db/access.php
index 98b75a71bc5..fcfe8247cab 100644
--- a/grade/report/grader/db/access.php
+++ b/grade/report/grader/db/access.php
@@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
);
diff --git a/grade/report/outcomes/db/access.php b/grade/report/outcomes/db/access.php
index bc8df5740bf..99e39a9a7ac 100644
--- a/grade/report/outcomes/db/access.php
+++ b/grade/report/outcomes/db/access.php
@@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/grade/report/overview/db/access.php b/grade/report/overview/db/access.php
index 3e3d97880f5..a358853819a 100644
--- a/grade/report/overview/db/access.php
+++ b/grade/report/overview/db/access.php
@@ -23,7 +23,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'student' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
diff --git a/grade/report/user/db/access.php b/grade/report/user/db/access.php
index a8b0e79fd62..eb460bc2027 100644
--- a/grade/report/user/db/access.php
+++ b/grade/report/user/db/access.php
@@ -25,7 +25,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
);
diff --git a/group/assign.php b/group/assign.php
index 2f1f8e6e4fc..8cf1249c2f7 100644
--- a/group/assign.php
+++ b/group/assign.php
@@ -90,8 +90,7 @@ if ($currentmembers) {
$coursemanagerroles = split(',', $managerroles);
foreach ($coursemanagerroles as $roleid) {
$role = $DB->get_record('role', array('id'=>$roleid));
- $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
- $managers = get_role_users($roleid, $context, true, 'u.id', 'u.id ASC', $canseehidden);
+ $managers = get_role_users($roleid, $context, true, 'u.id', 'u.id ASC');
}
}
} else {
diff --git a/group/autogroup.php b/group/autogroup.php
index 34057dc8a52..830ad5d005d 100644
--- a/group/autogroup.php
+++ b/group/autogroup.php
@@ -42,17 +42,8 @@ $error = '';
/// Get applicable roles
$rolenames = array();
-if ($roles = get_roles_used_in_context($context, true)) {
- $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
- $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext);
-
+if ($roles = get_profile_roles($context)) {
foreach ($roles as $role) {
- if (!isset($canviewroles[$role->id])) { // Avoid this role (eg course creator)
- continue;
- }
- if (isset($doanythingroles[$role->id])) { // Avoid this role (ie admin)
- continue;
- }
$rolenames[$role->id] = strip_tags(role_get_name($role, $context)); // Used in menus etc later on
}
}
diff --git a/group/externallib.php b/group/externallib.php
index 3dea054d1fe..8a732994415 100644
--- a/group/externallib.php
+++ b/group/externallib.php
@@ -368,8 +368,10 @@ class moodle_group_external extends external_api {
require_capability('moodle/course:managegroups', $context);
// now make sure user is enrolled in course - this is mandatory requirement,
- // unfortunately this is extermely slow
- require_capability('moodle/course:view', $context, $userid, false);
+ // unfortunately this is slow
+ if (!is_enrolled($context, $userid)) {
+ throw new invalid_parameter_exception('Only enrolled users may be members of groups');
+ }
groups_add_member($group, $user);
}
diff --git a/group/index.php b/group/index.php
index ce5e16b64e5..2c0eb1c9b8a 100644
--- a/group/index.php
+++ b/group/index.php
@@ -20,21 +20,18 @@ $userid = optional_param('user', false, PARAM_INT);
$action = groups_param_action();
// Support either single group= parameter, or array groups[]
if ($groupid) {
- $groupids=array($groupid);
+ $groupids = array($groupid);
} else {
$groupids = optional_param('groups', array(), PARAM_INT);
}
-$singlegroup=count($groupids) == 1;
+$singlegroup = (count($groupids) == 1);
$returnurl = $CFG->wwwroot.'/group/index.php?id='.$courseid;
// Get the course information so we can print the header and
// check the course id is valid
-if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
- $success = false;
- print_error('invalidcourse'); //'The course ID is invalid'
-}
+$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
$url = new moodle_url('/group/index.php', array('id'=>$courseid));
if ($userid) {
@@ -48,19 +45,19 @@ $PAGE->set_url($url);
// Make sure that the user has permissions to manage groups.
require_login($course);
-$context = get_context_instance(CONTEXT_COURSE, $courseid);
-if (! has_capability('moodle/course:managegroups', $context)) {
- redirect(); //"group.php?id=$course->id"); // Not allowed to see all groups
+$context = get_context_instance(CONTEXT_COURSE, $course->id);
+if (!has_capability('moodle/course:managegroups', $context)) {
+ redirect('/course/view.php', array('id'=>$course->id)); // Not allowed to manage all groups
}
// Check for multiple/no group errors
-if(!$singlegroup) {
+if (!$singlegroup) {
switch($action) {
case 'ajax_getmembersingroup':
case 'showgroupsettingsform':
case 'showaddmembersform':
case 'updatemembers':
- print_error('errorselectone','group',$returnurl);
+ print_error('errorselectone', 'group', $returnurl);
}
}
@@ -70,41 +67,41 @@ switch ($action) {
case 'ajax_getmembersingroup':
$roles = array();
- if ($groupmemberroles = groups_get_members_by_role($groupids[0],$courseid,'u.id,u.firstname,u.lastname')) {
+ if ($groupmemberroles = groups_get_members_by_role($groupids[0], $courseid, 'u.id,u.firstname,u.lastname')) {
foreach($groupmemberroles as $roleid=>$roledata) {
- $shortroledata=new StdClass;
- $shortroledata->name=$roledata->name;
- $shortroledata->users=array();
+ $shortroledata = new stdClass();
+ $shortroledata->name = $roledata->name;
+ $shortroledata->users = array();
foreach($roledata->users as $member) {
- $shortmember=new StdClass;
- $shortmember->id=$member->id;
- $shortmember->name=fullname($member, true);
- $shortroledata->users[]=$shortmember;
+ $shortmember = new stdClass();
+ $shortmember->id = $member->id;
+ $shortmember->name = fullname($member, true);
+ $shortroledata->users[] = $shortmember;
}
- $roles[]=$shortroledata;
+ $roles[] = $shortroledata;
}
}
echo json_encode($roles);
die; // Client side JavaScript takes it from here.
case 'deletegroup':
- if(count($groupids)==0) {
+ if (count($groupids) == 0) {
print_error('errorselectsome','group',$returnurl);
}
- $groupidlist=implode(',',$groupids);
- redirect('delete.php?courseid='.$courseid.'&groups='.$groupidlist);
+ $groupidlist = implode(',', $groupids);
+ redirect(new moodle_url('/group/delete.php', array('courseid'=>$courseid, 'groups'=>$groupidlist)));
break;
case 'showcreateorphangroupform':
- redirect('group.php?courseid='.$courseid);
+ redirect(new moodle_url('/group/group.php', array('courseid'=>$courseid)));
break;
case 'showautocreategroupsform':
- redirect('autogroup.php?courseid='.$courseid);
+ redirect(new moodle_url('/group/autogroup.php', array('courseid'=>$courseid)));
break;
case 'showgroupsettingsform':
- redirect('group.php?courseid='.$courseid.'&id='.$groupids[0]);
+ redirect(new moodle_url('/group/group.php', array('courseid'=>$courseid, 'id'=>$groupids[0])));
break;
case 'updategroups': //Currently reloading.
@@ -114,17 +111,15 @@ switch ($action) {
break;
case 'showaddmembersform':
- redirect('members.php?group='.$groupids[0]);
+ redirect(new moodle_url('/group/members.php', array('group'=>$groupids[0])));
break;
case 'updatemembers': //Currently reloading.
break;
default: //ERROR.
- if (debugging()) {
- print_error('unknowaction', '', $returnurl);
+ print_error('unknowaction', '', $returnurl);
break;
- }
}
// Print the page and form
diff --git a/group/lib.php b/group/lib.php
index 26e0f2ac8be..9274b2f2a70 100644
--- a/group/lib.php
+++ b/group/lib.php
@@ -40,7 +40,7 @@ function groups_add_member($grouporid, $userorid) {
}
//check if the user a participant of the group course
- if (!is_course_participant ($userid, $group->courseid)) {
+ if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $group->courseid), $userid)) {
return false;
}
@@ -487,25 +487,12 @@ function groups_delete_groupings($courseid, $showfeedback=false) {
* @return Array of role ID integers, or false if error/none.
*/
function groups_get_possible_roles($context) {
- $capability = 'moodle/course:view';
- $doanything = false;
+ $capability = 'moodle/course:participate';
// find all possible "student" roles
if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
- if (!$doanything) {
- if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
- return false; // Something is seriously wrong
- }
- $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
- }
-
$validroleids = array();
foreach ($possibleroles as $possiblerole) {
- if (!$doanything) {
- if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
- continue;
- }
- }
if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
$validroleids[] = $possiblerole->id;
@@ -529,64 +516,30 @@ function groups_get_possible_roles($context) {
* @param string $orderby The colum to sort users by
* @return array An array of the users
*/
-function groups_get_potential_members($courseid, $roleid = null, $orderby = 'lastname,firstname') {
+function groups_get_potential_members($courseid, $roleid = null, $orderby = 'lastname ASC, firstname ASC') {
global $DB;
$context = get_context_instance(CONTEXT_COURSE, $courseid);
- $sitecontext = get_context_instance(CONTEXT_SYSTEM);
- $rolenames = array();
- $avoidroles = array();
-
- if ($roles = get_roles_used_in_context($context, true)) {
-
- $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
- $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
-
- foreach ($roles as $role) {
- if (!isset($canviewroles[$role->id])) { // Avoid this role (eg course creator)
- $avoidroles[] = $role->id;
- unset($roles[$role->id]);
- continue;
- }
- if (isset($doanythingroles[$role->id])) { // Avoid this role (ie admin)
- $avoidroles[] = $role->id;
- unset($roles[$role->id]);
- continue;
- }
- $rolenames[$role->id] = strip_tags(role_get_name($role, $context)); // Used in menus etc later on
- }
- }
-
- if ($avoidroles) {
- list($adminroles, $params) = $DB->get_in_or_equal($avoidroles, SQL_PARAMS_NAMED, 'ar0', false);
- $adminroles = "AND r.roleid $adminroles";
- } else {
- $adminroles = "";
- $params = array();
- }
// we are looking for all users with this role assigned in this context or higher
- if ($usercontexts = get_parent_contexts($context)) {
- $listofcontexts = 'IN ('.implode(',', $usercontexts).')';
- } else {
- $listofcontexts = '='.$sitecontext->id.')'; // must be site
- }
+ $listofcontexts = get_related_contexts_string($context);
+ list($esql, $params) = get_enrolled_sql($context);
+
if ($roleid) {
- $selectrole = "AND r.roleid = :roleid";
$params['roleid'] = $roleid;
+ $where = "WHERE u.id IN (SELECT userid
+ FROM {role_assignments}
+ WHERE roleid = :roleid AND contextid $listofcontexts)";
} else {
- $selectrole = "";
+ $where = "";
}
$sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
FROM {user} u
- JOIN {role_assignments} r on u.id=r.userid
- WHERE (r.contextid = :contextid OR r.contextid $listofcontexts)
- AND u.deleted = 0 AND u.username != 'guest'
- $selectrole $adminroles
+ JOIN ($esql) e ON e.id = u.id
+ $where
ORDER BY $orderby";
- $params['contextid'] = $context->id;
return $DB->get_records_sql($sql, $params);
@@ -660,7 +613,7 @@ function groups_unassign_grouping($groupingid, $groupid) {
* @param string $fields List of fields from user table prefixed with u, default 'u.*'
* @param string $sort SQL ORDER BY clause, default 'u.lastname ASC'
* @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
- * @param array $whereparams any parameters required by $extrawheretest.
+ * @param array $whereparams any parameters required by $extrawheretest (named parameters).
* @return array Complex array as described above
*/
function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
@@ -681,11 +634,11 @@ function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
JOIN {user} u ON u.id = gm.userid
JOIN {role_assignments} ra ON ra.userid = u.id
JOIN {role} r ON r.id = ra.roleid
- WHERE gm.groupid=?
+ WHERE gm.groupid=:mgroupid
AND ra.contextid ".get_related_contexts_string($context).
$extrawheretest."
ORDER BY r.sortorder, $sort";
- array_unshift($whereparams, $groupid);
+ $whereparams['mgroupid'] = $groupid;
$rs = $DB->get_recordset_sql($sql, $whereparams);
return groups_calculate_role_people($rs, $context);
diff --git a/group/members.php b/group/members.php
index aa51780fb4c..1dd704b33b4 100644
--- a/group/members.php
+++ b/group/members.php
@@ -14,33 +14,26 @@ require_once($CFG->dirroot . '/user/selector/lib.php');
require_once($CFG->dirroot . '/course/lib.php');
$groupid = required_param('group', PARAM_INT);
+$cancel = optional_param('cancel', false, PARAM_BOOL);
-if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
- print_error('invalidgroupid');
-}
-
-if (!$course = $DB->get_record('course', array('id'=>$group->courseid))) {
- print_error('invalidcourse');
-}
-$courseid = $course->id;
+$group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
+$course = $DB->get_record('course', array('id'=>$group->courseid), '*', MUST_EXIST);
$PAGE->set_url('/groups/members.php', array('id'=>$groupid));
require_login($course);
-$context = get_context_instance(CONTEXT_COURSE, $courseid);
+$context = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:managegroups', $context);
-$returnurl = $CFG->wwwroot.'/group/index.php?id='.$courseid.'&group='.$group->id;
+$returnurl = $CFG->wwwroot.'/group/index.php?id='.$course->id.'&group='.$group->id;
-if (optional_param('cancel', false, PARAM_BOOL)) {
+if ($cancel) {
redirect($returnurl);
}
-$groupmembersselector = new group_members_selector('removeselect',
- array('groupid' => $groupid, 'courseid' => $course->id));
+$groupmembersselector = new group_members_selector('removeselect', array('groupid' => $groupid, 'courseid' => $course->id));
$groupmembersselector->set_extra_fields(array());
-$potentialmembersselector = new group_non_members_selector('addselect',
- array('groupid' => $groupid, 'courseid' => $course->id));
+$potentialmembersselector = new group_non_members_selector('addselect', array('groupid' => $groupid, 'courseid' => $course->id));
$potentialmembersselector->set_extra_fields(array());
if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) {
@@ -79,8 +72,8 @@ $groupname = format_string($group->name);
$PAGE->requires->yui2_lib('connection');
$PAGE->requires->js('/group/clientlib.js');
-$PAGE->navbar->add($strparticipants, new moodle_url('/user/index.php', array('id'=>$courseid)));
-$PAGE->navbar->add($strgroups, new moodle_url('/group/index.php', array('id'=>$courseid)));
+$PAGE->navbar->add($strparticipants, new moodle_url('/user/index.php', array('id'=>$course->id)));
+$PAGE->navbar->add($strgroups, new moodle_url('/group/index.php', array('id'=>$course->id)));
$PAGE->navbar->add($stradduserstogroup);
/// Print header
diff --git a/index.php b/index.php
index 68a5735d1a7..bc34b5302e9 100644
--- a/index.php
+++ b/index.php
@@ -62,7 +62,7 @@
set_moodle_cookie('nobody'); // To help search for cookies on login page
}
- if (!empty($USER->id)) {
+ if (isloggedin()) {
add_to_log(SITEID, 'course', 'view', 'view.php?id='.SITEID, SITEID);
}
@@ -142,7 +142,7 @@
print_error('cannotfindorcreateforum', 'forum');
}
- if (!empty($USER->id)) {
+ if (isloggedin()) {
$SESSION->fromdiscussion = $CFG->wwwroot;
$subtext = '';
if (forum_is_subscribed($USER->id, $newsforum)) {
diff --git a/lang/en_utf8/admin.php b/lang/en_utf8/admin.php
index 2f51165f424..afe5d105a4f 100644
--- a/lang/en_utf8/admin.php
+++ b/lang/en_utf8/admin.php
@@ -246,6 +246,7 @@ $string['configpathtodu'] = 'Path to du. Probably something like /usr/bin/du. If
$string['configperfdebug'] = 'If you turn this on, performance info will be printed in the footer of the standard theme';
$string['configprofilesforenrolledusersonly'] = 'To prevent misuse by spammers, profile descriptions of users who are not yet enrolled in any course are hidden. New users must enrol in at least one course before they can add a profile description.';
$string['configprotectusernames'] = 'By default forget_password.php does not display any hints that would allow guessing of usernames or email addresses.';
+$string['configprofileroles'] = 'List of roles that are visible on user profiles and participation page.';
$string['configproxybypass'] = 'Comma separated list of (partial) hostnames or IPs that should bypass proxy (e.g., 192.168., .mydomain.com)';
$string['configproxyhost'] = 'If this server needs to use a proxy computer (eg a firewall) to access the Internet, then provide the proxy hostname here. Otherwise leave it blank.';
$string['configproxypassword'] = 'Password needed to access internet through proxy if required, empty if none (PHP cURL extension required).';
@@ -737,6 +738,7 @@ $string['profilemenuoptions'] = 'Menu options (one per line)';
$string['profilemenutoofewoptions'] = 'You must provide at least 2 options';
$string['profilename'] = 'Name';
$string['profilenofieldsdefined'] = 'No fields have been defined';
+$string['profileroles'] = 'Profile visible roles';
$string['profileshortname'] = 'Short name (must be unique)';
$string['profileshortnamenotunique'] = 'This short name is already in use';
$string['profilesignup'] = 'Display on signup page?';
diff --git a/lang/en_utf8/role.php b/lang/en_utf8/role.php
index a62ba20174f..b0a5aa6fed3 100644
--- a/lang/en_utf8/role.php
+++ b/lang/en_utf8/role.php
@@ -14,6 +14,7 @@ $string['allowroletooverride'] = 'Allow users with role $a->fromrole to override
$string['allowroletoswitch'] = 'Allow users with role $a->fromrole to switch roles to the role $a->targetrole';
$string['allowswitch'] = 'Allow role switches';
$string['allsiteusers'] = 'All site users';
+$string['archetype'] = 'Role archetype';
$string['assignanotherrole'] = 'Assign another role';
$string['assignerror'] = 'Error while assigning the role $a->role to user $a->user.';
$string['assignrolenameincontext'] = 'Assign role \'$a->role\' in $a->context';
@@ -23,6 +24,14 @@ $string['assignrolesrelativetothisuser'] = 'Assign roles relative to this user';
$string['assignglobalroles'] = 'Assign system roles';
$string['assignmentcontext'] = 'Assignment context';
$string['assignmentoptions'] = 'Assignment options';
+$string['archetypecoursecreator'] = 'ARCHETYPE: Course Creator';
+$string['archetypeeditingteacher'] = 'ARCHETYPE: Teacher (editing)';
+$string['archetypefrontpage'] = 'ARCHETYPE: Authenticated user on frontpage';
+$string['archetypeguest'] = 'ARCHETYPE: Guest';
+$string['archetypemanager'] = 'ARCHETYPE: Manager';
+$string['archetypestudent'] = 'ARCHETYPE: Student';
+$string['archetypeteacher'] = 'ARCHETYPE: Teacher (non-editing)';
+$string['archetypeuser'] = 'ARCHETYPE: Authenticated user';
$string['backtoallroles'] = 'Back to the list of all roles';
$string['backup:backupcourse'] = 'Backup courses';
$string['backup:downloadfile'] = 'Download files from backup areas';
@@ -59,6 +68,8 @@ $string['chooseroletoassign'] = 'Please choose a role to assign';
$string['comment:delete'] = 'Delete comments';
$string['comment:post'] = 'Post comments';
$string['comment:view'] = 'Read comments';
+$string['confirmaddadmin'] = 'Do you really want to add user $a as new site administrator?';
+$string['confirmdeladmin'] = 'Do you really want to remove user $a from the list of site administrators?';
$string['context'] = 'Context';
$string['course:activityvisibility'] = 'Hide/show activities';
$string['course:bulkmessaging'] = 'Send a message to many people';
@@ -74,13 +85,14 @@ $string['course:managefiles'] = 'Manage files';
$string['course:managegroups'] = 'Manage groups';
$string['course:managemetacourse'] = 'Manage metacourse';
$string['course:managescales'] = 'Manage scales';
+$string['course:participate'] = 'Participate in courses';
$string['course:request'] = 'Request new courses';
$string['course:reset'] = 'Reset course';
$string['course:sectionvisibility'] = 'Control section visibility';
$string['course:setcurrentsection'] = 'Set current section';
$string['course:update'] = 'Update course settings';
$string['course:useremail'] = 'Enable/disable email address';
-$string['course:view'] = 'View courses';
+$string['course:view'] = 'View courses without participation';
$string['course:viewhiddenactivities'] = 'View hidden activities';
$string['course:viewhiddencourses'] = 'View hidden courses';
$string['course:viewhiddensections'] = 'View hidden sections';
@@ -110,14 +122,16 @@ $string['errorbadrolename'] = 'Incorrect role name';
$string['errorbadroleshortname'] = 'Incorrect role short name';
$string['errorexistsrolename'] = 'Role name already exists';
$string['errorexistsroleshortname'] = 'Role name already exists';
+$string['existingadmins'] = 'Current site administrators';
$string['existingusers'] = '$a existing users';
$string['explanation'] = 'Explanation';
$string['explainpermission'] = 'Explain permission';
$string['explainpermissionsinfo'] = 'To use this table:
First look to see if there are any Prohibits. If there are, has_capability will return false. Otherwise, read across the rows, left-to-right, top-to-bottom, and find the first cell where the number of Prevents and Allows are different. If there are more Allows than Prevents in that cell, then has_capability will return true, otherwise it will return false. If no cell has different numbers of Prevents and Allows, then has_capability will return false. ';
-$string['explainpermissionsdoanything'] = 'Note that this user has the moodle/site:doanything capability, so even though the table above shows that has_capability will return false, this user will actually be deemed to have the capability $a in most circumstances.';
$string['extusers'] = 'Existing users';
$string['extusersmatching'] = 'Existing users matching \'$a\'';
$string['filter:manage'] = 'Manage local filter settings';
+$string['frontpageuser'] = 'Authenticated user on frontpage';
+$string['frontpageuserdescription'] = 'All logged in users in the frontpage course.';
$string['globalrole'] = 'System role';
$string['globalroleswarning'] = 'WARNING! Any roles you assign from this page will apply to the assigned users throughout the entire system, including the front page and all the courses.';
$string['gotoassignroles'] = 'Go to Assign roles for this $a->contextlevel';
@@ -151,7 +165,10 @@ $string['legacy:user'] = 'LEGACY ROLE: Authenticated user';
$string['legacytype'] = 'Legacy role type';
$string['listallroles'] = 'List all roles';
$string['localroles'] = 'Locally assigned roles';
+$string['manageadmins'] = 'Manage site administrators';
$string['manageroles'] = 'Manage roles';
+$string['manager'] = 'Manager';
+$string['managerdescription'] = 'Managers can access course and modify them, they usually do not participate in courses.';
$string['maybeassignedin'] = 'Context types where this role may be assigned';
$string['metaassignerror'] = 'Can not assign this role to user \"$a\" because Manage metacourse capability is needed.';
$string['metaunassignerror'] = 'Role of user \"$a\" was automatically reassigned, please unassign the role in child courses instead.';
@@ -199,7 +216,7 @@ $string['question:viewall'] = 'View all questions';
$string['question:viewmine'] = 'View your own questions';
$string['resetrole'] = 'Reset to defaults';
$string['resetrolenolegacy'] = 'Clear permissions';
-$string['resetrolesure'] = 'Are you sure that you want to reset role \"$a->name ($a->shortname)\" to defaults?
The defaults are taken from the selected legacy capability ($a->legacytype).';
+$string['resetrolesure'] = 'Are you sure that you want to reset role \"$a->name ($a->shortname)\" to defaults?
The defaults are taken from the selected archetype ($a->legacytype).';
$string['resetrolesurenolegacy'] = 'Are you sure that you want to clear all permissions defined in this role \"$a->name ($a->shortname)\"?';
$string['restore:createuser'] = 'Create users on restore';
$string['restore:restorecourse'] = 'Restore courses';
@@ -226,6 +243,7 @@ $string['selectanotheruser'] = 'Select another user';
$string['selectrole'] = 'Select a role';
$string['showallroles'] = 'Show all roles';
$string['showthisuserspermissions'] = 'Show this user\'s permissions';
+$string['siteadministrators'] = 'Site administrators';
$string['site:accessallgroups'] = 'Access all groups';
$string['site:approvecourse'] = 'Approve course creation';
$string['site:backup'] = 'Backup courses';
diff --git a/lib/accesslib.php b/lib/accesslib.php
index f8cd300ef39..d26f2a029de 100755
--- a/lib/accesslib.php
+++ b/lib/accesslib.php
@@ -188,13 +188,13 @@ if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
$ACCESSLIB_PRIVATE = new stdClass;
$ACCESSLIB_PRIVATE->contexts = array(); // Cache of context objects by level and instance
$ACCESSLIB_PRIVATE->contextsbyid = array(); // Cache of context objects by id
-$ACCESSLIB_PRIVATE->systemcontext = null; // Used in get_system_context
-$ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache
+$ACCESSLIB_PRIVATE->systemcontext = NULL; // Used in get_system_context
+$ACCESSLIB_PRIVATE->dirtycontexts = NULL; // Dirty contexts cache
$ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
$ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
$ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
$ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
-$ACCESSLIB_PRIVATE->capabilitynames = null; // Used in is_valid_capability (only in developer debug mode)
+$ACCESSLIB_PRIVATE->capabilities = NULL; // detailed information about the capabilities
/**
* Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
@@ -213,13 +213,13 @@ function accesslib_clear_all_caches_for_unit_testing() {
}
$ACCESSLIB_PRIVATE->contexts = array();
$ACCESSLIB_PRIVATE->contextsbyid = array();
- $ACCESSLIB_PRIVATE->systemcontext = null;
- $ACCESSLIB_PRIVATE->dirtycontexts = null;
+ $ACCESSLIB_PRIVATE->systemcontext = NULL;
+ $ACCESSLIB_PRIVATE->dirtycontexts = NULL;
$ACCESSLIB_PRIVATE->accessdatabyuser = array();
$ACCESSLIB_PRIVATE->roledefinitions = array();
$ACCESSLIB_PRIVATE->croncache = array();
$ACCESSLIB_PRIVATE->preloadedcourses = array();
- $ACCESSLIB_PRIVATE->capabilitynames = null;
+ $ACCESSLIB_PRIVATE->capabilities = NULL;
unset($USER->access);
}
@@ -295,7 +295,7 @@ function get_role_context_caps($roleid, $context) {
* @global object
* @global object
* @param int $roleid
- * @param array $accessdata defaults to null
+ * @param array $accessdata defaults to NULL
* @return array
*/
function get_role_access($roleid, $accessdata=NULL) {
@@ -366,7 +366,7 @@ function get_role_access($roleid, $accessdata=NULL) {
* @global object
* @global object
* @param int $roleid
- * @param array $accessdata defaults to null
+ * @param array $accessdata defaults to NULL
* @return array
*/
function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
@@ -414,7 +414,7 @@ function get_guest_role() {
global $CFG, $DB;
if (empty($CFG->guestroleid)) {
- if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
+ if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
$guestrole = array_shift($roles); // Pick the first one
set_config('guestroleid', $guestrole->id);
return $guestrole;
@@ -441,16 +441,18 @@ function get_guest_role() {
* has_capability('mod/forum:replypost',$context)
*
* By default checks the capabilties of the current user, but you can pass a
- * different userid. By default will return true for admin-like users who have the
- * moodle/site:doanything capability, but you can override that with the fourth argument.
+ * different userid. By default will return true for admin users, but you can override that with the fourth argument.
+ *
+ * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
+ * or capabilities with XSS, config or data loss risks.
*
* @param string $capability the name of the capability to check. For example mod/forum:view
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
- * @param integer $userid A user id. By default (null) checks the permissions of the current user.
- * @param boolean $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
+ * @param integer|object $user A user id or object. By default (NULL) checks the permissions of the current user.
+ * @param boolean $doanything If false, ignores effect of admin role assignment
* @return boolean true if the user has this capability. Otherwise false.
*/
-function has_capability($capability, $context, $userid=NULL, $doanything=true) {
+function has_capability($capability, $context, $user = NULL, $doanything=true) {
global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
if (during_initial_install()) {
@@ -462,29 +464,36 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
}
}
+ if (strpos($capability, 'moodle/legacy:') === 0) {
+ throw new coding_exception('Legacy capabilities can not be used any more!');
+ }
+
// the original $CONTEXT here was hiding serious errors
// for security reasons do not reuse previous context
if (empty($context)) {
debugging('Incorrect context specified');
return false;
}
-
-/// Some sanity checks
- if (debugging('',DEBUG_DEVELOPER)) {
- if (!is_valid_capability($capability)) {
- debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
- }
- if (!is_bool($doanything)) {
- debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
- }
+ if (!is_bool($doanything)) {
+ throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
}
- if (empty($userid)) { // we must accept null, 0, '0', '' etc. in $userid
- if (empty($USER->id)) {
- // Session not set up yet.
- $userid = 0;
- } else {
- $userid = $USER->id;
+ // make sure there is a real user specified
+ if ($user === NULL) {
+ $userid = !empty($USER->id) ? $USER->id : 0;
+ } else {
+ $userid = !empty($user->id) ? $user->id : $user;
+ }
+
+ // capability must exist
+ if (!$capinfo = get_capability_info($capability)) {
+ debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
+ return false;
+ }
+ // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
+ if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
+ if (isguestuser($userid) or $userid == 0) {
+ return false;
}
}
@@ -546,6 +555,14 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
}
}
+ // Find out if user is admin - it is not possible to override the doanything in any way
+ // and it is not possible to switch to admin role either.
+ if ($doanything) {
+ if (is_siteadmin($userid)) {
+ return true;
+ }
+ }
+
// divulge how many times we are called
//// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
@@ -561,7 +578,7 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
//
if ($context->contextlevel <= CONTEXT_COURSE) {
// Course and above are always preloaded
- return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
+ return has_capability_in_accessdata($capability, $context, $USER->access);
}
// Load accessdata for below-the-course contexts
if (!path_inaccessdata($context->path,$USER->access)) {
@@ -570,15 +587,16 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
// error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
load_subcontext($USER->id, $context, $USER->access);
}
- return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
+ return has_capability_in_accessdata($capability, $context, $USER->access);
}
if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
load_user_accessdata($userid);
}
+
if ($context->contextlevel <= CONTEXT_COURSE) {
// Course and above are always preloaded
- return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid], $doanything);
+ return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
}
// Load accessdata for below-the-course contexts as needed
if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
@@ -587,7 +605,7 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
// error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
}
- return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid], $doanything);
+ return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
}
/**
@@ -603,8 +621,8 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
* @see has_capability()
* @param array $capabilities an array of capability names.
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
- * @param integer $userid A user id. By default (null) checks the permissions of the current user.
- * @param boolean $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
+ * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
+ * @param boolean $doanything If false, ignore effect of admin role assignment
* @return boolean true if the user has any of these capabilities. Otherwise false.
*/
function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
@@ -633,8 +651,8 @@ function has_any_capability($capabilities, $context, $userid=NULL, $doanything=t
* @see has_capability()
* @param array $capabilities an array of capability names.
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
- * @param integer $userid A user id. By default (null) checks the permissions of the current user.
- * @param boolean $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
+ * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
+ * @param boolean $doanything If false, ignore effect of admin role assignment
* @return boolean true if the user has all of these capabilities. Otherwise false.
*/
function has_all_capabilities($capabilities, $context, $userid=NULL, $doanything=true) {
@@ -651,101 +669,58 @@ function has_all_capabilities($capabilities, $context, $userid=NULL, $doanything
}
/**
- * Check if the user is an admin at the site level
+ * Check if the user is an admin at the site level.
*
- * Uses 1 DB query to answer whether a user is an admin at the sitelevel.
- * It depends on DB schema >=1.7 but does not depend on the new datastructures
- * in v1.9 (context.path, or $USER->access)
+ * Please note that use of proper capabilities is always encouraged,
+ * this function is supposed to be used from core or for temporary hacks.
*
- * Will return true if the userid has any of
- * - moodle/site:config
- * - moodle/legacy:admin
- * - moodle/site:doanything
- *
- * @global object
- * @global object
- * @param int $userid
- * @returns bool true is user can administer server settings
+ * @param int|object $user_or_id user id or user object
+ * @returns bool true if user is one of the administrators, false otherwise
*/
-function is_siteadmin($userid) {
- global $CFG, $DB;
+function is_siteadmin($user_or_id = NULL) {
+ global $CFG, $USER;
- $sql = "SELECT SUM(rc.permission)
- FROM {role_capabilities} rc
- JOIN {context} ctx
- ON ctx.id=rc.contextid
- JOIN {role_assignments} ra
- ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
- WHERE ctx.contextlevel=10
- AND ra.userid=?
- AND rc.capability IN (?, ?, ?)
- GROUP BY rc.capability
- HAVING SUM(rc.permission) > 0";
- $params = array($userid, 'moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
+ if ($user_or_id === NULL) {
+ $user_or_id = $USER;
+ }
- return $DB->record_exists_sql($sql, $params);
+ if (empty($user_or_id)) {
+ return false;
+ }
+ if (!empty($user_or_id->id)) {
+ // we support
+ $userid = $user_or_id->id;
+ } else {
+ $userid = $user_or_id;
+ }
+
+ $siteadmins = explode(',', $CFG->siteadmins);
+ return in_array($userid, $siteadmins);
}
/**
- * Check whether a role is an admin at the site level
- *
- * Will return true if the userid has any of
- * - moodle/site:config
- * - moodle/legacy:admin
- * - moodle/site:doanything
- *
- * @global object
- * @param integer $roleid a role id.
- * @return boolean, whether this role is an admin role.
+ * Returns true if user has at least one role assign
+ * of 'coursemanager' role (is potentially listed in some course descriptions).
+ * @param $userid
+ * @return unknown_type
*/
-function is_admin_role($roleid) {
+function has_coursemanager_role($userid) {
global $DB;
+ if (empty($CFG->coursemanager)) {
+ return false;
+ }
$sql = "SELECT 1
- FROM {role_capabilities} rc
- JOIN {context} ctx ON ctx.id = rc.contextid
- WHERE ctx.contextlevel = 10
- AND rc.roleid = ?
- AND rc.capability IN (?, ?, ?)
- GROUP BY rc.capability
- HAVING SUM(rc.permission) > 0";
- $params = array($roleid, 'moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
-
- return $DB->record_exists_sql($sql, $params);
-}
-
-/**
- * Returns all the roles for which is_admin_role($role->id) is true.
- *
- * @global object
- * @return array
- */
-function get_admin_roles() {
- global $DB;
-
- $sql = "SELECT *
- FROM {role} r
- WHERE EXISTS (
- SELECT 1
- FROM {role_capabilities} rc
- JOIN {context} ctx ON ctx.id = rc.contextid
- WHERE ctx.contextlevel = 10
- AND rc.roleid = r.id
- AND rc.capability IN (?, ?, ?)
- GROUP BY rc.capability
- HAVING SUM(rc.permission) > 0
- )
- ORDER BY r.sortorder";
- $params = array('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
-
- return $DB->get_records_sql($sql, $params);
+ FROM {role_assignments}
+ WHERE userid = :userid AND roleid IN ($CFG->coursemanager)";
+ return $DB->record_exists($sql, array('userid'=>$userid));
}
/**
* @param string $path
* @return string
*/
-function get_course_from_path ($path) {
+function get_course_from_path($path) {
// assume that nothing is more than 1 course deep
if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
return $matches[1];
@@ -759,6 +734,9 @@ function get_course_from_path ($path) {
* @return bool
*/
function path_inaccessdata($path, $accessdata) {
+ if (empty($accessdata['loaded'])) {
+ return false;
+ }
// assume that contexts hang from sys or from a course
// this will only work well with stuff that hangs from a course
@@ -813,23 +791,12 @@ function path_inaccessdata($path, $accessdata) {
* and then verify if user has at least one role with allow
* and at the same time no role with prohibit.
*
- * Incorrectly set Guest role as Default user role
- * -----------------------------------------------
- * Admins have to make sure that the "Default user role" does
- * not have 'moodle/course:view' or 'moodle/legacy:guest'!
- *
- * Incorrectly set Frontpage role
- * ------------------------------
- * Admins have to make sure that the "Frontpage role" does
- * not have 'moodle/legacy:guest'.
- *
* @param string $capability
* @param object $context
* @param array $accessdata
- * @param bool $doanything
* @return bool
*/
-function has_capability_in_accessdata($capability, $context, array $accessdata, $doanything) {
+function has_capability_in_accessdata($capability, $context, array $accessdata) {
global $CFG;
if (empty($context->id)) {
@@ -845,11 +812,6 @@ function has_capability_in_accessdata($capability, $context, array $accessdata,
}
unset($contextids);
- if ($doanything and strpos($capability, 'moodle/legacy:') === 0) {
- // admins do not have any legacy capabilities
- $doanything = false;
- }
-
$roles = array();
$switchedrole = false;
@@ -859,7 +821,7 @@ function has_capability_in_accessdata($capability, $context, array $accessdata,
foreach ($paths as $path) {
if (isset($accessdata['rsw'][$path])) {
// Found a switchrole assignment - check for that role _plus_ the default user role
- $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
+ $roles = array($accessdata['rsw'][$path]=>NULL, $CFG->defaultuserroleid=>NULL);
$switchedrole = true;
break;
}
@@ -871,25 +833,10 @@ function has_capability_in_accessdata($capability, $context, array $accessdata,
foreach ($paths as $path) {
if (isset($accessdata['ra'][$path])) {
foreach ($accessdata['ra'][$path] as $roleid) {
- $roles[$roleid] = null;
+ $roles[$roleid] = NULL;
}
}
}
-
- // Find out if user is admin - it is not possible to override the doanything in any way
- // and it is not possible to switch to admin role either.
- if ($doanything or $capability === 'moodle/site:doanything') {
- $systempath = '/'.SYSCONTEXTID;
- foreach ($roles as $roleid=>$ignored) {
- if (isset($accessdata['rdef']["{$systempath}:$roleid"]['moodle/site:doanything']) and $accessdata['rdef']["{$systempath}:$roleid"]['moodle/site:doanything'] == CAP_ALLOW) {
- return true;
- }
- }
- if ($capability === 'moodle/site:doanything') {
- // do anything can not be overridden, prevented or prohibited
- return false;
- }
- }
}
// Now find out what access is given to each role, going bottom-->up direction
@@ -958,8 +905,8 @@ function aggregate_roles_from_accessdata($context, $accessdata) {
*
* @param string $capability the name of the capability to check. For example mod/forum:view
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
- * @param integer $userid A user id. By default (null) checks the permissions of the current user.
- * @param bool $doanything If false, ignore the special moodle/site:doanything capability that admin-like roles have.
+ * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
+ * @param bool $doanything If false, ignore effect of admin role assignment
* @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
* @param string $stringfile The language file to load the error string from. Defaults to 'error'.
* @return void terminates with an error if the user does not have the given capability.
@@ -1015,13 +962,13 @@ function require_capability($capability, $context, $userid = NULL, $doanything =
* @global object
* @param string $capability - name of the capability
* @param array $accessdata - accessdata session array
- * @param bool $doanything - if false, ignore do anything
+ * @param bool $doanything_ignored - admin roles are completely ignored here
* @param string $sort - sorting fields - prefix each fieldname with "c."
* @param array $fields - additional fields you are interested in...
* @param int $limit - set if you want to limit the number of courses
* @return array $courses - ordered array of course objects - see notes above
*/
-function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
+function get_user_courses_bycap($userid, $cap, $accessdata, $doanything_ignored, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
global $CFG, $DB;
@@ -1047,7 +994,7 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
}
$sysctx = get_context_instance(CONTEXT_SYSTEM);
- if (has_capability_in_accessdata($cap, $sysctx, $accessdata, $doanything)) {
+ if (has_capability_in_accessdata($cap, $sysctx, $accessdata)) {
//
// Apparently the user has the cap sitewide, so walk *every* course
// (the cap checks are moderately fast, but this moves massive bandwidth w the db)
@@ -1080,7 +1027,7 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
$catpaths = array();
foreach ($rs as $catctx) {
if ($catctx->path != ''
- && has_capability_in_accessdata($cap, $catctx, $accessdata, $doanything)) {
+ && has_capability_in_accessdata($cap, $catctx, $accessdata)) {
$catpaths[] = $catctx->path;
}
}
@@ -1096,12 +1043,6 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
}
unset($catpaths);
- $capany = '';
- if ($doanything) {
- $capany = " OR rc.capability=:doany";
- $params['doany'] = 'moodle/site:doanything';
- }
-
/// UNION 3 queries:
/// - user role assignments in courses
/// - user capability (override - any status) in courses
@@ -1109,11 +1050,11 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
/// Enclosing the 3-UNION into an inline_view to avoid column names conflict and making the ORDER BY cross-db
/// and to allow selection of TEXT columns in the query (MSSQL and Oracle limitation). MDL-16209
$sql = "
- SELECT $coursefields, ctxid, ctxpath, ctxdepth, ctxlevel, categorypath
+ SELECT $coursefields, ctxid, ctxpath, ctxdepth, ctxlevel, ctxinstance, categorypath
FROM (
SELECT c.id,
ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
+ ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel, ctx.instanceid AS ctxinstance,
cc.path AS categorypath
FROM {course} c
JOIN {course_categories} cc
@@ -1125,7 +1066,7 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
UNION
SELECT c.id,
ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
+ ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel, ctx.instanceid AS ctxinstance,
cc.path AS categorypath
FROM {course} c
JOIN {course_categories} cc
@@ -1133,14 +1074,14 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
JOIN {context} ctx
ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
JOIN {role_capabilities} rc
- ON (rc.contextid=ctx.id AND (rc.capability=:cap $capany)) ";
+ ON (rc.contextid=ctx.id AND (rc.capability=:cap)) ";
if (!empty($catclause)) { /// If we have found the right in categories, add child courses here too
$sql .= "
UNION
SELECT c.id,
ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
+ ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel, ctx.instanceid AS ctxinstance,
cc.path AS categorypath
FROM {course} c
JOIN {course_categories} cc
@@ -1171,9 +1112,10 @@ function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='
if ($rs) {
foreach ($rs as $c) {
// build the context obj
- $c = make_context_subobj($c);
+ context_instance_preload($c);
+ $context = get_context_instance(CONTEXT_COURSE, $c->id);
- if (has_capability_in_accessdata($cap, $c->context, $accessdata, $doanything)) {
+ if (has_capability_in_accessdata($cap, $context, $accessdata)) {
if ($limit > 0 && $cc >= $limit) {
break;
}
@@ -1489,7 +1431,7 @@ function load_subcontext($userid, $context, &$accessdata) {
* @global object
* @param integer $roleid the id of the user
* @param object $context needs path!
- * @param array $accessdata accessdata array null by default
+ * @param array $accessdata accessdata array NULL by default
* @return array
*/
function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
@@ -1850,46 +1792,23 @@ function check_enrolment_plugins(&$user) {
}
/**
- * Returns array of all legacy roles.
+ * Returns array of all role archetypes.
*
* @return array
*/
-function get_legacy_roles() {
+function get_role_archetypes() {
return array(
- 'admin' => 'moodle/legacy:admin',
- 'coursecreator' => 'moodle/legacy:coursecreator',
- 'editingteacher' => 'moodle/legacy:editingteacher',
- 'teacher' => 'moodle/legacy:teacher',
- 'student' => 'moodle/legacy:student',
- 'guest' => 'moodle/legacy:guest',
- 'user' => 'moodle/legacy:user'
+ 'manager' => 'manager',
+ 'coursecreator' => 'coursecreator',
+ 'editingteacher' => 'editingteacher',
+ 'teacher' => 'teacher',
+ 'student' => 'student',
+ 'guest' => 'guest',
+ 'user' => 'user',
+ 'frontpage' => 'frontpage'
);
}
-/**
- * @param int roleid
- * @return string
- */
-function get_legacy_type($roleid) {
- $sitecontext = get_context_instance(CONTEXT_SYSTEM);
- $legacyroles = get_legacy_roles();
-
- $result = '';
- foreach($legacyroles as $ltype=>$lcap) {
- $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
- if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
- //choose first selected legacy capability - reset the rest
- if (empty($result)) {
- $result = $ltype;
- } else {
- unassign_capability($lcap, $roleid);
- }
- }
- }
-
- return $result;
-}
-
/**
* Assign the defaults found in this capabality definition to roles that have
* the corresponding legacy capabilities assigned to them.
@@ -1901,22 +1820,26 @@ function get_legacy_type($roleid) {
* 'teacher' => CAP_ALLOW,
* 'editingteacher' => CAP_ALLOW,
* 'coursecreator' => CAP_ALLOW,
- * 'admin' => CAP_ALLOW
+ * 'manager' => CAP_ALLOW
* @return boolean success or failure.
*/
function assign_legacy_capabilities($capability, $legacyperms) {
- $legacyroles = get_legacy_roles();
+ $archetypes = get_role_archetypes();
foreach ($legacyperms as $type => $perm) {
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
+ if ($type === 'admin') {
+ debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
+ $type = 'manager';
+ }
- if (!array_key_exists($type, $legacyroles)) {
+ if (!array_key_exists($type, $archetypes)) {
print_error('invalidlegacy', '', '', $type);
}
- if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
+ if ($roles = get_archetype_roles($type)) {
foreach ($roles as $role) {
// Assign a site level capability.
if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
@@ -1928,24 +1851,6 @@ function assign_legacy_capabilities($capability, $legacyperms) {
return true;
}
-
-/**
- * Checks to see if a capability is one of the special capabilities
- *
- * Checks to see if a capability is one of the special capabilities
- * (either a legacy capability, or moodle/site:doanything).
- *
- * @param string $capabilityname the capability name, e.g. mod/forum:view.
- * @return boolean whether this is one of the special capabilities.
- */
-function is_legacy($capabilityname) {
- if ($capabilityname == 'moodle/site:doanything' || strpos($capabilityname, 'moodle/legacy') === 0) {
- return true;
- } else {
- return false;
- }
-}
-
/**
* @param object $capability a capbility - a row from the capabilitites table.
* @return boolean whether this capability is safe - that is, wether people with the
@@ -1969,9 +1874,10 @@ function is_safe_capability($capability) {
* @global object
* @param int $contextlevel
* @param int $instanceid
+ * @param int $strictness
* @return object newly created context
*/
-function create_context($contextlevel, $instanceid) {
+function create_context($contextlevel, $instanceid, $strictness=IGNORE_MISSING) {
global $CFG, $DB;
@@ -1989,7 +1895,7 @@ function create_context($contextlevel, $instanceid) {
$basedepth = 1;
$result = true;
- $error_message = null;
+ $error_message = NULL;
switch ($contextlevel) {
case CONTEXT_COURSECAT:
@@ -2002,7 +1908,7 @@ function create_context($contextlevel, $instanceid) {
if ($p = $DB->get_record_sql($sql, $params)) {
$basepath = $p->path;
$basedepth = $p->depth;
- } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid))) {
+ } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), '*', $strictness)) {
if (empty($category->parent)) {
// ok - this is a top category
} else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
@@ -2010,7 +1916,7 @@ function create_context($contextlevel, $instanceid) {
$basedepth = $parent->depth;
} else {
// wrong parent category - no big deal, this can be fixed later
- $basepath = null;
+ $basepath = NULL;
$basedepth = 0;
}
} else {
@@ -2030,7 +1936,7 @@ function create_context($contextlevel, $instanceid) {
if ($p = $DB->get_record_sql($sql, $params)) {
$basepath = $p->path;
$basedepth = $p->depth;
- } else if ($course = $DB->get_record('course', array('id'=>$instanceid))) {
+ } else if ($course = $DB->get_record('course', array('id'=>$instanceid), '*', $strictness)) {
if ($course->id == SITEID) {
//ok - no parent category
} else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
@@ -2038,7 +1944,7 @@ function create_context($contextlevel, $instanceid) {
$basedepth = $parent->depth;
} else {
// wrong parent category of course - no big deal, this can be fixed later
- $basepath = null;
+ $basepath = NULL;
$basedepth = 0;
}
} else if ($instanceid == SITEID) {
@@ -2061,8 +1967,8 @@ function create_context($contextlevel, $instanceid) {
if ($p = $DB->get_record_sql($sql, $params)) {
$basepath = $p->path;
$basedepth = $p->depth;
- } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid))) {
- if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
+ } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), '*', $strictness)) {
+ if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course, $strictness)) {
$basepath = $parent->path;
$basedepth = $parent->depth;
} else {
@@ -2083,7 +1989,7 @@ function create_context($contextlevel, $instanceid) {
JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
WHERE bi.id = ?";
$params = array($instanceid, CONTEXT_COURSE);
- if ($p = $DB->get_record_sql($sql, $params)) {
+ if ($p = $DB->get_record_sql($sql, $params, '*', $strictness)) {
$basepath = $p->path;
$basedepth = $p->depth;
} else {
@@ -2102,24 +2008,24 @@ function create_context($contextlevel, $instanceid) {
$context->depth = $basedepth+1;
}
- if ($result and $id = $DB->insert_record('context', $context)) {
- // can't set the full path till we know the id!
- if ($basedepth != 0 and !empty($basepath)) {
- $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
- }
- return get_context_instance_by_id($id);
-
- } else {
+ if (!$result) {
debugging('Error: could not insert new context level "'.
s($contextlevel).'", instance "'.
s($instanceid).'". ' . $error_message);
return false;
}
+
+ $id = $DB->insert_record('context', $context);
+ // can't set the full path till we know the id!
+ if ($basedepth != 0 and !empty($basepath)) {
+ $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
+ }
+ return get_context_instance_by_id($id);
}
/**
- * Returns system context or null if can not be created yet.
+ * Returns system context or NULL if can not be created yet.
*
* @todo can not use get_record() because we do not know if query failed :-(
* switch to get_record() later
@@ -2127,7 +2033,7 @@ function create_context($contextlevel, $instanceid) {
* @global object
* @global object
* @param bool $cache use caching
- * @return mixed system context or null
+ * @return mixed system context or NULL
*/
function get_system_context($cache=true) {
global $DB, $ACCESSLIB_PRIVATE;
@@ -2146,7 +2052,7 @@ function get_system_context($cache=true) {
$context = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM));
} catch (dml_exception $e) {
//table does not exist yet, sorry
- return null;
+ return NULL;
}
if (!$context) {
@@ -2160,7 +2066,7 @@ function get_system_context($cache=true) {
$context->id = $DB->insert_record('context', $context);
} catch (dml_exception $e) {
// can not create context yet, sorry
- return null;
+ return NULL;
}
}
@@ -2227,7 +2133,7 @@ function delete_context($contextlevel, $instanceid) {
* @param bool $buildpaths update paths and depths
* @return void
*/
-function create_contexts($contextlevel=null, $buildpaths=true) {
+function create_contexts($contextlevel=NULL, $buildpaths=true) {
global $DB;
//make sure system context exists
@@ -2404,9 +2310,11 @@ function preload_course_contexts($courseid) {
* @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
* @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
* for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
+ * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
+ * MUST_EXIST means throw exception if no record or multiple records found
* @return object The context object.
*/
-function get_context_instance($contextlevel, $instance=0) {
+function get_context_instance($contextlevel, $instance=0, $strictness=IGNORE_MISSING) {
global $DB, $ACCESSLIB_PRIVATE;
static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
@@ -2439,7 +2347,7 @@ function get_context_instance($contextlevel, $instance=0) {
/// Get it from the database, or create it
if (!$context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instance))) {
- $context = create_context($contextlevel, $instance);
+ $context = create_context($contextlevel, $instance, $strictness);
}
/// Only add to cache if context isn't empty.
@@ -2544,8 +2452,8 @@ function get_context_info_array($contextid) {
global $DB;
$context = get_context_instance_by_id($contextid, MUST_EXIST);
- $course = null;
- $cm = null;
+ $course = NULL;
+ $cm = NULL;
if ($context->contextlevel == CONTEXT_COURSE) {
$course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
@@ -2582,12 +2490,22 @@ function get_context_info_array($contextid) {
* @param string $name role name
* @param string $shortname role short name
* @param string $description role description
- * @param string $legacy optional legacy capability
+ * @param string $archetype
* @return mixed id or dml_exception
*/
-function create_role($name, $shortname, $description, $legacy='') {
+function create_role($name, $shortname, $description, $archetype='') {
global $DB;
+ if (strpos($archetype, 'moodle/legacy:') !== false) {
+ throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
+ }
+
+ // verify role archetype actually exists
+ $archetypes = get_role_archetypes();
+ if (empty($archetypes[$archetype])) {
+ $archetype = '';
+ }
+
// Get the system context.
$context = get_context_instance(CONTEXT_SYSTEM);
@@ -2596,6 +2514,7 @@ function create_role($name, $shortname, $description, $legacy='') {
$role->name = $name;
$role->shortname = $shortname;
$role->description = $description;
+ $role->archetype = $archetype;
//find free sortorder number
$role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
@@ -2604,83 +2523,39 @@ function create_role($name, $shortname, $description, $legacy='') {
}
$id = $DB->insert_record('role', $role);
- if ($legacy) {
- assign_capability($legacy, CAP_ALLOW, $id, $context->id);
- }
-
return $id;
}
/**
* Function that deletes a role and cleanups up after it
*
- * @global object
- * @global object
* @param int $roleid id of role to delete
- * @return bool
+ * @return bool lways true
*/
function delete_role($roleid) {
global $CFG, $DB;
- $success = true;
-// mdl 10149, check if this is the last active admin role
-// if we make the admin role not deletable then this part can go
+ // first unssign all users
+ role_unassign($roleid);
- $systemcontext = get_context_instance(CONTEXT_SYSTEM);
+ // cleanup all references to this role, ignore errors
+ $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
+ $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
+ $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
+ $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
+ $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
+ $DB->delete_records('role_names', array('roleid'=>$roleid));
+ $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
- if ($role = $DB->get_record('role', array('id'=>$roleid))) {
- if ($DB->record_exists('role_capabilities', array('contextid'=>$systemcontext->id, 'roleid'=>$roleid, 'capability'=>'moodle/site:doanything'))) {
- // deleting an admin role
- $status = false;
- if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
- foreach ($adminroles as $adminrole) {
- if ($adminrole->id != $roleid) {
- // some other admin role
- if ($DB->record_exists('role_assignments', array('roleid'=>$adminrole->id, 'contextid'=>$systemcontext->id))) {
- // found another admin role with at least 1 user assigned
- $status = true;
- break;
- }
- }
- }
- }
- if ($status !== true) {
- print_error('cannotdeleterolenoadmin', 'access');
- }
- }
- }
-
-// first unssign all users
- if (!role_unassign($roleid)) {
- debugging("Error while unassigning all users from role with ID $roleid!");
- $success = false;
- }
-
-// cleanup all references to this role, ignore errors
- if ($success) {
- $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
- $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
- $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
- $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
- $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
- $DB->delete_records('role_names', array('roleid'=>$roleid));
- $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
- }
-
-// finally delete the role itself
+ // finally delete the role itself
// get this before the name is gone for logging
$rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
- if ($success and !$DB->delete_records('role', array('id'=>$roleid))) {
- debugging("Could not delete role record with ID $roleid!");
- $success = false;
- }
+ $DB->delete_records('role', array('id'=>$roleid));
- if ($success) {
- add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
- }
+ add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
- return $success;
+ return true;
}
/**
@@ -2696,7 +2571,6 @@ function delete_role($roleid) {
* @return bool
*/
function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
-
global $USER, $DB;
if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
@@ -2720,11 +2594,12 @@ function assign_capability($capability, $permission, $roleid, $contextid, $overw
if ($existing) {
$cap->id = $existing->id;
- return $DB->update_record('role_capabilities', $cap);
+ $DB->update_record('role_capabilities', $cap);
} else {
$c = $DB->get_record('context', array('id'=>$contextid));
- return $DB->insert_record('role_capabilities', $cap);
+ $DB->insert_record('role_capabilities', $cap);
}
+ return true;
}
/**
@@ -2738,15 +2613,13 @@ function assign_capability($capability, $permission, $roleid, $contextid, $overw
function unassign_capability($capability, $roleid, $contextid=NULL) {
global $DB;
- if (isset($contextid)) {
+ if (!empty($contextid)) {
// delete from context rel, if this is the last override in this context
- $status = $DB->delete_records('role_capabilities', array('capability'=>$capability,
- 'roleid'=>$roleid, 'contextid'=>$contextid));
+ $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$contextid));
} else {
- $status = $DB->delete_records('role_capabilities', array('capability'=>$capability,
- 'roleid'=>$roleid));
+ $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
}
- return $status;
+ return true;
}
@@ -2759,13 +2632,12 @@ function unassign_capability($capability, $roleid, $contextid=NULL) {
* @global object
* @global object
* @param string $capability - capability name (string)
- * @param null $permission - optional, the permission defined for this capability
+ * @param string $permission - optional, the permission defined for this capability
* either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to NULL
* @param object $contect
* @return mixed array or role objects
*/
-function get_roles_with_capability($capability, $permission=NULL, $context='') {
-
+function get_roles_with_capability($capability, $permission=NULL, $context=NULL) {
global $CFG, $DB;
$params = array();
@@ -2802,21 +2674,18 @@ function get_roles_with_capability($capability, $permission=NULL, $context='') {
/**
* This function makes a role-assignment (a role for a user or group in a particular context)
*
- * @global object
- * @global object
- * @global object
* @param int $roleid the role of the id
* @param int $userid userid
* @param int $groupid group id
* @param int $contextid id of the context
* @param int $timestart time this assignment becomes effective defaults to 0
* @param int $timeend time this assignemnt ceases to be effective defaults to 0
- * @param int $hidden defaults to 0
+ * @param int $hidden_ignored - use roels with moodle/course:view capability or enrolemnt instead
* @param string $enrol defaults to 'manual'
* @param string $timemodified defaults to ''
* @return int new id of the assigment
*/
-function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
+function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden_ignored=0, $enrol='manual',$timemodified='') {
global $USER, $CFG, $DB;
/// Do some data validation
@@ -2867,7 +2736,6 @@ function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $time
$ra->roleid = $roleid;
$ra->contextid = $context->id;
$ra->userid = $userid;
- $ra->hidden = $hidden;
$ra->enrol = $enrol;
/// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
/// by repeating queries with the same exact parameters in a 100 secs time window
@@ -2880,7 +2748,6 @@ function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $time
} else { // We already have one, just update it
$ra->id = $ra->id;
- $ra->hidden = $hidden;
$ra->enrol = $enrol;
/// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
/// by repeating queries with the same exact parameters in a 100 secs time window
@@ -2944,8 +2811,6 @@ function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NU
global $USER, $CFG, $DB;
require_once($CFG->dirroot.'/group/lib.php');
- $success = true;
-
$args = array('roleid', 'userid', 'groupid', 'contextid');
$select = array();
$params = array();
@@ -2965,16 +2830,11 @@ function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NU
if ($ras = $DB->get_records_select('role_assignments', implode(' AND ', $select), $params)) {
$mods = get_plugin_list('mod');
foreach($ras as $ra) {
- $fireevent = false;
/// infinite loop protection when deleting recursively
if (!$ra = $DB->get_record('role_assignments', array('id'=>$ra->id))) {
continue;
}
- if ($DB->delete_records('role_assignments', array('id'=>$ra->id))) {
- $fireevent = true;
- } else {
- $success = false;
- }
+ $DB->delete_records('role_assignments', array('id'=>$ra->id));
if (!$context = get_context_instance_by_id($ra->contextid)) {
// strange error, not much to do
@@ -3007,7 +2867,7 @@ function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NU
// cleanup leftover course groups/subscriptions etc when user has
// no capability to view course
// this may be slow, but this is the proper way of doing it
- if (!has_capability('moodle/course:view', $context, $ra->userid)) {
+ if (!has_capability('moodle/course:participate', $context, $ra->userid)) {
// remove from groups
groups_delete_group_members($context->instanceid, $ra->userid);
@@ -3023,14 +2883,12 @@ function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NU
}
}
- if ($fireevent) {
- events_trigger('role_unassigned', $ra);
- }
+ events_trigger('role_unassigned', $ra);
}
}
}
- return $success;
+ return true;
}
/**
@@ -3077,6 +2935,410 @@ function enrol_into_course($course, $user, $enrol) {
return false;
}
+/**
+ * Determines if a user is currently logged in
+ *
+ * @return bool
+ */
+function isloggedin() {
+ global $USER;
+
+ return (!empty($USER->id));
+}
+
+/**
+ * Determines if a user is logged in as real guest user with username 'guest'.
+ *
+ * @param int $user mixed user object or id, $USER if not specified
+ * @return bool true if user is the real guest user, false if not logged in or other user
+ */
+function isguestuser($user = NULL) {
+ global $USER, $DB, $CFG;
+
+ // make sure we have the user id cached in config table, because we are going to use it a lot
+ if (empty($CFG->siteguest)) {
+ if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
+ // guest does not exist yet, weird
+ return false;
+ }
+ set_config('siteguest', $guestid);
+ }
+ if ($user === NULL) {
+ $user = $USER;
+ }
+
+ if ($user === NULL) {
+ // happens when setting the $USER
+ return false;
+
+ } else if (is_numeric($user)) {
+ return ($CFG->siteguest == $user);
+
+ } else if (is_object($user)) {
+ if (empty($user->id)) {
+ return false; // not logged in means is not be guest
+ } else {
+ return ($CFG->siteguest == $user->id);
+ }
+
+ } else {
+ throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
+ }
+}
+
+/**
+ * Does user have a (temporary or real) guest access to course?
+ *
+ * @param object $context
+ * @param object|int $user
+ * @return bool
+ */
+function is_guest($context, $user = NULL) {
+ // first find the course context
+ $coursecontext = get_course_context($context);
+
+ // make sure there is a real user specified
+ if ($user === NULL) {
+ $userid = !empty($USER->id) ? $USER->id : 0;
+ } else {
+ $userid = !empty($user->id) ? $user->id : $user;
+ }
+
+ if (isguestuser($userid)) {
+ // can not inspect or be enrolled
+ return true;
+ }
+
+ if (has_capability('moodle/course:view', $coursecontext, $user)) {
+ // viewing users appear out of nowhere, they are neither guests nor participants
+ return false;
+ }
+
+ if (has_capability('moodle/course:participate', $coursecontext, $userid, false)) {
+ return false;
+ }
+
+ return true;
+}
+
+
+/**
+ * Returns true if user has course:inspect capability in course,
+ * this is intended for admins, managers (aka small admins), inspectors, etc.
+ *
+ * @param object $context
+ * @param int|object $user, if NULL $USER is used
+ * @param string $withcapability extra capability name
+ * @return bool
+ */
+function is_viewing($context, $user = NULL, $withcapability = '') {
+ global $USER;
+
+ // first find the course context
+ $coursecontext = get_course_context($context);
+
+ if (isguestuser($user)) {
+ // can not inspect
+ return true;
+ }
+
+ if (!has_capability('moodle/course:view', $coursecontext, $user)) {
+ // admins are allowed to inspect courses
+ return false;
+ }
+
+ if ($withcapability and !has_capability($withcapability, $context, $user)) {
+ // site admins always have the capability, but the enrolment above blocks
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Returns true if user is enrolled (is participating) in course
+ * this is intended for students and teachers.
+ *
+ * @param object $context
+ * @param int|object $user, if NULL $USER is used, oherwise user object or id expected
+ * @param string $withcapability extra capability name
+ * @return bool
+ */
+function is_enrolled($context, $user = NULL, $withcapability = '') {
+ global $USER;
+
+ // first find the course context
+ $coursecontext = get_course_context($context);
+
+ // make sure there is a real user specified
+ if ($user === NULL) {
+ $userid = !empty($USER->id) ? $USER->id : 0;
+ } else {
+ $userid = !empty($user->id) ? $user->id : $user;
+ }
+
+ if (empty($userid)) {
+ // not-logged-in!
+ return false;
+ } else if (isguestuser($userid)) {
+ // guest account can not be enrolled anywhere
+ return false;
+ }
+
+ if ($coursecontext->instanceid != SITEID and !has_capability('moodle/course:participate', $coursecontext, $userid, false)) {
+ // admins are not enrolled, everybody is "enrolled" in the frontpage course
+ return false;
+ }
+
+ if ($withcapability and !has_capability($withcapability, $context, $userid)) {
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Returns array with sql code and parameters returning all ids
+ * of users enrolled into course.
+ * @param object $context
+ * @param string $withcapability
+ * @param int $groupid 0 means ignore groups, any other value limits the result by group id
+ * @param string $prefix used for alias of user table, parameter names and in aliases of other used tables
+ * @return array list($sql, $params)
+ */
+function get_enrolled_sql($context, $withcapability = '', $groupid = 0, $prefix = 'eu') {
+ global $DB;
+
+ if ($context->contextlevel < CONTEXT_COURSE) {
+ throw new coding_exception('get_enrolled_sql() expects course context and bellow!');
+ }
+
+ // first find the course context
+ if ($context->contextlevel == CONTEXT_COURSE) {
+ $coursecontext = $context;
+
+ } else if ($context->contextlevel == CONTEXT_MODULE) {
+ $coursecontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
+
+ } else if ($context->contextlevel == CONTEXT_BLOCK) {
+ $parentcontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
+ if ($parentcontext->contextlevel == CONTEXT_COURSE) {
+ $coursecontext = $parentcontext;
+ } else if ($parentcontext->contextlevel == CONTEXT_MODULE) {
+ $coursecontext = get_context_instance_by_id(get_parent_contextid($parentcontext, MUST_EXIST));
+ } else {
+ throw new coding_exception('Invalid context supplied to get_enrolled_sql()!');
+ }
+
+ } else {
+ throw new coding_exception('Invalid context supplied to get_enrolled_sql()!');
+ }
+
+ list($contextids, $contextpaths) = get_context_info_list($context);
+ list($coursecontextids, $coursecontextpaths) = get_context_info_list($coursecontext);
+
+ // get all relevant capability info for all roles
+ if ($withcapability) {
+ list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con00');
+ $incaps = "IN (:participate, :withcap)";
+ $params['participate'] = 'moodle/course:participate';
+ $params['withcap'] = $withcapability;
+ } else {
+ list($incontexts, $params) = $DB->get_in_or_equal($coursecontextids, SQL_PARAMS_NAMED, 'con00');
+ $incaps = "= :participate";
+ $params['participate'] = 'moodle/course:participate';
+ }
+ $defs = array();
+ $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
+ FROM {role_capabilities} rc
+ JOIN {context} ctx on rc.contextid = ctx.id
+ WHERE rc.contextid $incontexts AND rc.capability $incaps";
+ $rcs = $DB->get_records_sql($sql, $params);
+ foreach ($rcs as $rc) {
+ $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
+ }
+
+ $courseaccess = array();
+ if (!empty($defs['moodle/course:participate'])) {
+ foreach ($coursecontextpaths as $path) {
+ if (empty($defs['moodle/course:participate'][$path])) {
+ continue;
+ }
+
+ foreach($defs['moodle/course:participate'][$path] as $roleid => $perm) {
+ if ($perm == CAP_PROHIBIT) {
+ $courseaccess[$roleid] = CAP_PROHIBIT;
+ continue;
+ }
+ if (!isset($courseaccess[$roleid])) {
+ $courseaccess[$roleid] = (int)$perm;
+ }
+ }
+ }
+ }
+
+ $access = array();
+ if (!empty($defs[$withcapability])) {
+ foreach ($contextpaths as $path) {
+ if (empty($defs[$withcapability][$path])) {
+ continue;
+ }
+ foreach($defs[$withcapability][$path] as $roleid => $perm) {
+ if ($perm == CAP_PROHIBIT) {
+ $access[$roleid] = CAP_PROHIBIT;
+ continue;
+ }
+ if (!isset($access[$roleid])) {
+ $access[$roleid] = (int)$perm;
+ }
+ }
+ }
+ }
+
+ unset($defs);
+
+ // make lists of roles that are needed and prohibited
+ $courseneeded = array(); // one of these is enough
+ $courseprohibited = array(); // must not have any of these
+ foreach ($courseaccess as $roleid => $perm) {
+ if ($perm == CAP_PROHIBIT) {
+ unset($courseneeded[$roleid]);
+ $courseprohibited[$roleid] = true;
+ } else if ($perm == CAP_ALLOW and empty($courseprohibited[$roleid])) {
+ $courseneeded[$roleid] = true;
+ }
+ }
+ $needed = array(); // one of these is enough
+ $prohibited = array(); // must not have any of these
+ if ($withcapability) {
+ foreach ($access as $roleid => $perm) {
+ if ($perm == CAP_PROHIBIT) {
+ unset($needed[$roleid]);
+ $prohibited[$roleid] = true;
+ } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
+ $needed[$roleid] = true;
+ }
+ }
+ }
+
+ $isfrontpage = ($coursecontext->instanceid == SITEID);
+
+ $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : NULL;
+ $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : NULL;
+
+ $nobody = false;
+
+ if ($isfrontpage) {
+ // on the frontpage all users are kind of enrolled, we have to respect only the prohibits
+ $courseneeded = array();
+ } else {
+ if (empty($courseneeded)) {
+ $nobody = true;
+ }
+ }
+
+ if ($withcapability and !$nobody) {
+ if ($isfrontpage) {
+ if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
+ $nobody = true;
+ } else if (!empty($neded[$defaultuserroleid]) or !empty($neded[$defaultfrontpageroleid])) {
+ // everybody not having prohibit has the capability
+ $needed = array();
+ } else if (empty($needed)) {
+ $nobody = true;
+ }
+ } else {
+ if (!empty($prohibited[$defaultuserroleid])) {
+ $nobody = true;
+ } else if (!empty($neded[$defaultuserroleid])) {
+ // everybody not having prohibit has the capability
+ $needed = array();
+ } else if (empty($needed)) {
+ $nobody = true;
+ }
+ }
+ }
+
+ if ($nobody) {
+ // nobody can match so return some SQL that does not return any results
+ return array("SELECT {$prefix}.id FROM {user} {$prefix} WHERE 1=2", array());
+ }
+
+ $joins = array();
+ $params = array();
+ $wheres = array("{$prefix}.deleted = 0 AND {$prefix}.username <> 'guest'");
+
+ if ($courseneeded) {
+ $ctxids = implode(',', $coursecontextids);
+ $roleids = implode(',', array_keys($courseneeded));
+ $joins[] = "JOIN {role_assignments} {$prefix}_ra1 ON ({$prefix}_ra1.userid = {$prefix}.id AND {$prefix}_ra1.roleid IN ($roleids) AND {$prefix}_ra1.contextid IN ($ctxids))";
+ }
+
+ if ($courseprohibited) {
+ $ctxids = implode(',', $coursecontextids);
+ $roleids = implode(',', array_keys($courseprohibited));
+ $joins[] = "LEFT JOIN {role_assignments} {$prefix}_ra2 ON ({$prefix}_ra2.userid = {$prefix}.id AND {$prefix}_ra2.roleid IN ($roleids) AND {$prefix}_ra2.contextid IN ($ctxids))";
+ $wheres[] = "{$prefix}_ra2 IS NULL";
+ }
+
+ if ($needed) {
+ $ctxids = implode(',', $contextids);
+ $roleids = implode(',', array_keys($needed));
+ $joins[] = "JOIN {role_assignments} {$prefix}_ra3 ON ({$prefix}_ra3.userid = {$prefix}.id AND {$prefix}_ra3.roleid IN ($roleids) AND {$prefix}_ra3.contextid IN ($ctxids))";
+ }
+
+ if ($prohibited) {
+ $ctxids = implode(',', $contextids);
+ $roleids = implode(',', array_keys($prohibited));
+ $joins[] = "LEFT JOIN {role_assignments} {$prefix}_ra4 ON ({$prefix}_ra4.userid = {$prefix}.id AND {$prefix}_ra4.roleid IN ($roleids) AND {$prefix}_ra4.contextid IN ($ctxids))";
+ $wheres[] = "{$prefix}_ra4 IS NULL";
+ }
+
+ if ($groupid) {
+ $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}.id AND {$prefix}.roleid = :{$prefix}gmid)";
+ $params["{$prefix}gmid"] = $groupid;
+ }
+
+ $joins = implode("\n", $joins);
+ $wheres = "WHERE ".implode(" AND ", $wheres);
+
+ $sql = "SELECT DISTINCT {$prefix}.id
+ FROM {user} {$prefix}
+ $joins
+ $wheres";
+
+ return array($sql, $params);
+}
+
+/**
+ * Returns list of users enrolled into course.
+ * @param object $context
+ * @param string $withcapability
+ * @param int $groupid 0 means ignore groups, any other value limits the result by group id
+ * @param string $userfields requested user record fields
+ * @param string $orderby
+ * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
+ * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
+ * @return array of user records
+ */
+function get_enrolled_users($context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
+ global $DB;
+
+ list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
+ $sql = "SELECT $userfields
+ FROM {user} u
+ JOIN ($esql) je ON je.id = u.id
+ WHERE u.deleted = 0";
+
+ if ($orderby) {
+ $sql = "$sql ORDER BY $orderby";
+ } else {
+ $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
+ }
+
+ return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
+}
+
/**
* Loads the capability definitions for the component (from file).
*
@@ -3094,8 +3356,9 @@ function load_capability_def($component) {
if (file_exists($defpath)) {
require($defpath);
if (!empty(${$component.'_capabilities'})) {
- // legacy capability array name
+ // BC capability array name
// since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
+ debugging('componentname_capabilities array is deprecated, please use capabilities array only in access.php files');
$capabilities = ${$component.'_capabilities'};
}
}
@@ -3115,16 +3378,22 @@ function get_cached_capabilities($component='moodle') {
}
/**
- * Returns default capabilities for given legacy role type.
- * @param string $legacyrole legacy role name
+ * Returns default capabilities for given role archetype.
+ * @param string $archetype role archetype
* @return array
*/
-function get_default_capabilities($legacyrole) {
+function get_default_capabilities($archetype) {
global $DB;
- $allcaps = $DB->get_records('capabilities');
+
+ if (!$archetype) {
+ return array();
+ }
+
$alldefs = array();
$defaults = array();
$components = array();
+ $allcaps = $DB->get_records('capabilities');
+
foreach ($allcaps as $cap) {
if (!in_array($cap->component, $components)) {
$components[] = $cap->component;
@@ -3132,46 +3401,31 @@ function get_default_capabilities($legacyrole) {
}
}
foreach($alldefs as $name=>$def) {
- if (isset($def['legacy'][$legacyrole])) {
- $defaults[$name] = $def['legacy'][$legacyrole];
+ if (isset($def['legacy'][$archetype])) {
+ $defaults[$name] = $def['legacy'][$archetype];
}
}
- //some exceptions
- $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
- if ($legacyrole == 'admin') {
- $defaults['moodle/site:doanything'] = CAP_ALLOW;
- }
return $defaults;
}
/**
- * Reset role capabilitites to default according to selected legacy capability.
- * If several legacy caps selected, use the first from get_default_capabilities.
- * If no legacy selected, removes all capabilities.
+ * Reset role capabilitites to default according to selected role archetype.
+ * If no archetype selected, removes all capabilities.
* @param int @roleid
*/
function reset_role_capabilities($roleid) {
global $DB;
- $sitecontext = get_context_instance(CONTEXT_SYSTEM);
- $legacyroles = get_legacy_roles();
+ $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
+ $defaultcaps = get_default_capabilities($role->archetype);
- $defaultcaps = array();
- foreach($legacyroles as $ltype=>$lcap) {
- $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
- if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
- //choose first selected legacy capability
- $defaultcaps = get_default_capabilities($ltype);
- break;
- }
- }
+ $sitecontext = get_context_instance(CONTEXT_SYSTEM);
$DB->delete_records('role_capabilities', array('roleid'=>$roleid));
- if (!empty($defaultcaps)) {
- foreach($defaultcaps as $cap=>$permission) {
- assign_capability($cap, $permission, $roleid, $sitecontext->id);
- }
+
+ foreach($defaultcaps as $cap=>$permission) {
+ assign_capability($cap, $permission, $roleid, $sitecontext->id);
}
}
@@ -3203,6 +3457,12 @@ function update_capabilities($component='moodle') {
if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
$filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
}
+ if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
+ $updatecap = new object();
+ $updatecap->id = $cachedcap->id;
+ $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
+ $DB->update_record('capabilities', $updatecap);
+ }
if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
$updatecap = new object();
$updatecap->id = $cachedcap->id;
@@ -3237,7 +3497,7 @@ function update_capabilities($component='moodle') {
}
// Add new capabilities to the stored definition.
foreach ($newcaps as $capname => $capdef) {
- $capability = new object;
+ $capability = new object();
$capability->name = $capname;
$capability->captype = $capdef['captype'];
$capability->contextlevel = $capdef['contextlevel'];
@@ -3256,12 +3516,9 @@ function update_capabilities($component='moodle') {
}
}
}
- // Do we need to assign the new capabilities to roles that have the
- // legacy capabilities moodle/legacy:* as well?
// we ignore legacy key if we have cloned permissions
- } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
- !assign_legacy_capabilities($capname, $capdef['legacy'])) {
- echo $OUTPUT->notification('Could not assign legacy capabilities for '.$capname);
+ } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
+ assign_legacy_capabilities($capname, $capdef['legacy']);
}
}
// Are there any capabilities that have been removed from the file
@@ -3270,7 +3527,7 @@ function update_capabilities($component='moodle') {
capabilities_cleanup($component, $filecaps);
// reset static caches
- is_valid_capability('reset', false);
+ $ACCESSLIB_PRIVATE->capabilities = NULL;
return true;
}
@@ -3324,7 +3581,7 @@ function capabilities_cleanup($component, $newcapdef=NULL) {
* @return string the name for this type of context.
*/
function get_contextlevel_name($contextlevel) {
- static $strcontextlevels = null;
+ static $strcontextlevels = NULL;
if (is_null($strcontextlevels)) {
$strcontextlevels = array(
CONTEXT_SYSTEM => get_string('coresystem'),
@@ -3707,6 +3964,53 @@ function get_parent_contextid($context) {
return array_shift($parentcontexts);
}
+/**
+ * Constructs array with contextids as first parameter and context paths,
+ * in both cases bottom top including self.
+ *
+ * @param object $context
+ * @return array
+ */
+function get_context_info_list($context) {
+ $contextids = explode('/', ltrim($context->path, '/'));
+ $contextpaths = array();
+ $contextids2 = $contextids;
+ while ($contextids2) {
+ $contextpaths[] = '/' . implode('/', $contextids2);
+ array_pop($contextids2);
+ }
+ return array($contextids, $contextpaths);
+}
+
+/**
+ * Find course context
+ * @param object $context - course or lower context
+ * @return object context of the enclosing course, throws exception when related course context can not be found
+ */
+function get_course_context($context) {
+ if (empty($context->contextlevel)) {
+ throw coding_exception('Invalid context parameter.');
+
+ } if ($context->contextlevel == CONTEXT_COURSE) {
+ return $context;
+
+ } else if ($context->contextlevel == CONTEXT_MODULE) {
+ return get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
+
+ } else if ($context->contextlevel == CONTEXT_BLOCK) {
+ $parentcontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
+ if ($parentcontext->contextlevel == CONTEXT_COURSE) {
+ return $parentcontext;
+ } else if ($parentcontext->contextlevel == CONTEXT_MODULE) {
+ return get_context_instance_by_id(get_parent_contextid($parentcontext, MUST_EXIST));
+ } else {
+ throw new coding_exception('Invalid level of block context parameter.');
+ }
+ }
+
+ throw new coding_exception('Invalid context level of parameter.');
+}
+
/**
* Check if contect is the front page context or a context inside it
*
@@ -3880,22 +4184,28 @@ function get_related_contexts_string($context) {
}
/**
- * Verifies if given capability installed.
+ * Returns capability information (cached)
*
- * @global object
* @param string $capabilityname
- * @param bool $cached
- * @return book true if capability exists
+ * @return object or NULL if capability not found
*/
-function is_valid_capability($capabilityname, $cached = true) {
- global $ACCESSLIB_PRIVATE; // one request per page only
+function get_capability_info($capabilityname) {
+ global $ACCESSLIB_PRIVATE, $DB; // one request per page only
- if (is_null($ACCESSLIB_PRIVATE->capabilitynames) or !$cached) {
- global $DB;
- $ACCESSLIB_PRIVATE->capabilitynames = $DB->get_records_menu('capabilities', null, '', 'name, 1');
+ // TODO: cache this in shared memory if available, use new $CFG->roledefrev for version check
+
+ if (empty($ACCESSLIB_PRIVATE->capabilities)) {
+ $ACCESSLIB_PRIVATE->capabilities = array();
+ $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
+ foreach ($caps as $cap) {
+ $capname = $cap->name;
+ unset($cap->id);
+ unset($cap->name);
+ $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
+ }
}
- return array_key_exists($capabilityname, $ACCESSLIB_PRIVATE->capabilitynames);
+ return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : NULL;
}
/**
@@ -4065,32 +4375,49 @@ function get_component_string($component, $contextlevel) {
/**
* Gets the list of roles assigned to this context and up (parents)
+ * from the list of roles that are visible on user profile page
+ * and participants page.
*
- * set $view to true when roles are pulled for display only
- * this is so that we can filter roles with no visible
- * assignment, for example, you might want to "hide" all
- * course creators when browsing the course participants
- * list.
- *
- * @global object
* @param object $context
- * @param bool $view
* @return array
*/
-function get_roles_used_in_context($context, $view = false) {
+function get_profile_roles($context) {
+ global $CFG, $DB;
+
+ if (empty($CFG->profileroles)) {
+ return array();
+ }
+
+ $allowed = explode(',', $CFG->profileroles);
+ list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
+
+ $contextlist = get_related_contexts_string($context);
+
+ $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
+ FROM {role_assignments} ra, {role} r
+ WHERE r.id = ra.roleid
+ AND ra.contextid $contextlist
+ AND r.id $rallowed
+ ORDER BY r.sortorder ASC";
+
+ return $DB->get_records_sql($sql, $params);
+}
+
+/**
+ * Gets the list of roles assigned to this context and up (parents)
+ *
+ * @param object $context
+ * @return array
+ */
+function get_roles_used_in_context($context) {
global $DB;
- // filter for roles with all hidden assignments
- // no need to return when only pulling roles for reviewing
- // e.g. participants page.
- $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
$contextlist = get_related_contexts_string($context);
$sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
FROM {role_assignments} ra, {role} r
WHERE r.id = ra.roleid
AND ra.contextid $contextlist
- $hiddensql
ORDER BY r.sortorder ASC";
return $DB->get_records_sql($sql);
@@ -4098,31 +4425,49 @@ function get_roles_used_in_context($context, $view = false) {
/**
* This function is used to print roles column in user profile page.
+ * It is using the CFG->profileroles to limit the list to only interesting roles.
+ * (The permission tab has full details of user role assingments.)
*
- * @global object
- * @global object
- * @global object
* @param int $userid
- * @param object $context
- * @param bool $view
+ * @param int $courseid
* @return string
*/
-function get_user_roles_in_context($userid, $context, $view=true){
+function get_user_roles_in_course($userid, $courseid) {
global $CFG, $DB,$USER;
+ if (empty($CFG->profileroles)) {
+ return '';
+ }
+
+ if ($courseid == SITEID) {
+ $context = get_context_instance(CONTEXT_SYSTEM);
+ } else {
+ $context = get_context_instance(CONTEXT_COURSE, $courseid);
+ }
+
+ if (empty($CFG->profileroles)) {
+ return array();
+ }
+
+ $allowed = explode(',', $CFG->profileroles);
+ list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
+
+ $contextlist = get_related_contexts_string($context);
+
+ $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
+ FROM {role_assignments} ra, {role} r
+ WHERE r.id = ra.roleid
+ AND ra.contextid $contextlist
+ AND r.id $rallowed
+ AND ra.userid = :userid
+ ORDER BY r.sortorder ASC";
+ $params['userid'] = $userid;
+
$rolestring = '';
- $sql = "SELECT *
- FROM {role_assignments} ra, {role} r
- WHERE ra.userid = ? and ra.contextid = ? and ra.roleid = r.id";
- $params = array($userid, $context->id);
- $rolenames = array();
+
if ($roles = $DB->get_records_sql($sql, $params)) {
foreach ($roles as $userrole) {
- // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
- if ($userrole->hidden && $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
- continue;
- }
- $rolenames[$userrole->roleid] = $userrole->name;
+ $rolenames[$userrole->id] = $userrole->name;
}
$rolenames = role_fix_names($rolenames, $context); // Substitute aliases
@@ -4132,43 +4477,10 @@ function get_user_roles_in_context($userid, $context, $view=true){
}
$rolestring = implode(',', $rolenames);
}
+
return $rolestring;
}
-
-/**
- * Checks if a user can override capabilities of a particular role in this context
- *
- * @deprecated As of version 2.0
- * @todo not needed anymore, remove in 2.0
- * @param object $context
- * @param int $targetroleid the id of the role you want to override
- * @return boolean
- */
-function user_can_override($context, $targetroleid) {
-
-// TODO: not needed anymore, remove in 2.0
-
- global $DB;
- // first check if user has override capability
- // if not return false;
- if (!has_capability('moodle/role:override', $context)) {
- return false;
- }
- // pull out all active roles of this user from this context(or above)
- if ($userroles = get_user_roles($context)) {
- foreach ($userroles as $userrole) {
- // if any in the role_allow_override table, then it's ok
- if ($DB->get_record('role_allow_override', array('roleid'=>$userrole->roleid, 'allowoverride'=>$targetroleid))) {
- return true;
- }
- }
- }
-
- return false;
-
-}
-
/**
* Checks if a user can assign users to a particular role in this context
*
@@ -4201,36 +4513,36 @@ function user_can_assign($context, $targetroleid) {
/**
* Returns all site roles in correct sort order.
*
- * @global object
* @return array
*/
function get_all_roles() {
global $DB;
- return $DB->get_records('role', null, 'sortorder ASC');
+ return $DB->get_records('role', NULL, 'sortorder ASC');
}
/**
- * gets all the user roles assigned in this context, or higher contexts
+ * Returns roles of a specified archetype
+ * @param string $archetype
+ * @return array of full role records
+ */
+function get_archetype_roles($archetype) {
+ global $DB;
+ return $DB->get_records('role', array('archetype'=>$archetype));
+}
+
+/**
+ * Gets all the user roles assigned in this context, or higher contexts
* this is mainly used when checking if a user can assign a role, or overriding a role
* i.e. we need to know what this user holds, in order to verify against allow_assign and
* allow_override tables
*
- * set $view to true when roles are pulled for display only
- * this is so that we can filter roles with no visible
- * assignment, for example, you might want to "hide" all
- * course creators when browsing the course participants
- * list.
- *
- * @global object
- * @global object
* @param object $context
* @param int $userid
* @param bool $checkparentcontexts defaults to true
* @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
- * @param bool $view
* @return array
*/
-function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
+function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC') {
global $USER, $DB;
if (empty($userid)) {
@@ -4239,8 +4551,6 @@ function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='
}
$userid = $USER->id;
}
- // set up hidden sql
- $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) ? "AND ra.hidden = 0" : "";
if ($checkparentcontexts) {
$contextids = get_parent_contexts($context);
@@ -4259,7 +4569,6 @@ function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='
AND ra.roleid = r.id
AND ra.contextid = c.id
AND ra.contextid $contextids
- $hiddensql
ORDER BY $order";
return $DB->get_records_sql($sql ,$params);
@@ -4293,7 +4602,7 @@ function allow_override($sroleid, $troleid) {
function allow_assign($fromroleid, $targetroleid) {
global $DB;
- $record = new object;
+ $record = new object();
$record->roleid = $fromroleid;
$record->allowassign = $targetroleid;
$DB->insert_record('role_allow_assign', $record);
@@ -4310,7 +4619,7 @@ function allow_assign($fromroleid, $targetroleid) {
function allow_switch($fromroleid, $targetroleid) {
global $DB;
- $record = new object;
+ $record = new object();
$record->roleid = $fromroleid;
$record->allowswitch = $targetroleid;
$DB->insert_record('role_allow_switch', $record);
@@ -4340,53 +4649,49 @@ function get_assignable_roles($context, $rolenamedisplay = ROLENAME_ALIAS, $with
}
}
- $parents = get_parent_contexts($context);
- $parents[] = $context->id;
+ $parents = get_parent_contexts($context, true);
$contexts = implode(',' , $parents);
$params = array();
$extrafields = '';
if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
- $extrafields .= ', ro.shortname';
+ $extrafields .= ', r.shortname';
}
if ($withusercounts) {
$extrafields = ', (SELECT count(u.id)
FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
- WHERE cra.roleid = ro.id AND cra.contextid = :conid AND u.deleted = 0
+ WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
) AS usercount';
$params['conid'] = $context->id;
}
- $raafrom = ", {role_allow_assign} raa";
- $raawhere = "AND raa.roleid = ra.roleid AND r.id = raa.allowassign";
- if (has_capability('moodle/site:doanything', get_context_instance(CONTEXT_SYSTEM))) {
+ if (is_siteadmin()) {
// show all roles allowed in this context to admins
- $raafrom = "";
- $raawhere = "";
+ $assignrestriction = "";
+ } else {
+ $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
+ FROM {role_allow_assign} raa
+ JOIN {role_assignments} ra ON ra.roleid = raa.roleid
+ WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
+ ) ar ON ar.id = r.id";
+ $params['userid'] = $USER->id;
}
-
- $params['userid'] = $USER->id;
$params['contextlevel'] = $context->contextlevel;
- $roles = $DB->get_records_sql("
- SELECT ro.id, ro.name$extrafields
- FROM {role} ro
- JOIN (SELECT DISTINCT r.id
- FROM {role} r,
- {role_assignments} ra $raafrom
- WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
- $raawhere
- ) inline_view ON ro.id = inline_view.id
- JOIN {role_context_levels} rcl ON ro.id = rcl.roleid
- WHERE rcl.contextlevel = :contextlevel
- ORDER BY ro.sortorder ASC", $params);
+ $sql = "SELECT r.id, r.name $extrafields
+ FROM {role} r
+ $assignrestriction
+ JOIN {role_context_levels} rcl ON r.id = rcl.roleid
+ WHERE rcl.contextlevel = :contextlevel
+ ORDER BY r.sortorder ASC";
+ $roles = $DB->get_records_sql($sql, $params);
$rolenames = array();
foreach ($roles as $role) {
$rolenames[$role->id] = $role->name;
if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
$rolenames[$role->id] .= ' (' . $role->shortname . ')';
- }
+ }
}
if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
$rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
@@ -4425,9 +4730,9 @@ function get_switchable_roles($context) {
$params = array();
$extrajoins = '';
$extrawhere = '';
- if (!has_capability('moodle/site:doanything', $systemcontext)) {
- // Admins are allowed to switch to any role with 'moodle/course:view' in the
- // role definition, and without 'moodle/site:doanything' anywhere.
+ if (!is_siteadmin()) {
+ // Admins are allowed to switch to any role with 'moodle/course:participate' in the
+ // role definition.
// Others are subject to the additional constraint that the switch-to role must be allowed by
// 'role_allow_switch' for some role they have assigned in this context or any parent.
$parents = get_parent_contexts($context);
@@ -4436,8 +4741,7 @@ function get_switchable_roles($context) {
$extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
- $extrawhere = "AND ra.userid = :userid
- AND ra.contextid IN ($contexts)";
+ $extrawhere = "AND ra.userid = :userid AND ra.contextid IN ($contexts)";
$params['userid'] = $USER->id;
}
@@ -4451,15 +4755,11 @@ function get_switchable_roles($context) {
AND rc.permission = " . CAP_ALLOW . "
AND rc.contextid = :syscontextid
$extrawhere
- AND NOT EXISTS (
- SELECT 1 FROM {role_capabilities} irc WHERE irc.roleid = rc.roleid AND
- irc.capability = :anythingcap AND irc.permission = " . CAP_ALLOW . ")
) idlist
JOIN {role} r ON r.id = idlist.roleid
ORDER BY r.sortorder";
$params['syscontextid'] = $systemcontext->id;
- $params['viewcap'] = 'moodle/course:view';
- $params['anythingcap'] = 'moodle/site:doanything';
+ $params['viewcap'] = 'moodle/course:participate';
$rolenames = $DB->get_records_sql_menu($query, $params);
return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
@@ -4467,29 +4767,26 @@ function get_switchable_roles($context) {
/**
* Get an array of role ids that might possibly be the target of a switchrole.
- * Our policy is that you cannot switch to a role with moodle/site:doanything
- * and you can only switch to a role with moodle/course:view. This method returns
+ * Our policy is that you cannot switch to admin role
+ * and you can only switch to a role with moodle/course:participate. This method returns
* a list of those role ids.
*
* @global object
* @return array an array whose keys are the allowed role ids.
*/
function get_allowed_switchable_roles() {
- global $DB;
+ global $CFG, $DB;
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
$query = "
SELECT DISTINCT rc.roleid, 1
FROM {role_capabilities} rc
- WHERE rc.capability = :viewcap
+ JOIN {role} r ON r.id = rc.roleid
+ WHERE rc.capability = :participate
AND rc.permission = " . CAP_ALLOW . "
- AND rc.contextid = :syscontextid
- AND NOT EXISTS (
- SELECT 1 FROM {role_capabilities} irc WHERE irc.roleid = rc.roleid AND
- irc.capability = :anythingcap AND irc.permission = " . CAP_ALLOW . ")";
- $params = array('syscontextid' => $systemcontext->id,
- 'viewcap' => 'moodle/course:view', 'anythingcap' => 'moodle/site:doanything');
+ AND rc.contextid = :syscontextid";
+ $params = array('syscontextid' => $systemcontext->id, 'participate' => 'moodle/course:participate');
return $DB->get_records_sql_menu($query, $params);
}
@@ -4535,7 +4832,7 @@ function get_overridable_roles($context, $rolenamedisplay = ROLENAME_ALIAS, $wit
$params['conid'] = $context->id;
}
- if (has_capability('moodle/site:doanything', get_context_instance(CONTEXT_SYSTEM))) {
+ if (is_siteadmin()) {
// show all roles to admins
$roles = $DB->get_records_sql("
SELECT ro.id, ro.name$extrafields
@@ -4602,22 +4899,23 @@ function get_roles_for_contextlevels($contextlevel) {
}
/**
- * @param string $roleid one of the legacy role types - that is, one of the keys
- * from the array returned by get_legacy_roles();
+ * @param string $rolearchetype one of the role archetypes - that is, one of the keys
+ * from the array returned by get_role_archetypes();
* @return array list of the context levels at which this type of role may be assigned by default.
*/
-function get_default_contextlevels($roletype) {
+function get_default_contextlevels($rolearchetype) {
static $defaults = array(
- 'admin' => array(CONTEXT_SYSTEM),
+ 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
'editingteacher' => array(CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE),
'teacher' => array(CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE),
'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
'guest' => array(),
- 'user' => array()
+ 'user' => array(),
+ 'frontpage' => array()
);
- if (isset($defaults[$roletype])) {
- return $defaults[$roletype];
+ if (isset($defaults[$rolearchetype])) {
+ return $defaults[$rolearchetype];
} else {
return array();
}
@@ -4669,7 +4967,7 @@ function get_default_course_role($course) {
}
/// It's unlikely we'll get here, but just in case, try and find a student role
- if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
+ if ($studentroles = $DB->get_records('role', array('archetype'=>'student'))) {
return array_shift($studentroles); /// Take the first one
}
@@ -4696,12 +4994,8 @@ function get_default_course_role($course) {
* @param string|array $groups - single group or array of groups - only return
* users who are in one of these group(s).
* @param string|array $exceptions - list of users to exclude, comma separated or array
- * @param bool $doanything prohibit takes over admin roles here, in has_capability() it does not
- * @param bool $view - set to true when roles are pulled for display only
- * this is so that we can filter roles with no visible
- * assignment, for example, you might want to "hide" all
- * course creators when browsing the course participants
- * list.
+ * @param bool $doanything_ignored not used any more, admin accounts are never returned
+ * @param bool $view_ignored - use get_enrolled_sql() instead
* @param bool $useviewallgroups if $groups is set the return users who
* have capability both $capability and moodle/site:accessallgroups
* in this context, as well as users who have $capability and who are
@@ -4709,15 +5003,15 @@ function get_default_course_role($course) {
* @return mixed
*/
function get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='', $limitnum='',
- $groups='', $exceptions='', $doanything=true, $view=false, $useviewallgroups=false) {
+ $groups='', $exceptions='', $doanything_ignored=NULL, $view_ignored=NULL, $useviewallgroups=false) {
global $CFG, $DB;
if (empty($context->id)) {
throw new coding_exception('Invalid context specified');
}
- $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : null;
- $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : null;
+ $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : NULL;
+ $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : NULL;
$ctxids = trim($context->path, '/');
$ctxids = str_replace('/', ',', $ctxids);
@@ -4735,20 +5029,9 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $l
$isfrontpage = ($isfrontpage || is_inside_frontpage($context));
$caps = (array)$capability;
- if ($doanything) {
- $caps[] = 'moodle/site:doanything';
- }
// contruct list of context paths bottom-->top
- $contextids = explode(',', $ctxids);
- $paths = array($context->path);
- $contextids2 = $contextids;
- while ($contextids2) {
- array_pop($contextids2);
- $paths[] = '/' . implode('/', $contextids2);
- }
- unset($contextids2);
-
+ list($contextids, $paths) = get_context_info_list($context);
// we need to find out all roles that have these capabilities either in definition or in overrides
$defs = array();
@@ -4896,13 +5179,6 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $l
$wherecond[] = "u.id $exsql";
}
- /// Set up hidden role-assignments sql
- if ($view and !has_capability('moodle/role:viewhiddenassigns', $context)) {
- $condhiddenra = 'AND hidden = 0';
- } else {
- $condhiddenra = '';
- }
-
// now add the needed and prohibited roles conditions as joins
if (!empty($needed['any'])) {
// simple case - there are no prohibits involved
@@ -4913,7 +5189,6 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $l
FROM {role_assignments}
WHERE contextid IN ($ctxids)
AND roleid IN (".implode(',', array_keys($needed['any'])) .")
- $condhiddenra
) ra ON ra.userid = u.id";
}
} else {
@@ -4928,8 +5203,7 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $l
$unions[] = "SELECT userid
FROM {role_assignments}
WHERE contextid IN ($ctxids)
- AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
- $condhiddenra";
+ AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
}
} else {
if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
@@ -4942,22 +5216,11 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $l
AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
} else {
- if ($condhiddenra) {
- $unions[] = "SELECT userid
- FROM {role_assignments}
- WHERE contextid IN ($ctxids)
- AND roleid IN (".implode(',', array_keys($needed[$cap])) .") $condhiddenra
- AND userid NOT IN (SELECT userid
- FROM {role_assignments}
- WHERE contextid IN ($ctxids)
- AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
- } else {
- $unions[] = "SELECT userid
- FROM {role_assignments}
- WHERE contextid IN ($ctxids)
- AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
- AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
- }
+ $unions[] = "SELECT userid
+ FROM {role_assignments}
+ WHERE contextid IN ($ctxids)
+ AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
+ AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
}
}
}
@@ -5011,7 +5274,7 @@ function get_users_by_capability($context, $capability, $fields='', $sort='', $l
* a good idea to see what roles have the capabilities you want
* (array_diff() them against roiles that have 'can-do-anything'
* to weed out admin-ish roles. Or fetch a list of roles from
- * variables like $CFG->coursemanagers .
+ * variables like $CFG->coursemanager .
*
* @global object
* @param array $users Users array, keyed on userid
@@ -5079,7 +5342,7 @@ function sort_by_roleassignment_authority($users, $context, $roles=array(), $sor
* @param bool $parent if true, get list of users assigned in higher context too
* @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
* @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
- * @param bool $gethidden whether to fetch hidden enrolments too
+ * @param bool $gethidden_ignored use enrolments instead
* @param string $group defaults to ''
* @param mixed $limitfrom defaults to ''
* @param mixed $limitnum defaults to ''
@@ -5088,7 +5351,7 @@ function sort_by_roleassignment_authority($users, $context, $roles=array(), $sor
* @return array
*/
function get_role_users($roleid, $context, $parent=false, $fields='',
- $sort='u.lastname, u.firstname', $gethidden=true, $group='',
+ $sort='u.lastname, u.firstname', $gethidden_ignored=NULL, $group='',
$limitfrom='', $limitnum='', $extrawheretest='', $whereparams=array()) {
global $DB;
@@ -5099,9 +5362,6 @@ function get_role_users($roleid, $context, $parent=false, $fields='',
'u.emailstop, u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name as rolename';
}
- // whether this assignment is hidden
- $hiddensql = $gethidden ? '': ' AND ra.hidden = 0 ';
-
$parentcontexts = '';
if ($parent) {
$parentcontexts = substr($context->path, 1); // kill leading slash
@@ -5143,7 +5403,6 @@ function get_role_users($roleid, $context, $parent=false, $fields='',
WHERE (ra.contextid = ? $parentcontexts)
$roleselect
$groupselect
- $hiddensql
$extrawheretest
ORDER BY $sort"; // join now so that we can just use fullname() later
@@ -5198,7 +5457,7 @@ function count_role_users($roleid, $context, $parent=false) {
*
* @global object
* @param string $capability Capability in question
- * @param int $userid User ID or null for current user
+ * @param int $userid User ID or NULL for current user
* @param bool $doanything True if 'doanything' is permitted (default)
* @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
* otherwise use a comma-separated list of the fields you require, not including id
@@ -5792,58 +6051,44 @@ function context_moved($context, $newparent) {
mark_context_dirty($newpath);
}
+/**
+ * Preloads context information together with instances.
+ * NOTE: in future this function may return empty strings
+ * if we implement different caching.
+ *
+ * @param string $joinon for example 'u.id'
+ * @param string $contextlevel context level of instance in $joinon
+ * @param string $tablealias context table alias
+ * @return array with two values - select and join part
+ */
+function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
+ $select = ", $tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
+ $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
+ return array($select, $join);
+}
/**
- * Turn the ctx* fields in an objectlike record into a context subobject
- * This allows us to SELECT from major tables JOINing with
- * context at no cost, saving a ton of context
- * lookups...
+ * Preloads context information from db record and strips the cached info.
+ * The db request has to ontain both the $join and $select from context_instance_preload_sql()
*
* @param object $rec
- * @return object
+ * @return void (modifies $rec)
*/
-function make_context_subobj($rec) {
- $ctx = new StdClass;
- $ctx->id = $rec->ctxid; unset($rec->ctxid);
- $ctx->path = $rec->ctxpath; unset($rec->ctxpath);
- $ctx->depth = $rec->ctxdepth; unset($rec->ctxdepth);
- $ctx->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
- $ctx->instanceid = $rec->id;
-
- $rec->context = $ctx;
- return $rec;
-}
-
-/**
- * Do some basic, quick checks to see whether $rec->context looks like a valid context object.
- *
- * @param object $rec a think that has a context, for example a course,
- * course category, course modules, etc.
- * @param int $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
- * @return bool whether $rec->context looks like the correct context object
- * for this thing.
- */
-function is_context_subobj_valid($rec, $contextlevel) {
- return isset($rec->context) && isset($rec->context->id) &&
- isset($rec->context->path) && isset($rec->context->depth) &&
- isset($rec->context->contextlevel) && isset($rec->context->instanceid) &&
- $rec->context->contextlevel == $contextlevel && $rec->context->instanceid == $rec->id;
-}
-
-/**
- * Ensure that $rec->context is present and correct before you continue
- *
- * When you have a record (for example a $category, $course, $user or $cm that may,
- * or may not, have come from a place that does make_context_subobj, you can use
- * this method to ensure that $rec->context is present and correct before you continue.
- *
- * @param object $rec a thing that has an associated context.
- * @param integer $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
- */
-function ensure_context_subobj_present(&$rec, $contextlevel) {
- if (!is_context_subobj_valid($rec, $contextlevel)) {
- $rec->context = get_context_instance($contextlevel, $rec->id);
+function context_instance_preload(stdClass $rec) {
+ if (empty($rec->ctxid)) {
+ // $rec does not have enough data, passed here repeatedly or context does not exist yet
+ return;
}
+
+ // note: in PHP5 the objects are passed by reference, no need to return $rec
+ $context = new object();
+ $context->id = $rec->ctxid; unset($rec->ctxid);
+ $context->path = $rec->ctxpath; unset($rec->ctxpath);
+ $context->depth = $rec->ctxdepth; unset($rec->ctxdepth);
+ $context->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
+ $context->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
+
+ cache_context($context);
}
/**
@@ -6072,10 +6317,6 @@ function prohibit_is_removable($roleid, $context, $capability) {
function role_change_permission($roleid, $context, $capname, $permission) {
global $DB;
- if ($capname === 'moodle/site:doanything' or is_legacy($capname)) {
- return;
- }
-
if ($permission == CAP_INHERIT) {
unassign_capability($capname, $roleid, $context->id);
mark_context_dirty($context->path);
diff --git a/lib/adminlib.php b/lib/adminlib.php
index 3be6936d5e4..26a32d1cf89 100644
--- a/lib/adminlib.php
+++ b/lib/adminlib.php
@@ -969,7 +969,7 @@ class admin_externalpage implements part_of_admin_tree {
global $CFG;
$context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
foreach($this->req_capability as $cap) {
- if (is_valid_capability($cap) and has_capability($cap, $context)) {
+ if (has_capability($cap, $context)) {
return true;
}
}
@@ -1144,7 +1144,7 @@ class admin_settingpage implements part_of_admin_tree {
global $CFG;
$context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
foreach($this->req_capability as $cap) {
- if (is_valid_capability($cap) and has_capability($cap, $context)) {
+ if (has_capability($cap, $context)) {
return true;
}
}
@@ -3732,9 +3732,8 @@ class admin_setting_pickroles extends admin_setting_configmulticheckbox {
* @param string $name Name of config variable
* @param string $visiblename Display name
* @param string $description Description
- * @param array $types Array of capabilities (usually moodle/legacy:something)
- * which identify roles that will be enabled by default. Default is the
- * student role
+ * @param array $types Array of archetypes which identify
+ * roles that will be enabled by default.
*/
public function __construct($name, $visiblename, $description, $types) {
parent::__construct($name, $visiblename, $description, NULL, NULL);
@@ -3776,8 +3775,8 @@ class admin_setting_pickroles extends admin_setting_configmulticheckbox {
return null;
}
$result = array();
- foreach($this->types as $capability) {
- if ($caproles = get_roles_with_capability($capability, CAP_ALLOW)) {
+ foreach($this->types as $archetype) {
+ if ($caproles = get_archetype_roles($archetype)) {
foreach ($caproles as $caprole) {
$result[$caprole->id] = 1;
}
@@ -4074,7 +4073,7 @@ class admin_setting_special_gradebookroles extends admin_setting_pickroles {
public function __construct() {
parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
get_string('configgradebookroles', 'admin'),
- array('moodle/legacy:student'));
+ array('student'));
}
}
@@ -4117,7 +4116,7 @@ class admin_setting_special_coursemanager extends admin_setting_pickroles {
public function __construct() {
parent::__construct('coursemanager', get_string('coursemanager', 'admin'),
get_string('configcoursemanager', 'admin'),
- array('moodle/legacy:editingteacher'));
+ array('editingteacher'));
}
}
diff --git a/lib/blocklib.php b/lib/blocklib.php
index d08d6cbcef7..1977027b980 100644
--- a/lib/blocklib.php
+++ b/lib/blocklib.php
@@ -307,6 +307,7 @@ class block_manager {
* @return boolean Whether there is anything in this region.
*/
public function region_has_content($region, $output) {
+
if (!$this->is_known_region($region)) {
return false;
}
@@ -448,13 +449,14 @@ class block_manager {
list($pagetypepatterntest, $pagetypepatternparams) =
$DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest0000');
+ list($ccselect, $ccjoin) = context_instance_preload_sql('b.id', CONTEXT_BLOCK, 'ctx');
+
$params = array(
'subpage1' => $this->page->subpage,
'subpage2' => $this->page->subpage,
'contextid1' => $context->id,
'contextid2' => $context->id,
'pagetype' => $this->page->pagetype,
- 'contextblock' => CONTEXT_BLOCK,
);
$sql = "SELECT
bi.id,
@@ -469,11 +471,8 @@ class block_manager {
COALESCE(bp.visible, 1) AS visible,
COALESCE(bp.region, bi.defaultregion) AS region,
COALESCE(bp.weight, bi.defaultweight) AS weight,
- bi.configdata,
- ctx.id AS ctxid,
- ctx.path AS ctxpath,
- ctx.depth AS ctxdepth,
- ctx.contextlevel AS ctxlevel
+ bi.configdata
+ $ccselect
FROM {block_instances} bi
JOIN {block} b ON bi.blockname = b.name
@@ -481,8 +480,7 @@ class block_manager {
AND bp.contextid = :contextid1
AND bp.pagetype = :pagetype
AND bp.subpage = :subpage1
- JOIN {context} ctx ON ctx.contextlevel = :contextblock
- AND ctx.instanceid = bi.id
+ $ccjoin
WHERE
$contexttest
@@ -500,7 +498,7 @@ class block_manager {
$this->birecordsbyregion = $this->prepare_per_region_arrays();
$unknown = array();
foreach ($blockinstances as $bi) {
- $bi = make_context_subobj($bi);
+ context_instance_preload($bi);
if ($this->is_known_region($bi->region)) {
$this->birecordsbyregion[$bi->region][] = $bi;
} else {
@@ -824,7 +822,6 @@ class block_manager {
if ($this->movingblock && $lastblock != $this->movingblock) {
$results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight + 1));
}
-
return $results;
}
@@ -890,10 +887,10 @@ class block_manager {
//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);
-
+
$controls[] = array('url' => $CFG->wwwroot . '/' . $CFG->admin .
'/roles/assign.php?contextid=' . $block->context->id . '&returnurl=' . urlencode($return),
'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role'));
diff --git a/lib/datalib.php b/lib/datalib.php
index 31e46957953..63b0e8e96f2 100644
--- a/lib/datalib.php
+++ b/lib/datalib.php
@@ -27,21 +27,22 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
- /**
- * The maximum courses in a category
- * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
- */
+/**
+ * The maximum courses in a category
+ * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
+ */
define('MAX_COURSES_IN_CATEGORY', 10000);
+
/**
* The maximum number of course categories
* MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/
define('MAX_COURSE_CATEGORIES', 10000);
- /**
- * Number of seconds to wait before updating lastaccess information in DB.
- */
- define('LASTACCESS_UPDATE_SECS', 60);
+/**
+ * Number of seconds to wait before updating lastaccess information in DB.
+ */
+define('LASTACCESS_UPDATE_SECS', 60);
/**
* Returns $user object of the main admin user
@@ -51,44 +52,33 @@ define('MAX_COURSE_CATEGORIES', 10000);
* @static object $myadmin
* @return object An associative array representing the admin user.
*/
-function get_admin () {
- static $myadmin;
+function get_admin() {
+ static $mainadmin = null;
- if (! isset($admin)) {
+ if (!isset($mainadmin)) {
if (! $admins = get_admins()) {
return false;
}
- $admin = reset($admins);//reset returns first element
+ //TODO: add some admin setting for specifying of THE main admin
+ // for now return the first assigned admin
+ $mainadmin = reset($admins);
}
- return $admin;
+ return $mainadmin;
}
/**
- * Returns list of all admins, using 1 DB query. It depends on DB schema v1.7
- * but does not depend on the v1.9 datastructures (context.path, etc).
+ * Returns list of all admins, using 1 DB query
*
- * @global object
* @return array
*/
function get_admins() {
- global $DB;
+ global $DB, $CFG;
- $sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid
- FROM {role_capabilities} rc
- JOIN {context} ctx ON ctx.id=rc.contextid
- JOIN {role_assignments} ra ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
- WHERE ctx.contextlevel=10 AND rc.capability IN (?, ?, ?)
- GROUP BY ra.userid
- HAVING SUM(rc.permission) > 0";
- $params = array('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
-
- $sql = "SELECT u.*, ra.adminid
+ $sql = "SELECT u.*
FROM {user} u
- JOIN ($sql) ra
- ON u.id=ra.userid
- ORDER BY ra.adminid ASC";
+ WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
- return $DB->get_records_sql($sql, $params);
+ return $DB->get_records_sql($sql);
}
/**
@@ -454,12 +444,11 @@ function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*")
$visiblecourses = array();
- $sql = "SELECT $fields,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+
+ $sql = "SELECT $fields $ccselect
FROM {course} c
- JOIN {context} ctx
- ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
+ $ccjoin
$categoryselect
$sortstatement";
@@ -468,10 +457,10 @@ function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*")
// loop throught them
foreach ($courses as $course) {
- $course = make_context_subobj($course);
+ context_instance_preload($course);
if (isset($course->visible) && $course->visible <= 0) {
// for hidden courses, require visibility check
- if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
+ if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
$visiblecourses [$course->id] = $course;
}
} else {
@@ -517,12 +506,11 @@ function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c
$categoryselect = "";
}
- $sql = "SELECT $fields,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+
+ $sql = "SELECT $fields $ccselect
FROM {course} c
- JOIN {context} ctx
- ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
+ $ccjoin
$categoryselect
ORDER BY $sort";
@@ -539,10 +527,10 @@ function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c
// iteration will have to be done inside loop to keep track of the limitfrom and limitnum
$visiblecourses = array();
foreach($rs as $course) {
- $course = make_context_subobj($course);
+ context_instance_preload($course);
if ($course->visible <= 0) {
// for hidden courses, require visibility check
- if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
+ if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
$totalcount++;
if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
$visiblecourses [$course->id] = $course;
@@ -566,7 +554,6 @@ function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c
* role assignments, etc.
*
* The returned array is indexed on c.id, and each course will have
- * - $course->context - a context obj
* - $course->managers - array containing RA objects that include a $user obj
* with the minimal fields needed for fullname()
*
@@ -646,12 +633,10 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
}
// pull out all courses matching the cat
- $sql = "SELECT $coursefields,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+ $sql = "SELECT $coursefields $ccselect
FROM {course} c
- JOIN {context} ctx
- ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
+ $ccjoin
$where
$sortstatement";
@@ -662,17 +647,19 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
// the context, and prepping data to fetch the
// managers efficiently later...
foreach ($courses as $k => $course) {
- $courses[$k] = make_context_subobj($courses[$k]);
+ context_instance_preload($course);
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+ $courses[$k] = $course;
$courses[$k]->managers = array();
if ($allcats === false) {
// single cat, so take just the first one...
if ($catpath === NULL) {
- $catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
+ $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
}
} else {
// chop off the contextid of the course itself
// like dirname() does...
- $catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
+ $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
}
}
} else {
@@ -717,7 +704,6 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
*
*/
$sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
- ra.hidden,
r.id AS roleid, r.name as rolename,
u.id AS userid, u.firstname, u.lastname
FROM {role_assignments} ra
@@ -742,7 +728,7 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
// This loop is fairly stupid as it stands - might get better
// results doing an initial pass clustering RAs by path.
foreach($rs as $ra) {
- $user = new StdClass;
+ $user = new stdClass;
$user->id = $ra->userid; unset($ra->userid);
$user->firstname = $ra->firstname; unset($ra->firstname);
$user->lastname = $ra->lastname; unset($ra->lastname);
@@ -751,7 +737,7 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
foreach ($courses as $k => $course) {
$courses[$k]->managers[] = $ra;
}
- } elseif ($ra->contextlevel == CONTEXT_COURSECAT) {
+ } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
if ($allcats === false) {
// It always applies
foreach ($courses as $k => $course) {
@@ -759,15 +745,16 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
}
} else {
foreach ($courses as $k => $course) {
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
// Note that strpos() returns 0 as "matched at pos 0"
- if (strpos($course->context->path, $ra->path.'/')===0) {
+ if (strpos($coursecontext->path, $ra->path.'/') === 0) {
// Only add it to subpaths
$courses[$k]->managers[] = $ra;
}
}
}
} else { // course-level
- if(!array_key_exists($ra->instanceid, $courses)) {
+ if (!array_key_exists($ra->instanceid, $courses)) {
//this course is not in a list, probably a frontpage course
continue;
}
@@ -821,9 +808,8 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
global $CFG, $USER, $DB;
- // Guest's do not have any courses
- $sitecontext = get_context_instance(CONTEXT_SYSTEM);
- if (has_capability('moodle/legacy:guest', $sitecontext, $userid, false)) {
+ // Guest account does not have any courses
+ if (isguestuser()) {
return(array());
}
@@ -902,14 +888,11 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
// the same...
// (but here we don't need to check has_cap)
$coursefields = 'c.' .join(',c.', $fields);
- $sql = "SELECT $coursefields,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
- cc.path AS categorypath
+ list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+ $sql = "SELECT $coursefields $ccselect, cc.path AS categorypath
FROM {course} c
JOIN {course_categories} cc ON c.category=cc.id
- JOIN {context} ctx
- ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
+ $ccjoin
WHERE c.id IN ($courseids)
$orderby";
$rs = $DB->get_recordset_sql($sql);
@@ -917,7 +900,7 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
$cc = 0; // keep count
foreach ($rs as $c) {
// build the context obj
- $c = make_context_subobj($c);
+ context_instance_preload($c);
if ($limit > 0 && $cc >= $limit) {
break;
@@ -939,7 +922,7 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
}
- $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
+ $courses = get_user_courses_bycap($userid, 'moodle/course:participate', $accessinfo,
$doanything, $sort, $fields,
$limit);
@@ -947,12 +930,10 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
// If we have to walk category visibility
// to eval course visibility, get the categories
if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
- $sql = "SELECT cc.id, cc.path, cc.visible,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
+ list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
+ $sql = "SELECT cc.id, cc.path, cc.visible $ccselect
FROM {course_categories} cc
- JOIN {context} ctx ON (cc.id = ctx.instanceid)
- WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
+ $ccjoin
ORDER BY cc.id";
$rs = $DB->get_recordset_sql($sql);
@@ -960,7 +941,7 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
$categories = array();
foreach($rs as $course_cat) {
// build the context obj
- $course_cat = make_context_subobj($course_cat);
+ context_instance_preload($course_cat);
$categories[$course_cat->id] = $course_cat;
}
$rs->close();
@@ -1142,12 +1123,10 @@ function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $record
$searchcond = implode(" AND ", $searchcond);
- $sql = "SELECT c.*,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+ $sql = "SELECT c.* $ccselect
FROM {course} c
- JOIN {context} ctx
- ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
+ $ccjoin
WHERE $searchcond AND c.id <> ".SITEID."
ORDER BY $sort";
$courses = array();
@@ -1159,8 +1138,9 @@ function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $record
$limitto = $limitfrom + $recordsperpage;
foreach($rs as $course) {
- $course = make_context_subobj($course);
- if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) {
+ context_instance_preload($course);
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+ if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
// Don't exit this loop till the end
// we need to count all the visible courses
// to update $totalcount
@@ -1207,34 +1187,27 @@ function get_categories($parent='none', $sort=NULL, $shallow=true) {
$sort = "ORDER BY $sort";
}
+ list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
+
if ($parent === 'none') {
- $sql = "SELECT cc.*,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ $sql = "SELECT cc.* $ccselect
FROM {course_categories} cc
- JOIN {context} ctx
- ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
+ $ccjoin
$sort";
$params = array();
} elseif ($shallow) {
- $sql = "SELECT cc.*,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ $sql = "SELECT cc.* $ccselect
FROM {course_categories} cc
- JOIN {context} ctx
- ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
+ $ccjoin
WHERE cc.parent=?
$sort";
$params = array($parent);
} else {
- $sql = "SELECT cc.*,
- ctx.id AS ctxid, ctx.path AS ctxpath,
- ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
+ $sql = "SELECT cc.* $ccselect
FROM {course_categories} cc
- JOIN {context} ctx
- ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
+ $ccjoin
JOIN {course_categories} ccp
ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").")
WHERE ccp.id=?
@@ -1245,8 +1218,9 @@ function get_categories($parent='none', $sort=NULL, $shallow=true) {
if( $rs = $DB->get_recordset_sql($sql, $params) ){
foreach($rs as $cat) {
- $cat = make_context_subobj($cat);
- if ($cat->visible || has_capability('moodle/category:viewhiddencategories',$cat->context)) {
+ context_instance_preload($cat);
+ $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
+ if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
$categories[$cat->id] = $cat;
}
}
@@ -2289,7 +2263,7 @@ function get_logs_userday($userid, $courseid, $daystart) {
*
* @global object
* @uses CONTEXT_SYSTEM
- * @param string $mode Either 'admin', 'teacher' or 'everybody'
+ * @param string $mode Either 'admin' or 'everybody'
* @param string $username The username we are searching for
* @param string $lastlogin The date from which we are searching
* @return int
@@ -2302,12 +2276,12 @@ function count_login_failures($mode, $username, $lastlogin) {
$count = new object();
- if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Return information about all accounts
+ if (is_siteadmin()) {
if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
$count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
return $count;
}
- } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
+ } else if ($mode == 'everybody') {
if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
return $count;
}
diff --git a/lib/db/access.php b/lib/db/access.php
index b528c162545..f38c10cbd8f 100644
--- a/lib/db/access.php
+++ b/lib/db/access.php
@@ -29,72 +29,6 @@
$capabilities = array(
-
- 'moodle/site:doanything' => array(
-
- 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG | RISK_DATALOSS,
-
- 'captype' => 'admin',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
- 'moodle/legacy:guest' => array(
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
- 'moodle/legacy:user' => array(
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
- 'moodle/legacy:student' => array(
-
- 'riskbitmask' => RISK_SPAM,
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
-
- 'moodle/legacy:teacher' => array(
-
- 'riskbitmask' => RISK_SPAM | RISK_PERSONAL,
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
-
- 'moodle/legacy:editingteacher' => array(
-
- 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
-
- 'moodle/legacy:coursecreator' => array(
-
- 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
-
- 'moodle/legacy:admin' => array(
-
- 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG | RISK_DATALOSS,
-
- 'captype' => 'legacy',
- 'contextlevel' => CONTEXT_SYSTEM
- ),
-
-
'moodle/site:config' => array(
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG | RISK_DATALOSS,
@@ -102,7 +36,6 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
)
),
@@ -113,7 +46,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW
)
),
@@ -125,7 +58,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
'user' => CAP_ALLOW
)
),
@@ -137,7 +70,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -149,7 +82,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:backup'
@@ -163,7 +96,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:backupdownload'
@@ -176,7 +109,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -188,7 +121,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:restore'
@@ -202,7 +135,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:import'
@@ -216,7 +149,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:backupupload'
@@ -229,7 +162,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -240,7 +173,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -250,7 +183,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -262,7 +195,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_BLOCK,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -273,7 +206,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -284,7 +217,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -297,7 +230,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -309,7 +242,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -320,7 +253,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -331,7 +264,6 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_PREVENT
)
),
@@ -342,7 +274,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -354,7 +286,7 @@ $capabilities = array(
'legacy' => array(
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
)
),
@@ -365,7 +297,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -376,7 +308,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -387,7 +319,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -400,7 +332,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -413,7 +345,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -424,7 +356,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -436,7 +368,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -449,7 +381,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -460,7 +392,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -482,7 +414,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -495,18 +427,7 @@ $capabilities = array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
- )
- ),
-
- 'moodle/role:viewhiddenassigns' => array(
-
- 'captype' => 'read',
- 'contextlevel' => CONTEXT_COURSE,
- 'legacy' => array(
- 'teacher' => CAP_ALLOW,
- 'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -518,7 +439,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -533,7 +454,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/category:update'
),
@@ -544,7 +465,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/category:visibility'
),
@@ -557,7 +478,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -577,7 +498,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -589,7 +510,21 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
+ )
+ ),
+
+ /* originaly this capability was called modole/coruse:view,
+ * but since 2.0 it is used for access to course without the enrolemnt
+ */
+ 'moodle/course:participate' => array(
+
+ 'captype' => 'read',
+ 'contextlevel' => CONTEXT_COURSE,
+ 'legacy' => array(
+ 'student' => CAP_ALLOW,
+ 'teacher' => CAP_ALLOW,
+ 'editingteacher' => CAP_ALLOW
)
),
@@ -598,10 +533,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'guest' => CAP_ALLOW,
- 'student' => CAP_ALLOW,
- 'teacher' => CAP_ALLOW,
- 'editingteacher' => CAP_ALLOW
+ 'manager' => CAP_ALLOW,
)
),
@@ -614,7 +546,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -627,7 +559,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -639,7 +571,7 @@ $capabilities = array(
'coursecreator' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -648,7 +580,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -660,7 +592,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -672,7 +604,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -684,7 +616,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -694,7 +626,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -705,7 +637,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -717,7 +649,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -729,7 +661,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:update'
),
@@ -742,7 +674,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:update'
),
@@ -755,7 +687,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:update'
),
@@ -766,7 +698,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:update'
),
@@ -778,7 +710,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:update'
),
@@ -789,7 +721,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -801,7 +733,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -811,7 +743,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -821,7 +753,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -833,7 +765,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -847,7 +779,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -860,7 +792,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -870,7 +802,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -882,7 +814,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'user' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -895,7 +827,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -910,7 +842,7 @@ $capabilities = array(
'user' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -923,7 +855,7 @@ $capabilities = array(
'user' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -936,7 +868,7 @@ $capabilities = array(
'user' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -948,7 +880,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'user' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -961,7 +893,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -974,7 +906,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -985,7 +917,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_USER,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -998,7 +930,7 @@ $capabilities = array(
'legacy' => array(
'guest' => CAP_PROHIBIT,
'user' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1009,7 +941,7 @@ $capabilities = array(
'legacy' => array(
'guest' => CAP_PROHIBIT,
'user' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1023,7 +955,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1035,7 +967,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1057,7 +989,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_USER,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1068,7 +1000,7 @@ $capabilities = array(
'legacy' => array(
'guest' => CAP_PROHIBIT,
'user' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1078,7 +1010,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1089,7 +1021,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1099,7 +1031,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1109,7 +1041,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1118,7 +1050,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1127,7 +1059,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1136,7 +1068,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1145,7 +1077,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1154,7 +1086,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1163,7 +1095,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/question:manage'
),
@@ -1175,7 +1107,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1188,7 +1120,7 @@ $capabilities = array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1198,7 +1130,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1208,7 +1140,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1218,7 +1150,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1228,7 +1160,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1238,7 +1170,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1247,7 +1179,7 @@ $capabilities = array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1258,7 +1190,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:viewcoursegrades'
),
@@ -1278,7 +1210,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:viewcoursegrades'
),
@@ -1289,7 +1221,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:managegrades'
),
@@ -1301,7 +1233,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:managegrades'
),
@@ -1312,7 +1244,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:managegrades'
),
@@ -1323,7 +1255,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:managegrades'
),
@@ -1333,7 +1265,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:managegrades'
),
@@ -1343,7 +1275,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/course:managegrades'
),
@@ -1353,7 +1285,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1362,7 +1294,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1371,7 +1303,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1389,7 +1321,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1401,7 +1333,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1413,7 +1345,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1423,7 +1355,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
'user' => CAP_ALLOW
)
),
@@ -1434,7 +1366,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
'user' => CAP_ALLOW
)
),
@@ -1445,7 +1377,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -1494,7 +1426,7 @@ $capabilities = array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
'moodle/comment:post' => array(
@@ -1508,7 +1440,7 @@ $capabilities = array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
'moodle/comment:delete' => array(
@@ -1519,7 +1451,7 @@ $capabilities = array(
'legacy' => array(
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
'moodle/webservice:createtoken' => array(
@@ -1528,7 +1460,7 @@ $capabilities = array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
'moodle/rating:view' => array(
@@ -1538,7 +1470,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
'moodle/rating:viewall' => array(
@@ -1549,7 +1481,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
'moodle/rating:rate' => array(
@@ -1558,7 +1490,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
);
diff --git a/lib/db/install.php b/lib/db/install.php
index b3748cdf44c..c7ad4785e93 100644
--- a/lib/db/install.php
+++ b/lib/db/install.php
@@ -6,14 +6,14 @@
function xmldb_main_install() {
global $CFG, $DB, $SITE;
-/// make sure system context exists
+ /// make sure system context exists
$syscontext = get_system_context(false);
if ($syscontext->id != 1) {
throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected system context id created!');
}
-// create site course
+ /// create site course
$newsite = new object();
$newsite->fullname = "";
$newsite->shortname = "";
@@ -35,10 +35,10 @@ function xmldb_main_install() {
}
-/// make sure site course context exists
+ /// make sure site course context exists
get_context_instance(CONTEXT_COURSE, $SITE->id);
-/// create default course category
+ /// create default course category
$cat = get_course_category();
$defaults = array(
@@ -66,7 +66,7 @@ function xmldb_main_install() {
}
-/// bootstrap mnet
+ /// bootstrap mnet
$mnethost = new object();
$mnethost->wwwroot = $CFG->wwwroot;
$mnethost->name = '';
@@ -108,7 +108,7 @@ function xmldb_main_install() {
$DB->insert_record('mnet_application', $mnet_app);
-/// insert log entries - replaces statements section in install.xml
+ /// insert log entries - replaces statements section in install.xml
update_log_display_entry('user', 'view', 'user', 'CONCAT(firstname,\' \',lastname)');
update_log_display_entry('course', 'user report', 'user', 'CONCAT(firstname,\' \',lastname)');
update_log_display_entry('course', 'view', 'course', 'fullname');
@@ -130,7 +130,7 @@ function xmldb_main_install() {
update_log_display_entry('tag', 'update', 'tag', 'name');
-/// Create guest record
+ /// Create guest record - do not assign any role, guest user get's the default guest role automatically on the fly
$guest = new object();
$guest->auth = 'manual';
$guest->username = 'guest';
@@ -146,7 +146,7 @@ function xmldb_main_install() {
$guest->id = $DB->insert_record('user', $guest);
-/// Now create admin user
+ /// Now create admin user
$admin = new object();
$admin->auth = 'manual';
$admin->firstname = get_string('admin');
@@ -161,54 +161,81 @@ function xmldb_main_install() {
$admin->timemodified = time();
$admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr(); // installation hijacking prevention
$admin->id = $DB->insert_record('user', $admin);
+ /// Store list of admins
+ set_config('siteadmins', $admin->id);
-/// Install the roles system.
- $adminrole = create_role(get_string('administrator'), 'admin',
- get_string('administratordescription'), 'moodle/legacy:admin');
- $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator',
- get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
- $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher',
- get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
- $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher',
- get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
- $studentrole = create_role(get_string('defaultcoursestudent'), 'student',
- get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
- $guestrole = create_role(get_string('guest'), 'guest',
- get_string('guestdescription'), 'moodle/legacy:guest');
- $userrole = create_role(get_string('authenticateduser'), 'user',
- get_string('authenticateduserdescription'), 'moodle/legacy:user');
+ /// Install the roles system.
+ $managerrole = create_role(get_string('manager', 'role'), 'manager', get_string('managerdescription', 'role'), 'manager');
+ $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'coursecreator');
+ $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'editingteacher');
+ $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'teacher');
+ $studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'student');
+ $guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'guest');
+ $userrole = create_role(get_string('authenticateduser'), 'user', get_string('authenticateduserdescription'), 'user');
+ $frontpagerole = create_role(get_string('frontpageuser', 'role'), 'frontpage', get_string('frontpageuserdescription', 'role'), 'frontpage');
/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
- assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
update_capabilities('moodle');
external_update_descriptions('moodle');
- /// assign default roles
- role_assign($guestrole, $guest->id, 0, $syscontext->id);
- role_assign($adminrole, $admin->id, 0, $syscontext->id);
+ /// Default allow assign
+ $defaultallowassigns = array(
+ array($managerrole, $managerrole),
+ array($managerrole, $coursecreatorrole),
+ array($managerrole, $editteacherrole),
+ array($managerrole, $noneditteacherrole),
+ array($managerrole, $studentrole),
- /// Default allow assign/override/switch.
- $defaultallows = array(
- $coursecreatorrole => $noneditteacherrole,
- $coursecreatorrole => $editteacherrole,
- $coursecreatorrole => $studentrole,
- $coursecreatorrole => $guestrole,
-
- $editteacherrole => $noneditteacherrole,
- $editteacherrole => $studentrole,
- $editteacherrole => $guestrole,
+ array($editteacherrole, $noneditteacherrole),
+ array($editteacherrole, $studentrole),
);
-
- foreach ($defaultallows as $fromroleid => $toroleid) {
+ foreach ($defaultallowassigns as $allow) {
+ list($fromroleid, $toroleid) = $allow;
allow_assign($fromroleid, $toroleid);
+ }
+
+ /// Default allow override
+ $defaultallowoverrides = array(
+ array($managerrole, $managerrole),
+ array($managerrole, $coursecreatorrole),
+ array($managerrole, $editteacherrole),
+ array($managerrole, $noneditteacherrole),
+ array($managerrole, $studentrole),
+ array($managerrole, $guestrole),
+ array($managerrole, $userrole),
+ array($managerrole, $frontpagerole),
+
+ array($editteacherrole, $noneditteacherrole),
+ array($editteacherrole, $studentrole),
+ array($editteacherrole, $guestrole),
+ );
+ foreach ($defaultallowoverrides as $allow) {
+ list($fromroleid, $toroleid) = $allow;
allow_override($fromroleid, $toroleid); // There is a rant about this in MDL-15841.
+ }
+
+ /// Default allow switch.
+ $defaultallowswitch = array(
+ array($managerrole, $editteacherrole),
+ array($managerrole, $noneditteacherrole),
+ array($managerrole, $studentrole),
+ array($managerrole, $guestrole),
+
+ array($editteacherrole, $noneditteacherrole),
+ array($editteacherrole, $studentrole),
+ array($editteacherrole, $guestrole),
+
+ array($noneditteacherrole, $studentrole),
+ array($noneditteacherrole, $guestrole),
+ );
+ foreach ($defaultallowswitch as $allow) {
+ list($fromroleid, $toroleid) = $allow;
allow_switch($fromroleid, $toroleid);
}
- allow_switch($noneditteacherrole, $studentrole);
/// Set up the context levels where you can assign each role.
- set_role_contextlevels($adminrole, get_default_contextlevels('admin'));
+ set_role_contextlevels($managerrole, get_default_contextlevels('manager'));
set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator'));
set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher'));
set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher'));
@@ -216,7 +243,7 @@ function xmldb_main_install() {
set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
set_role_contextlevels($userrole, get_default_contextlevels('user'));
- // init themes
+ // Init themes
set_config('themerev', 1);
// Install licenses
diff --git a/lib/db/install.xml b/lib/db/install.xml
index c3322d65e8a..01225098402 100644
--- a/lib/db/install.xml
+++ b/lib/db/install.xml
@@ -855,7 +855,8 @@
-
+
+
diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php
index 0eb1f39068b..913a6b7f48c 100644
--- a/lib/db/upgrade.php
+++ b/lib/db/upgrade.php
@@ -106,24 +106,6 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint($result, 2008050700);
}
- if ($result && $oldversion < 2008051200) {
- // if guest role used as default user role unset it and force admin to choose new setting
- if (!empty($CFG->defaultuserroleid)) {
- if ($role = $DB->get_record('role', array('id'=>$CFG->defaultuserroleid))) {
- if ($guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
- if (isset($guestroles[$role->id])) {
- set_config('defaultuserroleid', null);
- echo $OUTPUT->notification('Guest role removed from "Default role for all users" setting, please select another role.', 'notifysuccess');
- }
- }
- } else {
- set_config('defaultuserroleid', null);
- }
- }
- /// Main savepoint reached
- upgrade_main_savepoint($result, 2008051200);
- }
-
if ($result && $oldversion < 2008051201) {
echo $OUTPUT->notification('Increasing size of user idnumber field, this may take a while...', 'notifysuccess');
upgrade_set_timeout(60*20); // this may take a while
@@ -209,14 +191,6 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint($result, 2008070300);
}
- if ($result && $oldversion < 2008070700) {
- if (isset($CFG->defaultuserroleid) and isset($CFG->guestroleid) and $CFG->defaultuserroleid == $CFG->guestroleid) {
- // guest can not be selected in defaultuserroleid!
- unset_config('defaultuserroleid');
- }
- upgrade_main_savepoint($result, 2008070700);
- }
-
if ($result && $oldversion < 2008070701) {
/// Define table portfolio_instance to be created
@@ -920,9 +894,6 @@ function xmldb_main_upgrade($oldversion) {
/// Defaults, should match moodle_install_roles.
$rolecontextlevels = array();
- if (isset($roleids['admin'])) {
- $rolecontextlevels[$roleids['admin']] = get_default_contextlevels('admin');
- }
if (isset($roleids['coursecreator'])) {
$rolecontextlevels[$roleids['coursecreator']] = get_default_contextlevels('coursecreator');
}
@@ -963,50 +934,6 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint($result, 2008110602);
}
- /// Remove any role overrides for moodle/site:doanything, or any permissions
- /// for it in a role without legacy:admin.
- if ($result && $oldversion < 2008110603) {
- $systemcontext = get_context_instance(CONTEXT_SYSTEM);
-
- // Remove all overrides.
- $DB->delete_records_select('role_capabilities', 'capability = ? AND contextid <> ?', array('moodle/site:doanything', $systemcontext->id));
-
- // Get the ids of all the roles that are moodle/legacy:admin.
- $adminroleids = $DB->get_records_menu('role_capabilities',
- array('capability' => 'moodle/legacy:admin', 'permission' => 1, 'contextid' => $systemcontext->id),
- '', 'id, roleid');
-
- // Remove moodle/site:doanything from all other roles.
- list($notroletest, $params) = $DB->get_in_or_equal($adminroleids, SQL_PARAMS_QM, '', false);
- $DB->delete_records_select('role_capabilities', "roleid $notroletest AND capability = ? AND contextid = ?",
- array_merge($params, array('moodle/site:doanything', $systemcontext->id)));
-
- // Ensure that for all admin-y roles, the permission for moodle/site:doanything is 1
- list($isroletest, $params) = $DB->get_in_or_equal($adminroleids);
- $DB->set_field_select('role_capabilities', 'permission', 1,
- "roleid $isroletest AND capability = ? AND contextid = ?",
- array_merge($params, array('moodle/site:doanything', $systemcontext->id)));
-
- // And for any admin-y roles where moodle/site:doanything is not set, set it.
- $doanythingroleids = $DB->get_records_menu('role_capabilities',
- array('capability' => 'moodle/site:doanything', 'permission' => 1, 'contextid' => $systemcontext->id),
- '', 'id, roleid');
- foreach ($adminroleids as $roleid) {
- if (!in_array($roleid, $doanythingroleids)) {
- $rc = new stdClass;
- $rc->contextid = $systemcontext->id;
- $rc->roleid = $roleid;
- $rc->capability = 'moodle/site:doanything';
- $rc->permission = 1;
- $rc->timemodified = time();
- $DB->insert_record('role_capabilities', $rc);
- }
- }
-
- /// Main savepoint reached
- upgrade_main_savepoint($result, 2008110603);
- }
-
/// Drop the deprecated teacher, teachers, student and students columns from the course table.
if ($result && $oldversion < 2008111200) {
$table = new xmldb_table('course');
@@ -1100,25 +1027,6 @@ function xmldb_main_upgrade($oldversion) {
upgrade_main_savepoint($result, 2008120700);
}
- /// For MDL-17501. Ensure that any role that has moodle/course:update also
- /// has moodle/course:visibility.
- if ($result && $oldversion < 2008120800) {
- /// Get the roles with 'moodle/course:update'.
- $systemcontext = get_context_instance(CONTEXT_SYSTEM);
- $roles = get_roles_with_capability('moodle/course:update', CAP_ALLOW, $systemcontext);
-
- /// Give those roles 'moodle/course:visibility'.
- foreach ($roles as $role) {
- assign_capability('moodle/course:visibility', CAP_ALLOW, $role->id, $systemcontext->id);
- }
-
- /// Force all sessions to refresh access data.
- mark_context_dirty($systemcontext->path);
-
- /// Main savepoint reached
- upgrade_main_savepoint($result, 2008120800);
- }
-
if ($result && $oldversion < 2008120801) {
/// Changing precision of field shortname on table mnet_enrol_course to (100)
@@ -3072,7 +2980,7 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
$table->add_field('scaleid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
$table->add_field('rating', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
$table->add_field('userid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
-
+
$table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
$table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
@@ -3333,7 +3241,192 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
/// Main savepoint reached
upgrade_main_savepoint($result, 2010033101);
}
-
+
+ if ($result && $oldversion < 2010033102.00) {
+ // rename course view capability to participate
+ $params = array('view'=>'moodle/course:view', 'participate'=>'moodle/course:participate');
+ $sql = "UPDATE {role_capabilities} SET capability = :participate WHERE capability = :view";
+ $DB->execute($sql, $params);
+ $sql = "UPDATE {capabilities} SET name = :participate WHERE name = :view";
+ $DB->execute($sql, $params);
+ // note: the view capability is readded again at the end of upgrade, but with different meaning
+ upgrade_main_savepoint($result, 2010033102.00);
+ }
+
+ if ($result && $oldversion < 2010033102.01) {
+ // Define field archetype to be added to role table
+ $table = new xmldb_table('role');
+ $field = new xmldb_field('archetype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null, 'sortorder');
+ $dbman->add_field($table, $field);
+ upgrade_main_savepoint($result, 2010033102.01);
+ }
+
+ if ($result && $oldversion < 2010033102.02) {
+ // Set archetype for existing roles and change admin role to manager role
+ $sql = "SELECT r.*, rc.capability
+ FROM {role} r
+ JOIN {role_capabilities} rc ON rc.roleid = r.id
+ WHERE rc.contextid = :syscontextid AND rc.capability LIKE :legacycaps
+ ORDER BY r.id";
+ $params = array('syscontextid'=>SYSCONTEXTID, 'legacycaps'=>'moodle/legacy:%');
+ $substart = strlen('moodle/legacy:');
+ $roles = $DB->get_recordset_sql($sql, $params); // in theory could be multiple legacy flags in one role
+ foreach ($roles as $role) {
+ $role->archetype = substr($role->capability, $substart);
+ unset($role->capability);
+ if ($role->archetype === 'admin') {
+ $role->archetype = 'manager';
+ if ($role->shortname === 'admin') {
+ $role->shortname = 'manager';
+ $role->name = get_string('manager', 'role');
+ $role->description = get_string('managerdescription', 'role');
+ }
+ }
+ $DB->update_record('role', $role);
+ }
+ $roles->close();
+
+ upgrade_main_savepoint($result, 2010033102.02);
+ }
+
+ if ($result && $oldversion < 2010033102.03) {
+ // Now pick site admins (===have manager role assigned at the system context)
+ // and store them in the new $CFG->siteadmins setting as comma separated list
+ $sql = "SELECT ra.id, ra.userid
+ FROM {role_assignments} ra
+ JOIN {role} r ON r.id = ra.roleid
+ JOIN {user} u ON u.id = ra.userid
+ WHERE ra.contextid = :syscontext AND r.archetype = 'manager' AND u.deleted = 0
+ ORDER BY ra.id";
+ $ras = $DB->get_records_sql($sql, array('syscontext'=>SYSCONTEXTID));
+ $admins = array();
+ foreach ($ras as $ra) {
+ $admins[$ra->userid] = $ra->userid;
+ set_config('siteadmins', implode(',', $admins)); // better to save it repeatedly, we do need at least one admin
+ $DB->delete_records('role_assignments', array('id'=>$ra->id));
+ }
+
+ upgrade_main_savepoint($result, 2010033102.03);
+ }
+
+ if ($result && $oldversion < 2010033102.04) {
+ // clean up the manager roles
+ $managers = $DB->get_records('role', array('archetype'=>'manager'));
+ foreach ($managers as $manager) {
+ // now sanitize the capabilities and overrides
+ $DB->delete_records('role_capabilities', array('capability'=>'moodle/site:config', 'roleid'=>$manager->id)); // only site admins may configure servers
+ // note: doanything and legacy caps are deleted automatically, they get moodle/course:view later at the end of the upgrade
+
+ // set usable contexts
+ $DB->delete_records('role_context_levels', array('roleid'=>$manager->id));
+ $assignlevels = array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE);
+ foreach ($assignlevels as $assignlevel) {
+ $record = (object)array('roleid'=>$manager->id, 'contextlevel'=>$assignlevel);
+ $DB->insert_record('role_context_levels', $record);
+ }
+
+ // remove manager role assignments bellow the course context level - admin role was never intended for activities and blocks,
+ // the problem is that those assignments would not be visible after upgrade and old style admins in activities make no sense anyway
+ $DB->delete_records_select('role_assignments', "roleid = :manager AND contextid IN (SELECT id FROM {context} WHERE contextlevel > 50)", array('manager'=>$manager->id));
+
+ // allow them to assign all roles except default user, guest and frontpage - users get these roles automatically on the fly when needed
+ $DB->delete_records('role_allow_assign', array('roleid'=>$manager->id));
+ $roles = $DB->get_records_sql("SELECT * FROM {role} WHERE archetype <> 'user' AND archetype <> 'guest' AND archetype <> 'frontpage'");
+ foreach ($roles as $role) {
+ $record = (object)array('roleid'=>$manager->id, 'allowassign'=>$role->id);
+ $DB->insert_record('role_allow_assign', $record);
+ }
+
+ // allow them to override all roles
+ $DB->delete_records('role_allow_override', array('roleid'=>$manager->id));
+ $roles = $DB->get_records_sql("SELECT * FROM {role}");
+ foreach ($roles as $role) {
+ $record = (object)array('roleid'=>$manager->id, 'allowoverride'=>$role->id);
+ $DB->insert_record('role_allow_override', $record);
+ }
+
+ // allow them to switch to all following roles
+ $DB->delete_records('role_allow_switch', array('roleid'=>$manager->id));
+ $roles = $DB->get_records_sql("SELECT * FROM {role} WHERE archetype IN ('student', 'teacher', 'editingteacher')");
+ foreach ($roles as $role) {
+ $record = (object)array('roleid'=>$manager->id, 'allowswitch'=>$role->id);
+ $DB->insert_record('role_allow_switch', $record);
+ }
+ }
+
+ upgrade_main_savepoint($result, 2010033102.04);
+ }
+
+ if ($result && $oldversion < 2010033102.05) {
+ // remove course:view from all roles that are not used for enrolment, it does NOT belong there because it really means user is enrolled!
+ $noenrolroles = $DB->get_records_select('role', "archetype IN ('guest', 'user', 'manager', 'coursecreator', 'frontpage')");
+ foreach ($noenrolroles as $role) {
+ $DB->delete_records('role_capabilities', array('roleid'=>$role->id, 'capability'=>'moodle/course:participate'));
+ }
+ upgrade_main_savepoint($result, 2010033102.05);
+ }
+
+ if ($result && $oldversion < 2010033102.06) {
+ // make sure there is nothing weird in default user role
+ if (!empty($CFG->defaultuserroleid)) {
+ if ($role = $DB->get_record('role', array('id'=>$CFG->defaultuserroleid))) {
+ if ($role->archetype !== '' and $role->archetype !== 'user') {
+ upgrade_log(UPGRADE_LOG_NOTICE, null, 'Default authenticated user role (defaultuserroleid) value is invalid, setting cleared.');
+ unset_config('defaultuserroleid');
+ }
+ } else {
+ unset_config('defaultuserroleid');
+ }
+ }
+ upgrade_main_savepoint($result, 2010033102.06);
+ }
+
+ if ($result && $oldversion < 2010033102.07) {
+ if (!empty($CFG->displayloginfailures) and $CFG->displayloginfailures === 'teacher') {
+ upgrade_log(UPGRADE_LOG_NOTICE, null, 'Displaying of login failuters to teachers is not supported any more.');
+ unset_config('displayloginfailures');
+ }
+ upgrade_main_savepoint($result, 2010033102.07);
+ }
+
+ if ($result && $oldversion < 2010033102.08) {
+ // make sure there are no problems in default guest role settings
+ if (!empty($CFG->guestroleid)) {
+ if ($role = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
+ if ($role->archetype !== '' and $role->archetype !== 'guest') {
+ upgrade_log(UPGRADE_LOG_NOTICE, null, 'Default guest role (guestroleid) value is invalid, setting cleared.');
+ unset_config('guestroleid');
+ }
+ } else {
+ upgrade_log(UPGRADE_LOG_NOTICE, null, 'Role specified in Default guest role (guestroleid) doeas not exist, setting cleared.');
+ unset_config('guestroleid');
+ }
+ }
+ // remove all roles of the guest account - the only way to change it is to override the guest role, sorry
+ // the guest account gets all the role assignemnts on the fly whcih works fine in has_capability(),
+ $DB->delete_records_select('role_assignments', "userid IN (SELECT id FROM {user} WHERE username = 'guest')");
+
+ upgrade_main_savepoint($result, 2010033102.08);
+ }
+
+ if ($result && $oldversion < 2010033102.09) {
+ // For MDL-17501. Ensure that any role that has moodle/course:update also has moodle/course:visibility.
+ // Get the roles with 'moodle/course:update'.
+ $systemcontext = get_context_instance(CONTEXT_SYSTEM);
+ $roles = get_roles_with_capability('moodle/course:update', CAP_ALLOW, $systemcontext);
+
+ // Give those roles 'moodle/course:visibility'.
+ foreach ($roles as $role) {
+ assign_capability('moodle/course:visibility', CAP_ALLOW, $role->id, $systemcontext->id);
+ }
+
+ // Force all sessions to refresh access data.
+ mark_context_dirty($systemcontext->path);
+
+ // Main savepoint reached
+ upgrade_main_savepoint($result, 2010033102.09);
+ }
+
return $result;
}
diff --git a/lib/deprecatedlib.php b/lib/deprecatedlib.php
index 9accb244a9f..f40e141bb40 100644
--- a/lib/deprecatedlib.php
+++ b/lib/deprecatedlib.php
@@ -29,140 +29,61 @@
*/
/**
- * Determines if a user is a teacher (or better)
- *
- * @global object
- * @uses CONTEXT_COURSE
- * @uses CONTEXT_SYSTEM
- * @param int $courseid The id of the course that is being viewed, if any
- * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
- * @param bool $obsolete_includeadmin Not used any more
- * @return bool
- */
-function isteacher($courseid=0, $userid=0, $obsolete_includeadmin=true) {
-/// Is the user able to access this course as a teacher?
- global $CFG;
-
- if ($courseid) {
- $context = get_context_instance(CONTEXT_COURSE, $courseid);
- } else {
- $context = get_context_instance(CONTEXT_SYSTEM);
- }
-
- return (has_capability('moodle/legacy:teacher', $context, $userid, false)
- or has_capability('moodle/legacy:editingteacher', $context, $userid, false)
- or has_capability('moodle/legacy:admin', $context, $userid, false));
-}
-
-/**
- * Determines if a user is a teacher in any course, or an admin
- *
- * @global object
- * @global object
- * @global object
- * @uses CAP_ALLOW
- * @uses CONTEXT_SYSTEM
- * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
- * @param bool $includeadmin Include anyone wo is an admin as well
- * @return bool
- */
-function isteacherinanycourse($userid=0, $includeadmin=true) {
- global $USER, $CFG, $DB;
-
- if (!$userid) {
- if (empty($USER->id)) {
- return false;
- }
- $userid = $USER->id;
- }
-
- if (!$DB->record_exists('role_assignments', array('userid'=>$userid))) { // Has no roles anywhere
- return false;
- }
-
-/// If this user is assigned as an editing teacher anywhere then return true
- if ($roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) {
- foreach ($roles as $role) {
- if ($DB->record_exists('role_assignments', array('roleid'=>$role->id, 'userid'=>$userid))) {
- return true;
- }
- }
- }
-
-/// If this user is assigned as a non-editing teacher anywhere then return true
- if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW)) {
- foreach ($roles as $role) {
- if ($DB->record_exists('role_assignments', array('roleid'=>$role->id, 'userid'=>$userid))) {
- return true;
- }
- }
- }
-
-/// Include admins if required
- if ($includeadmin) {
- $context = get_context_instance(CONTEXT_SYSTEM);
- if (has_capability('moodle/legacy:admin', $context, $userid, false)) {
- return true;
- }
- }
-
- return false;
-}
-
-
-/**
- * Determines if the specified user is logged in as guest.
- *
- * See {@link isguestuser()} as an alternative
- *
* @deprecated
- * @global object
- * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
- * @return bool
*/
-function isguest($userid=0) {
- global $CFG;
-
- $context = get_context_instance(CONTEXT_SYSTEM);
-
- return has_capability('moodle/legacy:guest', $context, $userid, false);
+function isteacher() {
+ error('Function isteacher() was removed, please use capabilities instead!');
}
+/**
+ * @deprecated
+ */
+function isteacherinanycourse() {
+ error('Function isteacherinanycourse() was removed, please use capabilities instead!');
+}
/**
- * Get the guest user information from the database
- *
- * @todo Is object(user) a correct return type? Or is array the proper return type with a
- * note that the contents include all details for a user.
- *
- * @return object(user) An associative array with the details of the guest user account.
+ * @deprecated
*/
function get_guest() {
- return get_complete_user_data('username', 'guest');
+ error('Function get_guest() was removed, please use capabilities instead!');
}
/**
- * Returns $user object of the main teacher for a course
- *
- * @global object
- * @uses CONTEXT_COURSE
- * @param int $courseid The course in question.
- * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
+ * @deprecated
*/
-function get_teacher($courseid) {
+function isguest() {
+ error('Function isguest() was removed, please use capabilities instead!');
+}
- global $CFG;
+/**
+ * @deprecated
+ */
+function get_teacher() {
+ error('Function get_teacher() was removed, please use capabilities instead!');
+}
- $context = get_context_instance(CONTEXT_COURSE, $courseid);
+/**
+ * Return all course participant for a given course
+ *
+ * @deprecated
+ * @param integer $courseid
+ * @return array of user
+ */
+function get_course_participants($courseid) {
+ return get_enrolled_users(get_context_instance(CONTEXT_COURSE, $courseid));
+}
- // Pass $view=true to filter hidden caps if the user cannot see them
- if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
- '', '', '', '', false, true)) {
- $users = sort_by_roleassignment_authority($users, $context);
- return array_shift($users);
- }
-
- return false;
+/**
+ * Return true if the user is a participant for a given course
+ *
+ * @deprecated
+ * @param integer $userid
+ * @param integer $courseid
+ * @return boolean
+ */
+function is_course_participant($userid, $courseid) {
+ return is_enrolled(get_context_instance(CONTEXT_COURSE, $courseid), $userid);
}
/**
@@ -195,6 +116,68 @@ function get_recent_enrolments($courseid, $timestart) {
return $DB->get_records_sql($sql, $params);
}
+
+/**
+ * Turn the ctx* fields in an objectlike record into a context subobject
+ * This allows us to SELECT from major tables JOINing with
+ * context at no cost, saving a ton of context lookups...
+ *
+ * Use context_instance_preload() instead.
+ *
+ * @deprecated since 2.0
+ * @param object $rec
+ * @return object
+ */
+function make_context_subobj($rec) {
+ $ctx = new StdClass;
+ $ctx->id = $rec->ctxid; unset($rec->ctxid);
+ $ctx->path = $rec->ctxpath; unset($rec->ctxpath);
+ $ctx->depth = $rec->ctxdepth; unset($rec->ctxdepth);
+ $ctx->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
+ $ctx->instanceid = $rec->id;
+
+ $rec->context = $ctx;
+ return $rec;
+}
+
+/**
+ * Do some basic, quick checks to see whether $rec->context looks like a valid context object.
+ *
+ * Use context_instance_preload() instead.
+ *
+ * @deprecated since 2.0
+ * @param object $rec a think that has a context, for example a course,
+ * course category, course modules, etc.
+ * @param int $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
+ * @return bool whether $rec->context looks like the correct context object
+ * for this thing.
+ */
+function is_context_subobj_valid($rec, $contextlevel) {
+ return isset($rec->context) && isset($rec->context->id) &&
+ isset($rec->context->path) && isset($rec->context->depth) &&
+ isset($rec->context->contextlevel) && isset($rec->context->instanceid) &&
+ $rec->context->contextlevel == $contextlevel && $rec->context->instanceid == $rec->id;
+}
+
+/**
+ * Ensure that $rec->context is present and correct before you continue
+ *
+ * When you have a record (for example a $category, $course, $user or $cm that may,
+ * or may not, have come from a place that does make_context_subobj, you can use
+ * this method to ensure that $rec->context is present and correct before you continue.
+ *
+ * Use context_instance_preload() instead.
+ *
+ * @deprecated since 2.0
+ * @param object $rec a thing that has an associated context.
+ * @param integer $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
+ */
+function ensure_context_subobj_present(&$rec, $contextlevel) {
+ if (!is_context_subobj_valid($rec, $contextlevel)) {
+ $rec->context = get_context_instance($contextlevel, $rec->id);
+ }
+}
+
########### FROM weblib.php ##########################################################################
diff --git a/lib/externallib.php b/lib/externallib.php
index 7e0d77ecdd6..b61e5cde2f6 100644
--- a/lib/externallib.php
+++ b/lib/externallib.php
@@ -155,7 +155,7 @@ class external_api {
}
}
return validate_param($params, $description->type, $description->allownull, get_string('errorinvalidparamsapi', 'webservice'));
-
+
} else if ($description instanceof external_single_structure) {
if (!is_array($params)) {
throw new invalid_parameter_exception(get_string('erroronlyarray', 'webservice'));
@@ -282,6 +282,8 @@ class external_api {
* @return void
*/
protected static function validate_context($context) {
+ global $CFG;
+
if (empty($context)) {
throw new invalid_parameter_exception('Context does not exist');
}
@@ -304,16 +306,26 @@ class external_api {
}
if ($context->contextlevel >= CONTEXT_COURSE) {
- //TODO: temporary bloody hack, this needs to be replaced by
- // proper enrolment and course visibility check
- // similar to require_login() (which can not be used
- // because it can be used only once and redirects)
- // oh - did I say we need to rewrite enrolments in 2.0
- // to solve this bloody mess?
- //
- // missing: hidden courses and categories, groupmembersonly,
- // conditional activities, etc.
- require_capability('moodle/course:view', $context);
+ list($context, $course, $cm) = get_context_info_array($context->id);
+ // must be enrolled or viewing
+ if (!is_enrolled($context) and !is_viewing($context)) {
+ throw new invalid_parameter_exception('Must be enrolled in course or be allowed to inspect it.');
+ }
+ // make sure the course is actually visible
+ if (!($course->visible && course_parent_visible($COURSE)) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
+ throw new invalid_parameter_exception('Invalid course.');
+ }
+ // make sure the activity is actually visible
+ if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id))) {
+ throw new invalid_parameter_exception('Invalid activity.');
+ }
+ // verify group memebers
+ if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
+ if (!groups_has_membership($cm)) {
+ throw new invalid_parameter_exception('Must be member of at least one group.');
+ }
+ }
+ //TODO: verify course completion
}
}
}
@@ -441,8 +453,8 @@ function external_generate_token($tokentype, $serviceorid, $userid, $contextorid
}
$newtoken->tokentype = $tokentype;
$newtoken->userid = $userid;
-
- $newtoken->contextid = $context->id;
+
+ $newtoken->contextid = $context->id;
$newtoken->creatorid = $USER->id;
$newtoken->timecreated = time();
$newtoken->validuntil = $validuntil;
diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index 99ef07a557c..e93bf182db1 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -733,7 +733,7 @@ function clean_param($param, $type) {
}
case PARAM_CAPABILITY:
- if (is_valid_capability($param)) {
+ if (get_capability_info($param)) {
return $param;
} else {
return '';
@@ -781,7 +781,7 @@ function clean_param($param, $type) {
// regular expression, eliminate all chars EXCEPT:
// alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
$param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
- }
+ }
return $param;
case PARAM_EMAIL:
@@ -1326,7 +1326,7 @@ function unset_user_preference($name, $otheruserid=NULL) {
function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
global $USER, $DB;
- if (empty($otheruserid) || (!empty($USER->id) && ($USER->id == $otheruserid))){
+ if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
check_user_preferences_loaded();
if (empty($name)) {
@@ -2098,7 +2098,7 @@ function get_login_url($loginguest=false) {
* in the course then the user is redirected to the course home page.
*
* When $cm parameter specified, this function sets page layout to 'module'.
- * You need to change it manually later if some other layout needed.
+ * You need to change it manually later if some other layout needed.
*
* @global object
* @global object
@@ -2225,21 +2225,15 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
}
// Fetch the course context, and prefetch its child contexts
- if (!isset($COURSE->context)) {
- if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
- print_error('nocontext');
- }
- }
- if (!empty($cm) && !isset($cm->context)) {
- if ( ! $cm->context = get_context_instance(CONTEXT_MODULE, $cm->id) ) {
- print_error('nocontext');
- }
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id, MUST_EXIST);
+ if ($cm) {
+ $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
}
// Conditional activity access control
- if(!empty($CFG->enableavailability) and $cm) {
+ if (!empty($CFG->enableavailability) and $cm) {
// We cache conditional access in session
- if(!isset($SESSION->conditionaccessok)) {
+ if (!isset($SESSION->conditionaccessok)) {
$SESSION->conditionaccessok = array();
}
// If you have been allowed into the module once then you are allowed
@@ -2250,8 +2244,7 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
$ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
// Check condition for user (this will do a query if the availability
// information depends on grade or completion information)
- if ($ci->is_available($junk) ||
- has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
+ if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
$SESSION->conditionaccessok[$cm->id] = true;
} else {
print_error('activityiscurrentlyhidden');
@@ -2261,8 +2254,7 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
if ($COURSE->id == SITEID) {
/// Eliminate hidden site activities straight away
- if (!empty($cm) && !$cm->visible
- && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
+ if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
}
user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
@@ -2271,53 +2263,53 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
} else {
/// Check if the user can be in a particular course
- if (empty($USER->access['rsw'][$COURSE->context->path])) {
+ if (empty($USER->access['rsw'][$coursecontext->path])) {
//
// MDL-13900 - If the course or the parent category are hidden
// and the user hasn't the 'course:viewhiddencourses' capability, prevent access
//
- if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
- !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
+ if ( !($COURSE->visible && course_parent_visible($COURSE)) && !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
echo $OUTPUT->header();
notice(get_string('coursehidden'), $CFG->wwwroot .'/');
}
}
- /// Non-guests who don't currently have access, check if they can be allowed in as a guest
-
- if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
- if ($COURSE->guest == 1) {
- // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
- $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
- }
- }
-
- /// If the user is a guest then treat them according to the course policy about guests
-
- if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
- if (has_capability('moodle/site:doanything', $sysctx)) {
- // administrators must be able to access any course - even if somebody gives them guest access
- user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
- return;
+ if (is_enrolled($coursecontext) or is_viewing($coursecontext)) {
+ // Enrolled user or allowed to visit course (managers, inspectors, etc.)
+ if (session_is_loggedinas()) { // Make sure the REAL person can also access this course
+ $realuser = session_get_realuser();
+ if (!is_enrolled($coursecontext, $realuser->id) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
+ echo $OUTPUT->header();
+ notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
+ }
}
+ // Make sure they can read this activity too, if specified
+ if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
+ redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
+ }
+ user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
+ return; // User is allowed to see this course
+
+ } else {
+ // guest access
switch ($COURSE->guest) { /// Check course policy about guest access
case 1: /// Guests always allowed
- if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
- echo $OUTPUT->header();
- notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
- }
- if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
+ if ($cm and !$cm->visible) { // Not allowed to see module, send to course page
redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
get_string('activityiscurrentlyhidden'));
}
+ if ($USER->username != 'guest' and !empty($CFG->guestroleid)) {
+ // Non-guests who don't currently have access, check if they can be allowed in as a guest
+ // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
+ $USER->access = load_temp_role($coursecontext, $CFG->guestroleid, $USER->access);
+ }
+
user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
return; // User is allowed to see this course
- break;
-
case 2: /// Guests allowed with key
if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
@@ -2330,7 +2322,7 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
$strloggedinasguest = get_string('loggedinasguest');
$PAGE->navbar->add($strloggedinasguest);
echo $OUTPUT->header();
- if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
+ if (empty($USER->access['rsw'][$coursecontext->path])) { // Normal guest
notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
} else {
echo $OUTPUT->notification(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
@@ -2340,30 +2332,9 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
}
break;
}
-
- /// For non-guests, check if they have course view access
-
- } else if (has_capability('moodle/course:view', $COURSE->context)) {
- if (session_is_loggedinas()) { // Make sure the REAL person can also access this course
- $realuser = session_get_realuser();
- if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) {
- echo $OUTPUT->header();
- notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
- }
- }
-
- /// Make sure they can read this activity too, if specified
-
- if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
- redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
- }
- user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
- return; // User is allowed to see this course
-
}
-
- /// Currently not enrolled in the course, so see if they want to enrol
+ // Currently not enrolled in the course, so see if they want to enrol
$SESSION->wantsurl = $FULLME;
redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
die;
@@ -2957,7 +2928,7 @@ function sync_metacourse($course) {
// Get assignments of a user to a role that exist in a child course, but
// not in the meta coure. That is, get a list of the assignments that need to be made.
if (!$assignments = $DB->get_records_sql("
- SELECT ra.id, ra.roleid, ra.userid, ra.hidden
+ SELECT ra.id, ra.roleid, ra.userid
FROM {role_assignments} ra, {context} con, {course_meta} cm
WHERE ra.contextid = con.id AND
con.contextlevel = ".CONTEXT_COURSE." AND
@@ -3005,7 +2976,7 @@ function sync_metacourse($course) {
// Make the assignments.
foreach ($assignments as $assignment) {
- $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id, 0, 0, $assignment->hidden) && $success;
+ $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id, 0, 0) && $success;
}
return $success;
@@ -3061,45 +3032,6 @@ function remove_from_metacourse($metacourseid, $courseid) {
return false;
}
-
-/**
- * Determines if a user is currently logged in
- *
- * @global object
- * @return bool
- */
-function isloggedin() {
- global $USER;
-
- return (!empty($USER->id));
-}
-
-/**
- * Determines if a user is logged in as real guest user with username 'guest'.
- * This function is similar to original isguest() in 1.6 and earlier.
- * Current isguest() is deprecated - do not use it anymore.
- *
- * @global object
- * @global object
- * @param int $user mixed user object or id, $USER if not specified
- * @return bool true if user is the real guest user, false if not logged in or other user
- */
-function isguestuser($user=NULL) {
- global $USER, $DB;
-
- if ($user === NULL) {
- $user = $USER;
- } else if (is_numeric($user)) {
- $user = $DB->get_record('user', array('id'=>$user), 'id, username');
- }
-
- if (empty($user->id)) {
- return false; // not logged in, can not be guest
- }
-
- return ($user->username == 'guest');
-}
-
/**
* Determines if the currently logged in user is in editing mode.
* Note: originally this function had $userid parameter - it was not usable anyway
@@ -4310,7 +4242,7 @@ function reset_course_userdata($data) {
if ($users = get_role_users($roleid, $context, false, 'u.id', 'u.id ASC')) {
foreach ($users as $user) {
role_unassign($roleid, $user->id, 0, $context->id);
- if (!has_capability('moodle/course:view', $context, $user->id)) {
+ if (!is_enrolled($context, $user->id)) {
$data->unenrolled[$user->id] = $user->id;
}
}
@@ -5090,7 +5022,7 @@ function email_welcome_message_to_user($course, $user=NULL) {
if (!empty($course->welcomemessage)) {
$message = $course->welcomemessage;
} else {
- $a = new Object();
+ $a = new object();
$a->coursename = $course->fullname;
$a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
$message = get_string("welcometocoursetext", "", $a);
@@ -5101,7 +5033,7 @@ function email_welcome_message_to_user($course, $user=NULL) {
$subject = get_string('welcometocourse', '', format_string($course->fullname));
$context = get_context_instance(CONTEXT_COURSE, $course->id);
- // Pass $view=true to filter hidden caps if the user cannot see them
+ // TODO: replace with $CFG->coursemanager test, 'moodle/course:update' is very wrong!!
if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC','', '', '', '', false, true)) {
$users = sort_by_roleassignment_authority($users, $context);
$teacher = array_shift($users);
diff --git a/lib/navigationlib.php b/lib/navigationlib.php
index ca7e9fd27f1..5358c45d7ec 100644
--- a/lib/navigationlib.php
+++ b/lib/navigationlib.php
@@ -438,7 +438,7 @@ class navigation_node {
$link->add_class('dimmed');
}
$content = $OUTPUT->render($link);
-
+
} else if ($this->action instanceof moodle_url) {
$attributes = array();
if ($title !== '') {
@@ -725,7 +725,7 @@ class navigation_node {
} else {
$key = array_shift($keys);
$child = $this->get($key);
-
+
if ($child !== false) {
return $child->get_by_path($keys);
}
@@ -996,7 +996,7 @@ class global_navigation extends navigation_node {
*/
protected function load_for_user($user=null) {
global $DB, $PAGE, $CFG, $USER;
-
+
$iscurrentuser = false;
if ($user === null) {
// We can't require login here but if the user isn't logged in we don't
@@ -1101,7 +1101,7 @@ class global_navigation extends navigation_node {
$reporttab->add(get_string('outlinereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'outline'))));
$reporttab->add(get_string('completereport'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'complete'))));
}
-
+
if ($viewreports || has_capability('coursereport/log:viewtoday', $coursecontext)) {
$reporttab->add(get_string('todaylogs'), new moodle_url('/course/user.php', array_merge($reportargs, array('mode'=>'todaylogs'))));
}
@@ -1156,7 +1156,7 @@ class global_navigation extends navigation_node {
/**
* Adds the provided user to an array and when the navigation is generated
* it is extended for this user.
- *
+ *
* @param object $user
*/
public function extend_for_user($user) {
@@ -1206,7 +1206,7 @@ class global_navigation extends navigation_node {
return $depth;
}
- if (isloggedin() && has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $PAGE->course->id))) {
+ if (isloggedin() && has_capability('moodle/course:participate', get_context_instance(CONTEXT_COURSE, $PAGE->course->id))) {
$depth += $this->load_course_activities($keys);
$depth += $this->load_course_sections($keys);
}
@@ -1420,31 +1420,16 @@ class global_navigation extends navigation_node {
// itself hasn't set PAGE->cm (usually set by require_login)
// Chances are this is a front page module.
$cm = get_coursemodule_from_id(false, $this->context->instanceid);
- if ($cm) {
- $cm->context = $this->context;
- $PAGE->set_cm($cm, $PAGE->course);
- } else {
- debugging('The module has not been set against the page but we are attempting to generate module specific information for navigation', DEBUG_DEVELOPER);
- return;
- }
+ $PAGE->set_cm($cm, $PAGE->course);
}
$node = $this->find_child($PAGE->cm->id, self::TYPE_ACTIVITY);
if ($node) {
$node->make_active();
- if (!isset($PAGE->course->context)) {
- // If we get here chances we are on a front page module
- $this->context = $PAGE->context;
- } else {
- $this->context = $PAGE->course->context;
- }
+ $this->context = $PAGE->context;
$file = $CFG->dirroot.'/mod/'.$PAGE->activityname.'/lib.php';
$function = $PAGE->activityname.'_extend_navigation';
- if (empty($PAGE->cm->context)) {
- $PAGE->cm->context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->instance);
- }
-
if (file_exists($file)) {
require_once($file);
if (function_exists($function)) {
@@ -1795,15 +1780,10 @@ class global_navigation extends navigation_node {
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
- // Cache capability moodle/site:config we use this in the next bit of code
- if (!$this->cache->cached('hassiteconfig')) {
- $this->cache->hassiteconfig = has_capability('moodle/site:config', $systemcontext);
- }
-
// If the user is logged in (but not as a guest), doesnt have the site config capability,
// and my courses havn't been disabled then we will show the user's courses in the
// global navigation, otherwise we will show up to FRONTPAGECOURSELIMIT available courses
- if (isloggedin() && !$this->cache->hassiteconfig && !isguestuser() && empty($CFG->disablemycourses)) {
+ if (isloggedin() && !is_siteadmin() && !isguestuser() && empty($CFG->disablemycourses)) {
if (!$this->cache->cached('mycourses')) {
$this->cache->mycourses = get_my_courses($USER->id);
}
@@ -1818,7 +1798,7 @@ class global_navigation extends navigation_node {
$accessinfo = get_user_access_sitewide($USER->id);
}
// Get the available courses using get_user_courses_bycap
- $this->cache->availablecourses = get_user_courses_bycap($USER->id, 'moodle/course:view',
+ $this->cache->availablecourses = get_user_courses_bycap($USER->id, 'moodle/course:participate',
$accessinfo, true, 'c.sortorder ASC',
array('fullname','visible', 'category'),
FRONTPAGECOURSELIMIT);
@@ -2048,7 +2028,7 @@ class global_navigation_for_ajax extends global_navigation {
$keys = array();
parent::load_course($keys, $course);
- if (isloggedin() && has_capability('moodle/course:view', $this->context)) {
+ if (isloggedin() && has_capability('moodle/course:participate', $this->context)) {
if (!$this->cache->cached('course'.$course->id.'section0')) {
$this->cache->{'course'.$course->id.'section0'} = get_course_section('0', $course->id);
}
@@ -2066,7 +2046,7 @@ class global_navigation_for_ajax extends global_navigation {
*/
protected function load_section($instanceid=0) {
global $DB, $PAGE, $CFG;
-
+
$section = $DB->get_record('course_sections', array('id'=>$instanceid), '*', MUST_EXIST);
if (!$this->cache->cached('course'.$section->course)) {
@@ -2500,7 +2480,7 @@ class settings_navigation extends navigation_node {
*/
public function initialise() {
global $DB;
-
+
if (during_initial_install()) {
return false;
}
@@ -2635,7 +2615,7 @@ class settings_navigation extends navigation_node {
$adminroot = admin_get_root(false, false);
// This is the active section identifier
$this->adminsection = $this->page->url->param('section');
-
+
// Disable the navigation from automatically finding the active node
navigation_node::$autofindactive = false;
$branchkey = $this->add(get_string('administrationsite'), null, self::TYPE_SETTING, null, 'root');
@@ -2762,17 +2742,12 @@ class settings_navigation extends navigation_node {
* @return bool|mixed Either false of a key to access the course tree by
*/
protected function load_course_settings($forceopen = false) {
- global $CFG, $USER, $SESSION;
+ global $CFG, $USER, $SESSION, $OUTPUT;
$course = $this->page->course;
- if (empty($course->context)) {
- if (!$this->cache->cached('coursecontext'.$course->id)) {
- $this->cache->{'coursecontext'.$course->id} = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
- }
- $course->context = $this->cache->{'coursecontext'.$course->id};
- }
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
if (!$this->cache->cached('canviewcourse'.$course->id)) {
- $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:view', $course->context);
+ $this->cache->{'canviewcourse'.$course->id} = has_capability('moodle/course:participate', $coursecontext);
}
if ($course->id === SITEID || !$this->cache->{'canviewcourse'.$course->id}) {
return false;
@@ -2782,7 +2757,7 @@ class settings_navigation extends navigation_node {
$coursenode = $this->get($coursenodekey);
$coursenode->forceopen = ($forceopen==true);
- if (has_capability('moodle/course:update', $course->context)) {
+ if (has_capability('moodle/course:update', $coursecontext)) {
// Add the turn on/off settings
$url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
if ($this->page->user_is_editing()) {
@@ -2880,37 +2855,37 @@ class settings_navigation extends navigation_node {
$coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
}
- if (has_capability('moodle/role:assign', $course->context)) {
+ if (has_capability('moodle/role:assign', $coursecontext)) {
// Add assign or override roles if allowed
- $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$course->context->id));
+ $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
$coursenode->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
// Override roles
- if (has_capability('moodle/role:review', $course->context) or count(get_overridable_roles($course->context))>0) {
- $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$course->context->id));
+ if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
+ $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
$coursenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
}
// Check role permissions
- if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $course->context)) {
- $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$course->context->id));
+ if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
+ $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
$coursenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
}
// Manage filters
- if (has_capability('moodle/filter:manage', $course->context) && count(filter_get_available_in_context($course->context))>0) {
- $url = new moodle_url('/filter/manage.php', array('contextid'=>$course->context->id));
+ if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
+ $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
$coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
}
}
// Add view grade report is permitted
$reportavailable = false;
- if (has_capability('moodle/grade:viewall', $course->context)) {
+ if (has_capability('moodle/grade:viewall', $coursecontext)) {
$reportavailable = true;
} else if (!empty($course->showgrades)) {
$reports = get_plugin_list('gradereport');
if (is_array($reports) && count($reports)>0) { // Get all installed reports
arsort($reports); // user is last, we want to test it first
foreach ($reports as $plugin => $plugindir) {
- if (has_capability('gradereport/'.$plugin.':view', $course->context)) {
+ if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
//stop when the first visible plugin is found
$reportavailable = true;
break;
@@ -2924,48 +2899,48 @@ class settings_navigation extends navigation_node {
}
// Add outcome if permitted
- if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $course->context)) {
+ if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
$url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
$coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/outcomes', ''));
}
// Add meta course links
if ($course->metacourse) {
- if (has_capability('moodle/course:managemetacourse', $course->context)) {
+ if (has_capability('moodle/course:managemetacourse', $coursecontext)) {
$url = new moodle_url('/course/importstudents.php', array('id'=>$course->id));
$coursenode->add(get_string('childcourses'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
- } else if (has_capability('moodle/role:assign', $course->context)) {
+ } else if (has_capability('moodle/role:assign', $coursecontext)) {
$key = $coursenode->add(get_string('childcourses'), null, self::TYPE_SETTING, null, null, new pix_icon('i/course', ''));
$coursenode->get($key)->hidden = true;;
}
}
// Manage groups in this course
- if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $course->context)) {
+ if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
$url = new moodle_url('/group/index.php', array('id'=>$course->id));
$coursenode->add(get_string('groups'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/group', ''));
}
// Backup this course
- if (has_capability('moodle/backup:backupcourse', $course->context)) {
+ if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
$url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
$coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
}
// Restore to this course
- if (has_capability('moodle/restore:restorecourse', $course->context)) {
+ if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
$url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
$coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
}
// Import data from other courses
- if (has_capability('moodle/restore:restoretargetimport', $course->context)) {
+ if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
$url = new moodle_url('/course/import.php', array('id'=>$course->id));
$coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
}
// Reset this course
- if (has_capability('moodle/course:reset', $course->context)) {
+ if (has_capability('moodle/course:reset', $coursecontext)) {
$url = new moodle_url('/course/reset.php', array('id'=>$course->id));
$coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
}
@@ -3017,13 +2992,19 @@ class settings_navigation extends navigation_node {
}
// Unenrol link
- if (empty($course->metacourse)) {
- if (has_capability('moodle/legacy:guest', $this->context, NULL, false)) { // Are a guest now
- $url = new moodle_url('/course/enrol.php', array('id'=>$course->id));
- $coursenode->add(get_string('enrolme', '', format_string($course->shortname)), $url, self::TYPE_SETTING, null, null, new pix_icon('i/user', ''));
- } else if (has_capability('moodle/role:unassignself', $this->context, NULL, false) && get_user_roles($this->context, 0, false)) { // Have some role
- $url = new moodle_url('/course/unenrol.php', array('id'=>$course->id));
- $coursenode->add(get_string('unenrolme', '', format_string($course->shortname)), $url, self::TYPE_SETTING, null, null, new pix_icon('i/user', ''));
+ if (empty($course->metacourse) && ($course->id!==SITEID)) {
+ if (is_enrolled(get_context_instance(CONTEXT_COURSE, $course->id))) {
+ if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) { // Have some role
+ $this->content->items[]=''.get_string('unenrolme', '', format_string($course->shortname)).' ';
+ $this->content->icons[]=' ';
+ }
+
+ } else if (is_viewing(get_context_instance(CONTEXT_COURSE, $course->id))) {
+ // inspector, manager, etc. - do not show anything
+ } else {
+ // access because otherwise they would not get into this course at all
+ $this->content->items[]=''.get_string('enrolme', '', format_string($course->shortname)).' ';
+ $this->content->icons[]=' ';
}
}
@@ -3083,22 +3064,13 @@ class settings_navigation extends navigation_node {
if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
$cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
- $cm->context = $this->context;
$this->page->set_cm($cm, $this->page->course);
}
- if (empty($this->page->cm->context)) {
- if ($this->context->instanceid === $this->page->cm->id) {
- $this->page->cm->context = $this->context;
- } else {
- $this->page->cm->context = get_context_instance(CONTEXT_MODULE, $this->page->cm->instance);
- }
- }
-
$modulekey = $this->add(get_string($this->page->activityname.'administration', $this->page->activityname));
$modulenode = $this->get($modulekey);
$modulenode->forceopen = true;
-
+
// Settings for the module
if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
$url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => true, 'sesskey' => sesskey()));
@@ -3124,7 +3096,7 @@ class settings_navigation extends navigation_node {
$url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
$modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING);
}
-
+
$file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
$function = $this->page->activityname.'_extend_settings_navigation';
@@ -3214,7 +3186,7 @@ class settings_navigation extends navigation_node {
$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
@@ -3225,12 +3197,12 @@ class settings_navigation extends navigation_node {
// Check that the user can view the profile
$usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
if ($course->id==SITEID) {
- if ($CFG->forceloginforprofiles && !isteacherinanycourse() && !isteacherinanycourse($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // Reduce possibility of "browsing" userbase at site level
+ if ($CFG->forceloginforprofiles && !!has_coursemanager_role($user->id) && !has_capability('moodle/user:viewdetails', $usercontext)) { // 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 {
- if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:view', $coursecontext, $user->id, false)) {
+ if ((!has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) || !has_capability('moodle/course:participate', $coursecontext, $user->id, false)) {
return false;
}
if (groups_get_course_groupmode($course) == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
@@ -3357,7 +3329,7 @@ class settings_navigation extends navigation_node {
/**
* Loads block specific settings in the navigation
- *
+ *
* @return string The key that can be used to retrieve the navigation node
*/
protected function load_block_settings() {
@@ -3453,16 +3425,14 @@ class settings_navigation extends navigation_node {
global $SITE, $CFG;
$course = clone($SITE);
- if (empty($course->context)) {
- $course->context = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
- }
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
$frontpagekey = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
$frontpage = $this->get($frontpagekey);
$frontpage->forceopen = $forceopen;
$frontpage->id = 'frontpagesettings';
- if (has_capability('moodle/course:update', $course->context)) {
+ if (has_capability('moodle/course:update', $coursecontext)) {
// Add the turn on/off settings
$url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
@@ -3481,41 +3451,41 @@ class settings_navigation extends navigation_node {
}
//Participants
- if (has_capability('moodle/site:viewparticipants', $course->context)) {
- $url = new moodle_url('/user/index.php', array('contextid'=>$course->context->id));
+ if (has_capability('moodle/site:viewparticipants', $coursecontext)) {
+ $url = new moodle_url('/user/index.php', array('contextid'=>$coursecontext->id));
$frontpage->add(get_string('participants'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/users', ''));
}
// Roles
- if (has_capability('moodle/role:assign', $course->context)) {
+ if (has_capability('moodle/role:assign', $coursecontext)) {
// Add assign or override roles if allowed
- $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$course->context->id));
+ $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$coursecontext->id));
$frontpage->add(get_string('assignroles', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
// Override roles
- if (has_capability('moodle/role:review', $course->context) or count(get_overridable_roles($course->context))>0) {
- $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$course->context->id));
+ if (has_capability('moodle/role:review', $coursecontext) or count(get_overridable_roles($coursecontext))>0) {
+ $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$coursecontext->id));
$frontpage->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
}
// Check role permissions
- if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $course->context)) {
- $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$course->context->id));
+ if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
+ $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$coursecontext->id));
$frontpage->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/roles', ''));
}
// Manage filters
- if (has_capability('moodle/filter:manage', $course->context) && count(filter_get_available_in_context($course->context))>0) {
- $url = new moodle_url('/filter/manage.php', array('contextid'=>$course->context->id));
+ if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
+ $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
$frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
}
}
// Backup this course
- if (has_capability('moodle/backup:backupcourse', $course->context)) {
+ if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
$url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
$frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
}
// Restore to this course
- if (has_capability('moodle/restore:restorecourse', $course->context)) {
+ if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
$url = new moodle_url('/files/index.php', array('id'=>$course->id, 'wdir'=>'/backupdata'));
$frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
}
diff --git a/lib/outputrenderers.php b/lib/outputrenderers.php
index 1b0afa143f7..ad5a00198ee 100644
--- a/lib/outputrenderers.php
+++ b/lib/outputrenderers.php
@@ -399,7 +399,7 @@ class core_renderer extends renderer_base {
if (empty($course->id)) {
// $course->id is not defined during installation
return '';
- } else if (!empty($USER->id)) {
+ } else if (isloggedin()) {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$fullname = fullname($USER, true);
diff --git a/lib/pagelib.php b/lib/pagelib.php
index 95e57e2ed13..fe41b899633 100644
--- a/lib/pagelib.php
+++ b/lib/pagelib.php
@@ -703,12 +703,13 @@ class moodle_page {
* @param objcet $cm a full cm objcet obtained from get_coursemodule_from_id or get_coursemodule_from_instance.
*/
public function set_cm($cm, $course = null, $module = null) {
- if (!isset($cm->name) || !isset($cm->modname)) {
+ if (!isset($cm->name) || !isset($cm->modname) || !isset($cm->id)) {
throw new coding_exception('The $cm you set on $PAGE must have been obtained with get_coursemodule_from_id or get_coursemodule_from_instance. That is, the ->name and -> modname fields must be present and correct.');
}
$this->_cm = $cm;
+ $this->_cm->context = get_context_instance(CONTEXT_MODULE, $cm->id); // hacky shortcut
if (!$this->_context) {
- $this->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
+ $this->set_context($this->_cm->context);
}
if (!$this->_course || $this->_course->id != $cm->course) {
if (!$course) {
diff --git a/lib/setuplib.php b/lib/setuplib.php
index b9c369dc0c8..11149f8f199 100644
--- a/lib/setuplib.php
+++ b/lib/setuplib.php
@@ -747,7 +747,7 @@ function get_real_size($size=0) {
*/
function redirect_if_major_upgrade_required() {
global $CFG;
- $lastmajordbchanges = 2009110400;
+ $lastmajordbchanges = 2010033103;
if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
during_initial_install() or !empty($CFG->adminsetuppending)) {
try {
diff --git a/lib/simpletest/broken_testfilelib.php b/lib/simpletest/broken_testfilelib.php
index d0185fcc6a3..d0361c0fdad 100644
--- a/lib/simpletest/broken_testfilelib.php
+++ b/lib/simpletest/broken_testfilelib.php
@@ -81,10 +81,8 @@ class filelib_test extends UnitTestCaseUsingDatabase {
// User and capability stuff (stolen from testaccesslib.php)
$syscontext = get_system_context(false);
- $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
- assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
update_capabilities('moodle');
update_capabilities('mod_forum');
diff --git a/lib/simpletest/testaccesslib.php b/lib/simpletest/testaccesslib.php
index d077dee2586..ab943274930 100644
--- a/lib/simpletest/testaccesslib.php
+++ b/lib/simpletest/testaccesslib.php
@@ -57,23 +57,20 @@ class accesslib_test extends UnitTestCaseUsingDatabase {
$syscontext = get_system_context(false);
/// Install the roles system.
- $adminrole = create_role(get_string('administrator'), 'admin',
- get_string('administratordescription'), 'moodle/legacy:admin');
$coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator',
- get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
+ get_string('coursecreatorsdescription'), 'coursecreator');
$editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher',
- get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
+ get_string('defaultcourseteacherdescription'), 'editingteacher');
$noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher',
- get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
+ get_string('noneditingteacherdescription'), 'teacher');
$studentrole = create_role(get_string('defaultcoursestudent'), 'student',
- get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
+ get_string('defaultcoursestudentdescription'), 'student');
$guestrole = create_role(get_string('guest'), 'guest',
- get_string('guestdescription'), 'moodle/legacy:guest');
+ get_string('guestdescription'), 'guest');
$userrole = create_role(get_string('authenticateduser'), 'user',
- get_string('authenticateduserdescription'), 'moodle/legacy:user');
+ get_string('authenticateduserdescription'), 'user');
/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
- assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
update_capabilities('moodle');
update_capabilities('mod_forum');
update_capabilities('mod_quiz');
@@ -174,11 +171,6 @@ class accesslib_test extends UnitTestCaseUsingDatabase {
array_map(create_function('$o', 'return $o->id;'),
get_users_by_capability($contexts[$conindex], array('mod/quiz:attempt', 'mod/quiz:reviewmyattempts'))));
}
- // System context, specifically checking doanything.
- $this->assert(new ArraysHaveSameValuesExpectation(
- array($users['a']->id)),
- array_map(create_function('$o', 'return $o->id;'),
- get_users_by_capability($contexts[0], 'moodle/site:doanything')));
// For reference: get_users_by_capability argument order:
// $context, $capability, $fields='', $sort='', $limitfrom='', $limitnum='',
@@ -271,8 +263,7 @@ class accesslib_test extends UnitTestCaseUsingDatabase {
$this->load_test_data('capabilities',
array('name'), array(
- array('moodle/site:doanything'),
- array('moodle/course:view')));
+ array('moodle/course:participate')));
$roles = $this->load_test_data('role',
array( 'name', 'shortname', 'description', 'sortorder'), array(
@@ -283,15 +274,13 @@ class accesslib_test extends UnitTestCaseUsingDatabase {
$adminid = $roles['admin']->id;
$r1id = $roles['r1']->id;
$r2id = $roles['r2']->id;
- $funnyid = $roles['funny']->id; // strange role to test that roles with 'moodle/site:doanything' and 'moodle/course:view' are not returned.
+ $funnyid = $roles['funny']->id; // strange role to test that roles with 'moodle/course:participate' are not returned.
$this->load_test_data('role_capabilities',
array('roleid', 'capability', 'contextid', 'permission'), array(
- array($adminid, 'moodle/site:doanything', SYSCONTEXTID, CAP_ALLOW),
- array( $r1id, 'moodle/course:view', SYSCONTEXTID + 1, CAP_ALLOW),
- array( $r2id, 'moodle/course:view', SYSCONTEXTID, CAP_ALLOW),
- array($funnyid, 'moodle/site:doanything', SYSCONTEXTID, CAP_ALLOW),
- array($funnyid, 'moodle/course:view', SYSCONTEXTID, CAP_ALLOW)));
+ array( $r1id, 'moodle/course:participate', SYSCONTEXTID + 1, CAP_ALLOW),
+ array( $r2id, 'moodle/course:participate', SYSCONTEXTID, CAP_ALLOW),
+ array($funnyid, 'moodle/course:participate', SYSCONTEXTID, CAP_ALLOW)));
$this->load_test_data('role_assignments',
array('userid', 'contextid', 'roleid'), array(
@@ -306,7 +295,7 @@ class accesslib_test extends UnitTestCaseUsingDatabase {
array( $r2id , $r2id),
array( $r2id , $funnyid)));
- // Admin should be able to switch to any role with 'moodle/course:view' in any context.
+ // Admin should be able to switch to any role with 'moodle/course:participate' in any context.
$this->switch_global_user_id(1);
accesslib_clear_all_caches_for_unit_testing();
$this->assert(new ArraysHaveSameValuesExpectation(array($r2id)), array_keys(get_switchable_roles($syscontext)));
@@ -333,13 +322,10 @@ class accesslib_test extends UnitTestCaseUsingDatabase {
$this->load_test_data('role_capabilities',
array('roleid', 'capability', 'contextid', 'permission'), array(
array( 1, 'moodle/forum:replypost', SYSCONTEXTID, CAP_ALLOW),
- array( 2, 'moodle/course:view', SYSCONTEXTID, CAP_ALLOW),
- array( 3, 'moodle/site:doanything', SYSCONTEXTID, CAP_ALLOW),
- array( 4, 'moodle/site:doanything', SYSCONTEXTID, CAP_ALLOW),
- array( 4, 'moodle/course:view', SYSCONTEXTID, CAP_ALLOW),
- array( 5, 'moodle/course:view', SYSCONTEXTID, CAP_ALLOW),
- array( 5, 'moodle/site:doanything', SYSCONTEXTID, CAP_PREVENT),
- array( 6, 'moodle/course:view', SYSCONTEXTID, CAP_PREVENT),
+ array( 2, 'moodle/course:participate', SYSCONTEXTID, CAP_ALLOW),
+ array( 4, 'moodle/course:participate', SYSCONTEXTID, CAP_ALLOW),
+ array( 5, 'moodle/course:participate', SYSCONTEXTID, CAP_ALLOW),
+ array( 6, 'moodle/course:participate', SYSCONTEXTID, CAP_PREVENT),
));
$this->switch_to_test_db();
diff --git a/lib/statslib.php b/lib/statslib.php
index ab031171a51..a57de28e8a5 100644
--- a/lib/statslib.php
+++ b/lib/statslib.php
@@ -855,24 +855,21 @@ function stats_cron_monthly() {
* @param bool $includedoanything include also admins
* @return array ra join and where string
*/
-function stats_get_enrolled_sql($limit, $includedoanything) {
+function stats_get_enrolled_sql($limit, $ignored) {
global $CFG;
static $n = 0;
$params = array();
$n++;
- $adm = $includedoanything ? " OR rc.capability = :sge_doanything_$n " : "";
- $params['sge_doanything_'.$n] = 'moodle/site:doanything';
-
$join = "JOIN {context} ctx ON ctx.id = ra.contextid
CROSS JOIN {course} c
JOIN {role_capabilities} rc ON rc.roleid = ra.roleid";
- $where = "((rc.capability = :sge_courseview_$n $adm)
+ $where = "((rc.capability = :sge_courseview_$n)
AND rc.permission = 1 AND rc.contextid = ".SYSCONTEXTID."
AND (ctx.contextlevel = ".CONTEXT_SYSTEM."
OR (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE.")";
- $params['sge_courseview_'.$n] = 'moodle/course:view';
+ $params['sge_courseview_'.$n] = 'moodle/course:participate';
for($i=1; $i<=$limit; $i++) {
if ($i == 1) {
diff --git a/lib/upgradelib.php b/lib/upgradelib.php
index 0c937ea9b51..5cbc80d0969 100644
--- a/lib/upgradelib.php
+++ b/lib/upgradelib.php
@@ -40,10 +40,10 @@ define('UPGRADE_LOG_ERROR', 2);
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class upgrade_exception extends moodle_exception {
- function __construct($plugin, $version) {
+ function __construct($plugin, $version, $debuginfo=NULL) {
global $CFG;
$a = (object)array('plugin'=>$plugin, 'version'=>$version);
- parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
+ parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
}
}
diff --git a/login/change_password.php b/login/change_password.php
index 1bc56471c7c..c259a2c0a08 100644
--- a/login/change_password.php
+++ b/login/change_password.php
@@ -46,7 +46,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) {
}
// require proper login; guest user can not change password
-if (empty($USER->id) or isguestuser()) {
+if (!isloggedin() or isguestuser()) {
if (empty($SESSION->wantsurl)) {
$SESSION->wantsurl = $CFG->httpswwwroot.'/login/change_password.php';
}
diff --git a/login/index.php b/login/index.php
index d36354ed55e..fde2041a71e 100644
--- a/login/index.php
+++ b/login/index.php
@@ -100,7 +100,7 @@ if (empty($CFG->usesid) and $testcookies and (get_moodle_cookie() == '')) { /
$errormsg = get_string("cookiesnotenabled");
$errorcode = 1;
-} else if ($frm) { // Login WITH cookies
+} else if ($frm and isset($frm->username)) { // Login WITH cookies
$frm->username = trim(moodle_strtolower($frm->username));
@@ -188,7 +188,7 @@ if (empty($CFG->usesid) and $testcookies and (get_moodle_cookie() == '')) { /
}
/// Go to my-moodle page instead of homepage if mymoodleredirect enabled
- if (!has_capability('moodle/site:config', $context) and !empty($CFG->mymoodleredirect) and !has_capability('moodle/legacy:guest',$context, 0, false)) {
+ if (!empty($CFG->mymoodleredirect) and !is_siteadmin() and !isguestuser()) {
if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
$urltogo = $CFG->wwwroot.'/my/';
}
diff --git a/message/discussion.php b/message/discussion.php
index 6c574a0890b..8e9bf732454 100644
--- a/message/discussion.php
+++ b/message/discussion.php
@@ -28,7 +28,7 @@
require_login();
- if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+ if (isguestuser()) {
redirect($CFG->wwwroot);
}
diff --git a/message/history.php b/message/history.php
index 8a00131d3e3..e96cd400876 100644
--- a/message/history.php
+++ b/message/history.php
@@ -28,7 +28,7 @@ require('lib.php');
require_login();
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
redirect($CFG->wwwroot);
}
diff --git a/message/index.php b/message/index.php
index 667dba47d46..bfd26a0225c 100644
--- a/message/index.php
+++ b/message/index.php
@@ -28,7 +28,7 @@ require('lib.php');
require_login(0, false);
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
redirect($CFG->wwwroot);
}
diff --git a/message/refresh.php b/message/refresh.php
index bfef3df773f..61f69d32922 100644
--- a/message/refresh.php
+++ b/message/refresh.php
@@ -28,7 +28,7 @@ define('MESSAGE_DEFAULT_REFRESH', 5);
require_login();
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
redirect($CFG->wwwroot);
}
diff --git a/message/user.php b/message/user.php
index 58e6cbceca0..f9acf8535a7 100644
--- a/message/user.php
+++ b/message/user.php
@@ -26,7 +26,7 @@ require('lib.php');
require_login();
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
redirect($CFG->wwwroot);
}
diff --git a/mod/assignment/db/access.php b/mod/assignment/db/access.php
index ab37c0b0c1c..2794a0310d1 100644
--- a/mod/assignment/db/access.php
+++ b/mod/assignment/db/access.php
@@ -39,7 +39,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -60,7 +60,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -71,7 +71,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
'student' => CAP_ALLOW,
)
),
diff --git a/mod/assignment/lib.php b/mod/assignment/lib.php
index bb0bf4c3495..6565dee88c7 100644
--- a/mod/assignment/lib.php
+++ b/mod/assignment/lib.php
@@ -363,7 +363,7 @@ class assignment_base {
get_string('noattempts', 'assignment').' ';
}
} else {
- if (!empty($USER->id)) {
+ if (isloggedin()) {
if ($submission = $this->get_submission($USER->id)) {
if ($submission->timemodified) {
if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
@@ -2283,7 +2283,7 @@ function assignment_cron () {
/// mail is customised for the receiver.
cron_setup_user($user, $course);
- if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
+ if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
continue;
}
@@ -3361,28 +3361,25 @@ function assignment_extend_settings_navigation(settings_navigation $settings, na
$assignmentclass = 'assignment_'.$assignmentrow->assignmenttype;
$assignmentinstance = new $assignmentclass($PAGE->cm->id, $assignmentrow, $PAGE->cm, $PAGE->course);
- if (!empty($USER->id) && !has_capability('moodle/legacy:guest', $PAGE->cm->context, NULL, false)) {
+ $allgroups = false;
- $allgroups = false;
+ // Add assignment submission information
+ if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
+ if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
+ $group = 0;
+ } else {
+ $group = groups_get_activity_group($PAGE->cm);
+ }
+ $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
+ if ($count = $assignmentinstance->count_real_submissions($group)) {
+ $string = get_string('viewsubmissions', 'assignment', $count);
+ } else {
+ $string = get_string('noattempts', 'assignment');
+ }
+ $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
+ }
- // Add assignment submission information
- if (has_capability('mod/assignment:grade', $PAGE->cm->context)) {
- if ($allgroups && has_capability('moodle/site:accessallgroups', $PAGE->cm->context)) {
- $group = 0;
- } else {
- $group = groups_get_activity_group($PAGE->cm);
- }
- $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$PAGE->cm->id));
- if ($count = $assignmentinstance->count_real_submissions($group)) {
- $string = get_string('viewsubmissions', 'assignment', $count);
- } else {
- $string = get_string('noattempts', 'assignment');
- }
- $assignmentnode->add($string, $link, navigation_node::TYPE_SETTING);
- }
-
- if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
- $assignmentinstance->extend_settings_navigation($assignmentnode);
- }
- }
- }
+ if (is_object($assignmentinstance) && method_exists($assignmentinstance, 'extend_settings_navigation')) {
+ $assignmentinstance->extend_settings_navigation($assignmentnode);
+ }
+}
diff --git a/mod/assignment/type/upload/assignment.class.php b/mod/assignment/type/upload/assignment.class.php
index c2046d82035..f06d99d433c 100644
--- a/mod/assignment/type/upload/assignment.class.php
+++ b/mod/assignment/type/upload/assignment.class.php
@@ -1072,7 +1072,7 @@ class assignment_upload extends assignment_base {
// get users submission if there is one
$submission = $this->get_submission();
- if (has_capability('mod/assignment:submit', $this->cm->context)) {
+ if (has_capability('mod/assignment:submit', get_context_instance(COURSE_MODULE, $this->cm->id))) {
$editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
} else {
$editable = false;
diff --git a/mod/assignment/type/uploadsingle/assignment.class.php b/mod/assignment/type/uploadsingle/assignment.class.php
index 2713b0670af..9401c80631a 100644
--- a/mod/assignment/type/uploadsingle/assignment.class.php
+++ b/mod/assignment/type/uploadsingle/assignment.class.php
@@ -192,7 +192,7 @@ class assignment_uploadsingle extends assignment_base {
// get users submission if there is one
$submission = $this->get_submission();
- if (has_capability('mod/assignment:submit', $this->cm->context)) {
+ if (has_capability('mod/assignment:submit', get_context_instance(CONTEXT_MODULE, $this->cm->id))) {
$editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
} else {
$editable = false;
diff --git a/mod/chat/chat_ajax.php b/mod/chat/chat_ajax.php
index 514156dfa8a..36231394daa 100644
--- a/mod/chat/chat_ajax.php
+++ b/mod/chat/chat_ajax.php
@@ -38,7 +38,7 @@ if (!$course = $DB->get_record('course', array('id'=>$chat->course))) {
if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
chat_print_error('ERROR', get_string('notlogged','chat'));
}
diff --git a/mod/chat/db/access.php b/mod/chat/db/access.php
index 935589877f9..fd610872166 100644
--- a/mod/chat/db/access.php
+++ b/mod/chat/db/access.php
@@ -40,7 +40,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -52,7 +52,7 @@ $capabilities = array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -63,7 +63,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -76,7 +76,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
// not student - nervous about allowing this by default
),
@@ -91,7 +91,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW,
+ 'manager' => CAP_ALLOW,
),
),
diff --git a/mod/chat/gui_header_js/insert.php b/mod/chat/gui_header_js/insert.php
index 3958aa6a413..93f93c16e58 100644
--- a/mod/chat/gui_header_js/insert.php
+++ b/mod/chat/gui_header_js/insert.php
@@ -24,9 +24,9 @@ if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
print_error('invalidcoursemodule');
}
-require_login($course->id, false, $cm);
+require_login($course, false, $cm);
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
print_error('noguests');
}
diff --git a/mod/chat/gui_sockets/index.php b/mod/chat/gui_sockets/index.php
index 19314b4be2f..b6c014af9ff 100644
--- a/mod/chat/gui_sockets/index.php
+++ b/mod/chat/gui_sockets/index.php
@@ -24,9 +24,9 @@ if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
print_error('invalidcoursemodule');
}
-require_login($course->id, false, $cm);
+require_login($course, false, $cm);
-if (has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) {
+if (isguestuser()) {
print_error('noguests', 'chat');
}
diff --git a/mod/chat/lib.php b/mod/chat/lib.php
index 01c777f0679..af577fa3e60 100644
--- a/mod/chat/lib.php
+++ b/mod/chat/lib.php
@@ -1233,8 +1233,8 @@ function chat_extend_navigation($navigation, $course, $module, $cm) {
global $CFG, $USER, $PAGE, $OUTPUT;
$currentgroup = groups_get_activity_group($cm, true);
-
- if (has_capability('mod/chat:chat',$cm->context)) {
+
+ if (has_capability('mod/chat:chat', get_context_instance(CONTEXT_MODULE, $cm->context))) {
$strenterchat = get_string('enterchat', 'chat');
$target = $CFG->wwwroot.'/mod/chat/';
diff --git a/mod/choice/db/access.php b/mod/choice/db/access.php
index 2e7cc0e71d9..bd752b0b1d7 100644
--- a/mod/choice/db/access.php
+++ b/mod/choice/db/access.php
@@ -37,8 +37,7 @@ $capabilities = array(
'legacy' => array(
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
- 'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'editingteacher' => CAP_ALLOW
)
),
@@ -49,7 +48,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -60,7 +59,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
),
@@ -71,7 +70,7 @@ $capabilities = array(
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
- 'admin' => CAP_ALLOW
+ 'manager' => CAP_ALLOW
)
)
);
diff --git a/mod/choice/lib.php b/mod/choice/lib.php
index d0ce3a1b636..509e612755a 100644
--- a/mod/choice/lib.php
+++ b/mod/choice/lib.php
@@ -289,7 +289,7 @@ function choice_show_form($choice, $user, $cm, $allresponses) {
echo '
';
echo "
id\" />";
echo "
";
- if (has_capability('mod/choice:choose', $context, $user->id, false)) { //don't show save button if the logged in user is the guest user.
+ if (is_enrolled($context, NULL, 'mod/choice:choose')) { //only enrolled users are allowed to make a choice
if ($choicefull) {
print_string('choicefull', 'choice');
echo "";
@@ -346,7 +346,7 @@ WHERE
if ($answers) {
foreach ($answers as $a) { //only return enrolled users.
- if (has_capability('mod/choice:choose', $context, $a->userid, false)) {
+ if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
$countanswers++;
}
}
@@ -865,7 +865,7 @@ function choice_get_response_data($choice, $cm, $groupmode) {
/// First get all the users who have access here
/// To start with we assume they are all "unanswered" then move them later
- $allresponses[0] = get_users_by_capability($context, 'mod/choice:choose', 'u.id, u.picture, u.firstname, u.lastname, u.idnumber', 'u.lastname ASC,u.firstname ASC', '', '', $currentgroup, '', false, true);
+ $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup, 'u.id, u.picture, u.imagealt, u.firstname, u.lastname, u.idnumber', 'u.lastname ASC,u.firstname ASC');
/// Get all the recorded responses for this choice
$rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
diff --git a/mod/choice/view.php b/mod/choice/view.php
index ada1569c88b..ef0dddac1d9 100644
--- a/mod/choice/view.php
+++ b/mod/choice/view.php
@@ -35,7 +35,7 @@
print_error('badcontext');
}
- if ($action == 'delchoice' and confirm_sesskey() and has_capability('mod/choice:choose', $context) and $choice->allowupdate) {
+ if ($action == 'delchoice' and confirm_sesskey() and is_enrolled($context, NULL, 'mod/choice:choose') and $choice->allowupdate) {
if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id))) {
//print_object($answer);
$DB->delete_records('choice_answers', array('id' => $answer->id));
@@ -46,7 +46,7 @@
echo $OUTPUT->header();
/// Submit any new data if there is any
- if ($form = data_submitted() && has_capability('mod/choice:choose', $context) && confirm_sesskey()) {
+ if ($form = data_submitted() && is_enrolled($context, NULL, 'mod/choice:choose') && confirm_sesskey()) {
$timenow = time();
if (has_capability('mod/choice:deleteresponses', $context)) {
if ($action == 'delete') { //some responses need to be deleted
@@ -90,7 +90,7 @@
$current = false; // Initialise for later
//if user has already made a selection, and they are not allowed to update it, show their selected answer.
- if (!empty($USER->id) && ($current = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id))) &&
+ if (isloggedin() && ($current = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id))) &&
empty($choice->allowupdate) ) {
echo $OUTPUT->box(get_string("yourselection", "choice", userdate($choice->timeopen)).": ".format_string(choice_get_option_text($choice, $current->optionid)));
}
@@ -109,8 +109,7 @@
}
}
- if ( (!$current or $choice->allowupdate) and $choiceopen and
- has_capability('mod/choice:choose', $context) ) {
+ if ( (!$current or $choice->allowupdate) and $choiceopen and is_enrolled($context, NULL, 'mod/choice:choose')) {
// They haven't made their choice yet or updates allowed and choice is open
echo '