MDL-21655 big scary enrolment and roles improvements - see tacker for list of changes, includes other minor fixes too

This commit is contained in:
Petr Skoda 2010-03-31 07:41:31 +00:00
parent d1d4813ff2
commit 4f0c2d0009
225 changed files with 2942 additions and 3098 deletions

View File

@ -280,14 +280,14 @@
} }
$rs->close(); $rs->close();
/// Execute the same query again, looking for remaining records and deleting them /// Execute the same query again, looking for remaining records and deleting them
/// if the user hasn't moodle/course:view in the CONTEXT_COURSE context (orphan records) /// if the user hasn't moodle/course:participate in the CONTEXT_COURSE context (orphan records)
$rs = $DB->get_recordset_sql ("SELECT id, userid, courseid $rs = $DB->get_recordset_sql ("SELECT id, userid, courseid
FROM {user_lastaccess} FROM {user_lastaccess}
WHERE courseid != ".SITEID." WHERE courseid != ".SITEID."
AND timeaccess < ?", array($cuttime)); AND timeaccess < ?", array($cuttime));
foreach ($rs as $assign) { foreach ($rs as $assign) {
if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) { if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
if (!has_capability('moodle/course:view', $context, $assign->userid)) { if (!is_enrolled($context, $assign->userid) and !is_viewing($context, $assign->userid)) {
$DB->delete_records('user_lastaccess', array('userid'=>$assign->userid, 'courseid'=>$assign->courseid)); $DB->delete_records('user_lastaccess', array('userid'=>$assign->userid, 'courseid'=>$assign->courseid));
mtrace("Deleted orphan user_lastaccess for user $assign->userid from course $assign->courseid"); mtrace("Deleted orphan user_lastaccess for user $assign->userid from course $assign->courseid");
} }

View File

@ -1187,7 +1187,8 @@ class generator_cli extends generator {
} }
complete_user_login($user); complete_user_login($user);
$systemcontext = get_context_instance(CONTEXT_SYSTEM); $systemcontext = get_context_instance(CONTEXT_SYSTEM);
if (!has_capability('moodle/site:doanything', $systemcontext)) {
if (!is_siteadmin($user->id)) {//TODO: add some proper access control check here!!
echo "You do not have administration privileges on this Moodle site. " echo "You do not have administration privileges on this Moodle site. "
."These are required for running the generation script.{$this->eolchar}"; ."These are required for running the generation script.{$this->eolchar}";
die(); die();

View File

@ -122,11 +122,11 @@
FROM {role_capabilities} rc, FROM {role_capabilities} rc,
{role_assignments} ra, {role_assignments} ra,
{user} u {user} u
WHERE (rc.capability = ? or rc.capability = ?) WHERE (rc.capability = ?)
AND rc.roleid = ra.roleid AND rc.roleid = ra.roleid
AND u.id = ra.userid"; AND u.id = ra.userid";
$count = $DB->count_records_sql($sql, array('moodle/course:update', 'moodle/site:doanything')); $count = $DB->count_records_sql($sql, array('moodle/course:update'));
echo get_string("teachers").": ".$count; echo get_string("teachers").": ".$count;
echo "<input type=\"hidden\" name=\"courseupdaters\" value=\"$count\" />\n"; echo "<input type=\"hidden\" name=\"courseupdaters\" value=\"$count\" />\n";
echo '<br />'; echo '<br />';

View File

@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',

View File

@ -29,7 +29,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM, 'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:config', 'clonepermissionsfrom' => 'moodle/site:config',

View File

@ -30,7 +30,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM, 'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
) )
); );

View File

@ -576,16 +576,6 @@ function report_security_check_defaultuserrole($detailed=false) {
return $result; return $result;
} }
// first test if do anything enabled - that would be really crazy!
$params = array('doanything'=>'moodle/site:doanything', 'capallow'=>CAP_ALLOW, 'roleid'=>$default_role->id);
$sql = "SELECT COUNT(DISTINCT rc.contextid)
FROM {role_capabilities} rc
WHERE rc.capability = :doanything
AND rc.permission = :capallow
AND rc.roleid = :roleid";
$anythingcount = $DB->count_records_sql($sql, $params);
// risky caps - usually very dangerous // risky caps - usually very dangerous
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$default_role->id); $params = array('capallow'=>CAP_ALLOW, 'roleid'=>$default_role->id);
$sql = "SELECT COUNT(DISTINCT rc.contextid) $sql = "SELECT COUNT(DISTINCT rc.contextid)
@ -598,24 +588,16 @@ function report_security_check_defaultuserrole($detailed=false) {
$riskycount = $DB->count_records_sql($sql, $params); $riskycount = $DB->count_records_sql($sql, $params);
// default role can not have view cap in all courses - this would break moodle badly // default role can not have view cap in all courses - this would break moodle badly
$viewcap = $DB->record_exists('role_capabilities', array('roleid'=>$default_role->id, 'permission'=>CAP_ALLOW, 'capability'=>'moodle/course:view')); $viewcap = $DB->record_exists('role_capabilities', array('roleid'=>$default_role->id, 'permission'=>CAP_ALLOW, 'capability'=>'moodle/course:participate'));
// it may have either no or 'user' legacy type - nothing else, or else it would break during upgrades badly // it may have either none or 'user' archetype - nothing else, or else it would break during upgrades badly
$legacyok = false; if ($default_role->archetype === '' or $default_role->archetype === 'user') {
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$default_role->id, 'legacy'=>'moodle/legacy:%');
$sql = "SELECT rc.capability, 1
FROM {role_capabilities} rc
WHERE rc.capability LIKE :legacy
AND rc.permission = :capallow
AND rc.roleid = :roleid";
$legacycaps = $DB->get_records_sql($sql, $params);
if (!$legacycaps) {
$legacyok = true;
} else if (count($legacycaps) == 1 and isset($legacycaps['moodle/legacy:user'])) {
$legacyok = true; $legacyok = true;
} else {
$legacyok = false;
} }
if ($anythingcount or $riskycount or $viewcap or !$legacyok) { if ($riskycount or $viewcap or !$legacyok) {
$result->status = REPORT_SECURITY_CRITICAL; $result->status = REPORT_SECURITY_CRITICAL;
$result->info = get_string('check_defaultuserrole_error', 'report_security', format_string($default_role->name)); $result->info = get_string('check_defaultuserrole_error', 'report_security', format_string($default_role->name));
@ -655,16 +637,6 @@ function report_security_check_guestrole($detailed=false) {
return $result; return $result;
} }
// first test if do anything enabled - that would be really crazy!
$params = array('doanything'=>'moodle/site:doanything', 'capallow'=>CAP_ALLOW, 'roleid'=>$guest_role->id);
$sql = "SELECT COUNT(DISTINCT rc.contextid)
FROM {role_capabilities} rc
WHERE rc.capability = :doanything
AND rc.permission = :capallow
AND rc.roleid = :roleid";
$anythingcount = $DB->count_records_sql($sql, $params);
// risky caps - usually very dangerous // risky caps - usually very dangerous
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$guest_role->id); $params = array('capallow'=>CAP_ALLOW, 'roleid'=>$guest_role->id);
$sql = "SELECT COUNT(DISTINCT rc.contextid) $sql = "SELECT COUNT(DISTINCT rc.contextid)
@ -676,22 +648,14 @@ function report_security_check_guestrole($detailed=false) {
$riskycount = $DB->count_records_sql($sql, $params); $riskycount = $DB->count_records_sql($sql, $params);
// it may have either no or 'guest' legacy type - nothing else, or else it would break during upgrades badly // it may have either no or 'guest' archetype - nothing else, or else it would break during upgrades badly
$legacyok = false; if ($guest_role->archetype === '' or $guest_role->archetype === 'guest') {
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$guest_role->id, 'legacy'=>'moodle/legacy:%');
$sql = "SELECT rc.capability, 1
FROM {role_capabilities} rc
WHERE rc.capability LIKE :legacy
AND rc.permission = :capallow
AND rc.roleid = :roleid";
$legacycaps = $DB->get_records_sql($sql, $params);
if (!$legacycaps) {
$legacyok = true;
} else if (count($legacycaps) == 1 and isset($legacycaps['moodle/legacy:guest'])) {
$legacyok = true; $legacyok = true;
} else {
$legacyok = false;
} }
if ($anythingcount or $riskycount or !$legacyok) { if ($riskycount or !$legacyok) {
$result->status = REPORT_SECURITY_CRITICAL; $result->status = REPORT_SECURITY_CRITICAL;
$result->info = get_string('check_guestrole_error', 'report_security', format_string($guest_role->name)); $result->info = get_string('check_guestrole_error', 'report_security', format_string($guest_role->name));
@ -731,16 +695,6 @@ function report_security_check_frontpagerole($detailed=false) {
return $result; return $result;
} }
// first test if do anything enabled - that would be really crazy!
$params = array('doanything'=>'moodle/site:doanything', 'capallow'=>CAP_ALLOW, 'roleid'=>$frontpage_role->id);
$sql = "SELECT COUNT(DISTINCT rc.contextid)
FROM {role_capabilities} rc
WHERE rc.capability = :doanything
AND rc.permission = :capallow
AND rc.roleid = :roleid";
$anythingcount = $DB->count_records_sql($sql, $params);
// risky caps - usually very dangerous // risky caps - usually very dangerous
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$frontpage_role->id); $params = array('capallow'=>CAP_ALLOW, 'roleid'=>$frontpage_role->id);
$sql = "SELECT COUNT(DISTINCT rc.contextid) $sql = "SELECT COUNT(DISTINCT rc.contextid)
@ -753,19 +707,14 @@ function report_security_check_frontpagerole($detailed=false) {
$riskycount = $DB->count_records_sql($sql, $params); $riskycount = $DB->count_records_sql($sql, $params);
// there is no legacy role type for frontpage yet - anyway we can not allow teachers or admins there! // there is no legacy role type for frontpage yet - anyway we can not allow teachers or admins there!
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$frontpage_role->id, 'legacy'=>'moodle/legacy:%'); if ($frontpage_role->archetype === 'teacher' or $frontpage_role->archetype === 'editingteacher'
$sql = "SELECT rc.capability, 1 or $frontpage_role->archetype === 'coursecreator' or $frontpage_role->archetype === 'manager') {
FROM {role_capabilities} rc $legacyok = false;
WHERE rc.capability LIKE :legacy } else {
AND rc.permission = :capallow $legacyok = true;
AND rc.roleid = :roleid"; }
$legacycaps = $DB->get_records_sql($sql, $params);
$legacyok = (!isset($legacycaps['moodle/legacy:teacher'])
and !isset($legacycaps['moodle/legacy:editingteacher'])
and !isset($legacycaps['moodle/legacy:coursecreator'])
and !isset($legacycaps['moodle/legacy:admin']));
if ($anythingcount or $riskycount or !$legacyok) { if ($riskycount or !$legacyok) {
$result->status = REPORT_SECURITY_CRITICAL; $result->status = REPORT_SECURITY_CRITICAL;
$result->info = get_string('check_frontpagerole_error', 'report_security', format_string($frontpage_role->name)); $result->info = get_string('check_frontpagerole_error', 'report_security', format_string($frontpage_role->name));
@ -811,25 +760,6 @@ function report_security_check_defaultcourserole($detailed=false) {
return $result; return $result;
} }
// first test if do anything enabled - that would be really crazy!
$params = array('doanything'=>'moodle/site:doanything', 'capallow'=>CAP_ALLOW, 'roleid'=>$student_role->id);
$sql = "SELECT DISTINCT rc.contextid
FROM {role_capabilities} rc
WHERE rc.capability = :doanything
AND rc.permission = :capallow
AND rc.roleid = :roleid";
if ($anything_contexts = $DB->get_records_sql($sql, $params)) {
foreach($anything_contexts as $contextid) {
if ($contextid == SYSCONTEXTID) {
$a = "$CFG->wwwroot/$CFG->admin/roles/define.php?action=view&amp;roleid=$CFG->defaultcourseroleid";
} else {
$a = "$CFG->wwwroot/$CFG->admin/roles/override.php?contextid=$contextid&amp;roleid=$CFG->defaultcourseroleid";
}
$problems[] = get_string('check_defaultcourserole_anything', 'report_security', $a);
}
}
// risky caps - usually very dangerous // risky caps - usually very dangerous
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$student_role->id); $params = array('capallow'=>CAP_ALLOW, 'roleid'=>$student_role->id);
$sql = "SELECT DISTINCT rc.contextid $sql = "SELECT DISTINCT rc.contextid
@ -851,14 +781,7 @@ function report_security_check_defaultcourserole($detailed=false) {
} }
// course creator or administrator does not make any sense here // course creator or administrator does not make any sense here
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$student_role->id, 'legacy'=>'moodle/legacy:%'); if ($student_role->archetype === 'coursecreator' or $student_role->archetype === 'manager') {
$sql = "SELECT rc.capability, 1
FROM {role_capabilities} rc
WHERE rc.capability LIKE :legacy
AND rc.permission = :capallow
AND rc.roleid = :roleid";
$legacycaps = $DB->get_records_sql($sql, $params);
if (isset($legacycaps['moodle/legacy:coursecreator']) or isset($legacycaps['moodle/legacy:admin'])) {
$problems[] = get_string('check_defaultcourserole_legacy', 'report_security'); $problems[] = get_string('check_defaultcourserole_legacy', 'report_security');
} }
@ -922,43 +845,16 @@ function report_security_check_courserole($detailed=false) {
$sql = "SELECT DISTINCT rc.roleid $sql = "SELECT DISTINCT rc.roleid
FROM {role_capabilities} rc FROM {role_capabilities} rc
WHERE (rc.capability = :coursecreator OR rc.capability = :admin OR rc.capability = :teacher OR rc.capability = :editingteacher) JOIN {role} r ON r.id = rc.roleid
AND rc.permission = ".CAP_ALLOW.""; WHERE (r.archetype = :coursecreator OR r.archetype = :teacher OR r.archetype = :editingteacher OR r.archetype = :manager)";
$params = array('coursecreator' => 'moodle/legacy:coursecreator', $params = array('coursecreator' => 'coursecreator',
'admin' => 'moodle/legacy:admin', 'teacher' => 'teacher',
'teacher' => 'moodle/legacy:teacher', 'editingteacher' => 'editingteacher',
'editingteacher' => 'moodle/legacy:editingteacher'); 'manager' => 'manager');
$riskyroleids = $DB->get_records_sql($sql, $params); $riskyroleids = $DB->get_records_sql($sql, $params);
$riskyroleids = array_keys($riskyroleids); $riskyroleids = array_keys($riskyroleids);
// first test if do anything enabled - that would be really crazy!!!!!!
list($inroles, $params) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'r0', true);
$params = array_merge($params, array('doanything'=>'moodle/site:doanything', 'capallow'=>CAP_ALLOW));
$params['doanything'] = 'moodle/site:doanything';
$params['capallow'] = CAP_ALLOW;
$sql = "SELECT rc.roleid, rc.contextid
FROM {role_capabilities} rc
WHERE rc.capability = :doanything
AND rc.permission = :capallow
AND rc.roleid $inroles
GROUP BY rc.roleid, rc.contextid
ORDER BY rc.roleid, rc.contextid";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $res) {
$roleid = $res->roleid;
$contextid = $res->contextid;
if ($contextid == SYSCONTEXTID) {
$a = "$CFG->wwwroot/$CFG->admin/roles/define.php?action=view&amp;roleid=$roleid";
} else {
$a = "$CFG->wwwroot/$CFG->admin/roles/override.php?contextid=$contextid&amp;roleid=$roleid";
}
$problems[] = get_string('check_courserole_anything', 'report_security', $a);
}
$rs->close();
// any XSS legacy cap does not make any sense here! // any XSS legacy cap does not make any sense here!
list($inroles, $params) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'r0', true); list($inroles, $params) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'r0', true);
$sql = "SELECT DISTINCT c.id, c.shortname $sql = "SELECT DISTINCT c.id, c.shortname
@ -1034,37 +930,13 @@ function report_security_check_riskadmin($detailed=false) {
$result->status = null; $result->status = null;
$result->link = null; $result->link = null;
$params = array('doanything'=>'moodle/site:doanything', 'syscontextid'=>SYSCONTEXTID, 'capallow'=>CAP_ALLOW); $sql = "SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email
FROM {user} u
WHERE u.id IN ($CFG->siteadmins)";
$sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email $admins = $DB->get_records_sql($sql);
FROM {role_capabilities} rc
JOIN {role_assignments} ra ON (ra.contextid = rc.contextid AND ra.roleid = rc.roleid)
JOIN {user} u ON u.id = ra.userid
WHERE rc.capability = :doanything
AND rc.permission = :capallow
AND u.deleted = 0
AND rc.contextid = :syscontextid";
$admins = $DB->get_records_sql($sql, $params);
$admincount = count($admins); $admincount = count($admins);
$sqlunsup = "SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, ra.contextid, ra.roleid
FROM (SELECT rcx.*
FROM {role_capabilities} rcx
WHERE rcx.capability = :doanything AND rcx.permission = :capallow) rc,
{context} c,
{context} sc,
{role_assignments} ra,
{user} u
WHERE c.id = rc.contextid
AND (sc.path = c.path OR sc.path LIKE ".$DB->sql_concat('c.path', "'/%'")." OR c.path LIKE ".$DB->sql_concat('sc.path', "'/%'").")
AND u.id = ra.userid AND u.deleted = 0
AND ra.contextid = sc.id AND ra.roleid = rc.roleid AND ra.contextid <> :syscontextid
GROUP BY u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, ra.contextid, ra.roleid
ORDER BY u.lastname, u.firstname";
$unsupcount = $DB->count_records_sql("SELECT COUNT('x') FROM ($sqlunsup) unsup", $params);
if ($detailed) { if ($detailed) {
foreach ($admins as $uid=>$user) { foreach ($admins as $uid=>$user) {
$url = "$CFG->wwwroot/user/view.php?id=$user->id"; $url = "$CFG->wwwroot/user/view.php?id=$user->id";
@ -1073,32 +945,11 @@ function report_security_check_riskadmin($detailed=false) {
$admins = '<ul>'.implode($admins).'</ul>'; $admins = '<ul>'.implode($admins).'</ul>';
} }
if (!$unsupcount) { $result->status = REPORT_SECURITY_OK;
$result->status = REPORT_SECURITY_OK; $result->info = get_string('check_riskadmin_ok', 'report_security', $admincount);
$result->info = get_string('check_riskadmin_ok', 'report_security', $admincount);
if ($detailed) { if ($detailed) {
$result->details = get_string('check_riskadmin_detailsok', 'report_security', $admins); $result->details = get_string('check_riskadmin_detailsok', 'report_security', $admins);
}
} else {
$result->status = REPORT_SECURITY_WARNING;
$a = (object)array('admincount'=>$admincount, 'unsupcount'=>$unsupcount);
$result->info = get_string('check_riskadmin_warning', 'report_security', $a);
if ($detailed) {
$rs = $DB->get_recordset_sql($sqlunsup, $params);
$users = array();
foreach ($rs as $user) {
$url = "$CFG->wwwroot/$CFG->admin/roles/assign.php?contextid=$user->contextid&amp;roleid=$user->roleid";
$a = (object)array('fullname'=>fullname($user), 'url'=>$url, 'email'=>$user->email);
$users[] = '<li>'.get_string('check_riskadmin_unassign', 'report_security', $a).'</li>';
}
$rs->close();
$users = '<ul>'.implode($users).'</ul>';
$a = (object)array('admins'=>$admins, 'unsupported'=>$users);
$result->details = get_string('check_riskadmin_detailswarning', 'report_security', $a);
}
} }
return $result; return $result;

View File

@ -30,7 +30,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM, 'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:config', 'clonepermissionsfrom' => 'moodle/site:config',

137
admin/roles/admins.php Normal file
View File

@ -0,0 +1,137 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Lets you site administrators
*
* @package moodlecore
* @subpackage role
* @copyright 2010 Petr Skoda (skodak) http://skodak.org
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(__FILE__) . '/../../config.php');
require_once($CFG->dirroot . '/' . $CFG->admin . '/roles/lib.php');
$confirmadd = optional_param('confirmadd', 0, PARAM_INT);
$confirmdel = optional_param('confirmdel', 0, PARAM_INT);
$PAGE->set_url('/admin/roles/admins.php');
admin_externalpage_setup('admins');
if (!is_siteadmin()) {
die;
}
$admisselector = new admins_existing_selector();
$admisselector->set_extra_fields(array('username', 'email'));
$potentialadmisselector = new admins_potential_selector();
$potentialadmisselector->set_extra_fields(array('username', 'email'));
if (optional_param('add', false, PARAM_BOOL) and confirm_sesskey()) {
if ($userstoadd = $potentialadmisselector->get_selected_users()) {
$user = reset($userstoadd);
$username = fullname($user) . " ($user->username, $user->email)";
echo $OUTPUT->header();
echo $OUTPUT->confirm(get_string('confirmaddadmin', 'role', $username), new moodle_url('/admin/roles/admins.php', array('confirmadd'=>$user->id, 'sesskey'=>sesskey())), $PAGE->url);
echo $OUTPUT->footer();
die;
}
} else if (optional_param('remove', false, PARAM_BOOL) and confirm_sesskey()) {
if ($userstoremove = $admisselector->get_selected_users()) {
$user = reset($userstoremove);
if ($USER->id == $user->id) {
//can not remove self
} else {
$username = fullname($user) . " ($user->username, $user->email)";
echo $OUTPUT->header();
echo $OUTPUT->confirm(get_string('confirmdeladmin', 'role', $username), new moodle_url('/admin/roles/admins.php', array('confirmdel'=>$user->id, 'sesskey'=>sesskey())), $PAGE->url);
echo $OUTPUT->footer();
die;
}
}
} else if ($confirmadd and confirm_sesskey()) {
$admins = array();
foreach(explode(',', $CFG->siteadmins) as $admin) {
$admin = (int)$admin;
if ($admin) {
$admins[$admin] = $admin;
}
}
$admins[$confirmadd] = $confirmadd;
set_config('siteadmins', implode(',', $admins));
redirect($PAGE->url);
} else if ($confirmdel and confirm_sesskey() and $confirmdel != $USER->id) {
$admins = array();
foreach(explode(',', $CFG->siteadmins) as $admin) {
$admin = (int)$admin;
if ($admin) {
$admins[$admin] = $admin;
}
}
unset($admins[$confirmdel]);
set_config('siteadmins', implode(',', $admins));
redirect($PAGE->url);
}
/// Print header
echo $OUTPUT->header();
?>
<div id="addadmisform">
<h3 class="main"><?php print_string('manageadmins', 'role'); ?></h3>
<form id="assignform" method="post" action="<?php echo $PAGE->url ?>">
<div>
<input type="hidden" name="sesskey" value="<?php p(sesskey()); ?>" />
<table class="generaltable generalbox groupmanagementtable boxaligncenter" summary="">
<tr>
<td id='existingcell'>
<p>
<label for="removeselect"><?php print_string('existingadmins', 'role'); ?></label>
</p>
<?php $admisselector->display(); ?>
</td>
<td id='buttonscell'>
<p class="arrow_button">
<input name="add" id="add" type="submit" value="<?php echo $OUTPUT->larrow().'&nbsp;'.get_string('add'); ?>" title="<?php print_string('add'); ?>" /><br />
<input name="remove" id="remove" type="submit" value="<?php echo get_string('remove').'&nbsp;'.$OUTPUT->rarrow(); ?>" title="<?php print_string('remove'); ?>" />
</p>
</td>
<td id='potentialcell'>
<p>
<label for="addselect"><?php print_string('users'); ?></label>
</p>
<?php $potentialadmisselector->display(); ?>
</td>
</tr>
</table>
</div>
</form>
</div>
<?php
//this must be after calling display() on the selectors so their setup JS executes first
//////$PAGE->requires->js_function_call('init_add_remove_admis_page');
echo $OUTPUT->footer();

View File

@ -33,7 +33,6 @@
$roleid = optional_param('roleid', 0, PARAM_INT); $roleid = optional_param('roleid', 0, PARAM_INT);
$userid = optional_param('userid', 0, PARAM_INT); // needed for user tabs $userid = optional_param('userid', 0, PARAM_INT); // needed for user tabs
$courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs $courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs
$hidden = optional_param('hidden', 0, PARAM_BOOL); // whether this assignment is hidden
$extendperiod = optional_param('extendperiod', 0, PARAM_INT); $extendperiod = optional_param('extendperiod', 0, PARAM_INT);
$extendbase = optional_param('extendbase', 3, PARAM_INT); $extendbase = optional_param('extendbase', 3, PARAM_INT);
@ -148,11 +147,7 @@
$options = array('context' => $context, 'roleid' => $roleid); $options = array('context' => $context, 'roleid' => $roleid);
$potentialuserselector = roles_get_potential_user_selector($context, 'addselect', $options); $potentialuserselector = roles_get_potential_user_selector($context, 'addselect', $options);
if ($context->contextlevel == CONTEXT_SYSTEM && is_admin_role($roleid)) { $currentuserselector = new existing_role_holders('removeselect', $options);
$currentuserselector = new existing_role_holders_site_admin('removeselect', $options);
} else {
$currentuserselector = new existing_role_holders('removeselect', $options);
}
/// Process incoming role assignments /// Process incoming role assignments
$errors = array(); $errors = array();
@ -196,7 +191,7 @@
} else { } else {
$timeend = 0; $timeend = 0;
} }
if (! role_assign($roleid, $adduser->id, 0, $context->id, $timestart, $timeend, $hidden)) { if (! role_assign($roleid, $adduser->id, 0, $context->id, $timestart, $timeend)) {
$a = new stdClass; $a = new stdClass;
$a->role = $assignableroles[$roleid]; $a->role = $assignableroles[$roleid];
$a->user = fullname($adduser); $a->user = fullname($adduser);
@ -314,12 +309,6 @@
<?php print_collapsible_region_start('', 'assignoptions', get_string('enrolmentoptions', 'role'), <?php print_collapsible_region_start('', 'assignoptions', get_string('enrolmentoptions', 'role'),
'assignoptionscollapse', true); ?> 'assignoptionscollapse', true); ?>
<p><input type="checkbox" name="hidden" id="hidden" value="1" <?php
if ($hidden) { echo 'checked="checked" '; } ?>/>
<label for="hidden" title="<?php print_string('createhiddenassign', 'role'); ?>">
<?php print_string('hidden', 'role'); ?>
<?php echo $OUTPUT->help_icon('hiddenassign', get_string('createhiddenassign', 'role')); ?>
</label></p>
<p><label for="extendperiod"><?php print_string('enrolperiod') ?></label><br /> <p><label for="extendperiod"><?php print_string('enrolperiod') ?></label><br />
<?php echo html_writer::select($periodmenu, 'extendperiod', $defaultperiod, $unlimitedperiod); ?></p> <?php echo html_writer::select($periodmenu, 'extendperiod', $defaultperiod, $unlimitedperiod); ?></p>

View File

@ -103,7 +103,7 @@
admin_externalpage_print_header(); admin_externalpage_print_header();
$currenttab = 'manage'; $currenttab = 'manage';
include_once('managetabs.php'); include('managetabs.php');
if ($action == 'add') { if ($action == 'add') {
$title = get_string('addinganewrole', 'role'); $title = get_string('addinganewrole', 'role');
@ -131,7 +131,7 @@
$options['action'] = 'edit'; $options['action'] = 'edit';
echo $OUTPUT->single_button(new moodle_url($defineurl, $options), get_string('edit')); echo $OUTPUT->single_button(new moodle_url($defineurl, $options), get_string('edit'));
$options['action'] = 'reset'; $options['action'] = 'reset';
if ($definitiontable->get_legacy_type()) { if ($definitiontable->get_archetype()) {
echo $OUTPUT->single_button(new moodle_url($manageurl, $options), get_string('resetrole', 'role')); echo $OUTPUT->single_button(new moodle_url($manageurl, $options), get_string('resetrole', 'role'));
} else { } else {
echo $OUTPUT->single_button(new moodle_url($manageurl, $options), get_string('resetrolenolegacy', 'role')); echo $OUTPUT->single_button(new moodle_url($manageurl, $options), get_string('resetrolenolegacy', 'role'));

View File

@ -144,7 +144,7 @@ abstract class capability_table_base {
protected abstract function num_extra_columns(); protected abstract function num_extra_columns();
/** /**
* For subclasses to override. Allows certain capabilties (e.g. legacy capabilities) * For subclasses to override. Allows certain capabilties
* to be left out of the table. * to be left out of the table.
* *
* @param object $capability the capability this row relates to. * @param object $capability the capability this row relates to.
@ -213,10 +213,6 @@ class check_capability_table extends capability_table_base {
return 1; return 1;
} }
protected function skip_row($capability) {
return $capability->name != 'moodle/site:doanything' && is_legacy($capability->name);
}
protected function get_row_classes($capability) { protected function get_row_classes($capability) {
$this->hascap = has_capability($capability->name, $this->context, $this->user->id); $this->hascap = has_capability($capability->name, $this->context, $this->user->id);
if ($this->hascap) { if ($this->hascap) {
@ -285,10 +281,6 @@ class permissions_table extends capability_table_base {
return 3; return 3;
} }
protected function skip_row($capability) {
return $capability->name != 'moodle/site:doanything' && is_legacy($capability->name);
}
protected function add_row_cells($capability) { protected function add_row_cells($capability) {
global $OUTPUT, $PAGE; global $OUTPUT, $PAGE;
@ -554,7 +546,6 @@ class define_role_table_advanced extends capability_table_with_risks {
protected $errors; protected $errors;
protected $contextlevels; protected $contextlevels;
protected $allcontextlevels; protected $allcontextlevels;
protected $legacyroles;
protected $disabled = ''; protected $disabled = '';
public function __construct($context, $roleid) { public function __construct($context, $roleid) {
@ -571,8 +562,6 @@ class define_role_table_advanced extends capability_table_with_risks {
CONTEXT_MODULE => get_string('activitymodule'), CONTEXT_MODULE => get_string('activitymodule'),
CONTEXT_BLOCK => get_string('block') CONTEXT_BLOCK => get_string('block')
); );
$this->legacyroles = get_legacy_roles();
} }
protected function load_current_permissions() { protected function load_current_permissions() {
@ -581,7 +570,6 @@ class define_role_table_advanced extends capability_table_with_risks {
if (!$this->role = $DB->get_record('role', array('id' => $this->roleid))) { if (!$this->role = $DB->get_record('role', array('id' => $this->roleid))) {
throw new moodle_exception('invalidroleid'); throw new moodle_exception('invalidroleid');
} }
$this->role->legacytype = get_legacy_type($this->roleid);
$contextlevels = get_role_contextlevels($this->roleid); $contextlevels = get_role_contextlevels($this->roleid);
// Put the contextlevels in the array keys, as well as the values. // Put the contextlevels in the array keys, as well as the values.
if (!empty($contextlevels)) { if (!empty($contextlevels)) {
@ -594,7 +582,7 @@ class define_role_table_advanced extends capability_table_with_risks {
$this->role->name = ''; $this->role->name = '';
$this->role->shortname = ''; $this->role->shortname = '';
$this->role->description = ''; $this->role->description = '';
$this->role->legacytype = ''; $this->role->archetype = '';
$this->contextlevels = array(); $this->contextlevels = array();
} }
parent::load_current_permissions(); parent::load_current_permissions();
@ -638,12 +626,13 @@ class define_role_table_advanced extends capability_table_with_risks {
} }
// Legacy type. // Legacy type.
$legacytype = optional_param('legacytype', null, PARAM_RAW); $archetype = optional_param('archetype', null, PARAM_RAW);
if (!is_null($legacytype)) { if ($archetype) {
if (array_key_exists($legacytype, $this->legacyroles)) { $archetypes = get_role_archetypes();
$this->role->legacytype = $legacytype; if (isset($archetypes[$archetype])){
$this->role->archetype = $archetype;
} else { } else {
$this->role->legacytype = ''; $this->role->archetype = '';
} }
} }
@ -686,16 +675,12 @@ class define_role_table_advanced extends capability_table_with_risks {
return $this->role->id; return $this->role->id;
} }
public function get_legacy_type() { public function get_archetype() {
return $this->role->legacytype; return $this->role->archetype;
} }
protected function load_parent_permissions() { protected function load_parent_permissions() {
if ($this->role->legacytype) { $this->parentpermissions = get_default_capabilities($this->role->archetype);
$this->parentpermissions = get_default_capabilities($this->role->legacytype);
} else {
$this->parentpermissions = array();
}
} }
public function save_changes() { public function save_changes() {
@ -703,25 +688,11 @@ class define_role_table_advanced extends capability_table_with_risks {
if (!$this->roleid) { if (!$this->roleid) {
// Creating role // Creating role
if (isset($this->legacyroles[$this->role->legacytype])) { $this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $this->role->archetype);
$legacycap = $this->legacyroles[$this->role->legacytype];
} else {
$legacycap = '';
}
$this->role->id = create_role($this->role->name, $this->role->shortname, $this->role->description, $legacycap);
$this->roleid = $this->role->id; // Needed to make the parent::save_changes(); call work. $this->roleid = $this->role->id; // Needed to make the parent::save_changes(); call work.
} else { } else {
// Updating role // Updating role
$DB->update_record('role', $this->role); $DB->update_record('role', $this->role);
// Legacy type
foreach($this->legacyroles as $type => $cap) {
if ($type == $this->role->legacytype) {
assign_capability($cap, CAP_ALLOW, $this->role->id, $this->context->id);
} else {
unassign_capability($cap, $this->role->id);
}
}
} }
// Assignable contexts. // Assignable contexts.
@ -731,10 +702,6 @@ class define_role_table_advanced extends capability_table_with_risks {
parent::save_changes(); parent::save_changes();
} }
protected function skip_row($capability) {
return is_legacy($capability->name);
}
protected function get_name_field($id) { protected function get_name_field($id) {
return '<input type="text" id="' . $id . '" name="' . $id . '" maxlength="254" value="' . s($this->role->name) . '" />'; return '<input type="text" id="' . $id . '" name="' . $id . '" maxlength="254" value="' . s($this->role->name) . '" />';
} }
@ -747,14 +714,14 @@ class define_role_table_advanced extends capability_table_with_risks {
return print_textarea(true, 10, 50, 50, 10, 'description', $this->role->description, 0, true); return print_textarea(true, 10, 50, 50, 10, 'description', $this->role->description, 0, true);
} }
protected function get_legacy_type_field($id) { protected function get_archetype_field($id) {
global $OUTPUT; global $OUTPUT;
$options = array(); $options = array();
$options[''] = get_string('none'); $options[''] = get_string('none');
foreach($this->legacyroles as $type => $cap) { foreach(get_role_archetypes() as $type) {
$options[$type] = get_string('legacy:'.$type, 'role'); $options[$type] = get_string('archetype'.$type, 'role');
} }
return html_writer::select($options, 'legacytype', $this->role->legacytype, false); return html_writer::select($options, 'archetype', $this->role->archetype, false);
} }
protected function get_assignable_levels_control() { protected function get_assignable_levels_control() {
@ -814,7 +781,7 @@ class define_role_table_advanced extends capability_table_with_risks {
$this->print_field('name', get_string('name'), $this->get_name_field('name')); $this->print_field('name', get_string('name'), $this->get_name_field('name'));
$this->print_field('shortname', get_string('shortname'), $this->get_shortname_field('shortname')); $this->print_field('shortname', get_string('shortname'), $this->get_shortname_field('shortname'));
$this->print_field('edit-description', get_string('description'), $this->get_description_field('description')); $this->print_field('edit-description', get_string('description'), $this->get_description_field('description'));
$this->print_field('menulegacytype', get_string('legacytype', 'role'), $this->get_legacy_type_field('legacytype')); $this->print_field('menuarchetype', get_string('archetype', 'role'), $this->get_archetype_field('archetype'));
$this->print_field('', get_string('maybeassignedin', 'role'), $this->get_assignable_levels_control()); $this->print_field('', get_string('maybeassignedin', 'role'), $this->get_assignable_levels_control());
echo "</div>"; echo "</div>";
@ -905,11 +872,11 @@ class view_role_definition_table extends define_role_table_advanced {
return format_text($this->role->description, FORMAT_HTML); return format_text($this->role->description, FORMAT_HTML);
} }
protected function get_legacy_type_field($id) { protected function get_archetype_field($id) {
if (empty($this->role->legacytype)) { if (empty($this->role->archetype)) {
return get_string('none'); return get_string('none');
} else { } else {
return get_string('legacy:'.$this->role->legacytype, 'role'); return get_string('archetype'.$this->role->archetype, 'role');
} }
} }
@ -976,10 +943,6 @@ class override_permissions_table_advanced extends capability_table_with_risks {
return $this->haslockedcapabiltites; return $this->haslockedcapabiltites;
} }
protected function skip_row($capability) {
return is_legacy($capability->name);
}
protected function add_permission_cells($capability) { protected function add_permission_cells($capability) {
$disabled = ''; $disabled = '';
if ($capability->locked || $this->parentpermissions[$capability->name] == CAP_PROHIBIT) { if ($capability->locked || $this->parentpermissions[$capability->name] == CAP_PROHIBIT) {
@ -1058,7 +1021,7 @@ abstract class role_assign_user_selector_base extends user_selector_base {
* some CONTEXT_BLOCK). * some CONTEXT_BLOCK).
* *
* In this case we replicate part of get_users_by_capability() get the users * In this case we replicate part of get_users_by_capability() get the users
* with moodle/course:view (or moodle/site:doanything). We can't use * with moodle/course:participate. We can't use
* get_users_by_capability() becuase * get_users_by_capability() becuase
* 1) get_users_by_capability() does not deal with searching by name * 1) get_users_by_capability() does not deal with searching by name
* 2) exceptions array can be potentially large for large courses * 2) exceptions array can be potentially large for large courses
@ -1067,26 +1030,20 @@ class potential_assignees_below_course extends role_assign_user_selector_base {
public function find_users($search) { public function find_users($search) {
global $DB; global $DB;
// Get roles with some assignement to the 'moodle/course:view' capability. // Get roles with some assignement to the 'moodle/course:participate' capability.
$possibleroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $this->context); $possibleroles = get_roles_with_capability('moodle/course:participate', CAP_ALLOW, $this->context);
if (empty($possibleroles)) { if (empty($possibleroles)) {
// If there aren't any, we are done. // If there aren't any, we are done.
return array(); return array();
} }
// Now exclude the admin roles, and check the actual permission on // Now exclude the admin roles, and check the actual permission on
// 'moodle/course:view' to make sure it is allow. // 'moodle/course:participate' to make sure it is allow.
$doanythingroles = get_roles_with_capability('moodle/site:doanything',
CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM));
$validroleids = array(); $validroleids = array();
foreach ($possibleroles as $possiblerole) { foreach ($possibleroles as $possiblerole) {
if (isset($doanythingroles[$possiblerole->id])) { if ($caps = role_context_capabilities($possiblerole->id, $this->context, 'moodle/course:participate')) { // resolved list
continue; if (isset($caps['moodle/course:participate']) && $caps['moodle/course:participate'] > 0) { // resolved capability > 0
}
if ($caps = role_context_capabilities($possiblerole->id, $this->context, 'moodle/course:view')) { // resolved list
if (isset($caps['moodle/course:view']) && $caps['moodle/course:view'] > 0) { // resolved capability > 0
$validroleids[] = $possiblerole->id; $validroleids[] = $possiblerole->id;
} }
} }
@ -1116,13 +1073,13 @@ class potential_assignees_below_course extends role_assign_user_selector_base {
AND u.id NOT IN ( AND u.id NOT IN (
SELECT u.id SELECT u.id
FROM {role_assignments} r, {user} u FROM {role_assignments} r, {user} u
WHERE r.contextid = ? WHERE r.contextid = :contextid
AND u.id = r.userid AND u.id = r.userid
AND r.roleid = ?)"; AND r.roleid = :roleid)";
$order = ' ORDER BY lastname ASC, firstname ASC'; $order = ' ORDER BY lastname ASC, firstname ASC';
$params[] = $this->context->id; $params['contextid'] = $this->context->id;
$params[] = $this->roleid; $params['roleid'] = $this->roleid;
// Check to see if there are too many to show sensibly. // Check to see if there are too many to show sensibly.
if (!$this->is_validating()) { if (!$this->is_validating()) {
@ -1168,13 +1125,13 @@ class potential_assignees_course_and_above extends role_assign_user_selector_bas
AND id NOT IN ( AND id NOT IN (
SELECT u.id SELECT u.id
FROM {role_assignments} r, {user} u FROM {role_assignments} r, {user} u
WHERE r.contextid = ? WHERE r.contextid = :contextid
AND u.id = r.userid AND u.id = r.userid
AND r.roleid = ?)"; AND r.roleid = :roleid)";
$order = ' ORDER BY lastname ASC, firstname ASC'; $order = ' ORDER BY lastname ASC, firstname ASC';
$params[] = $this->context->id; $params['contextid'] = $this->context->id;
$params[] = $this->roleid; $params['roleid'] = $this->roleid;
if (!$this->is_validating()) { if (!$this->is_validating()) {
$potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params); $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
@ -1204,29 +1161,27 @@ class potential_assignees_course_and_above extends role_assign_user_selector_bas
* question on the assign roles page. * question on the assign roles page.
*/ */
class existing_role_holders extends role_assign_user_selector_base { class existing_role_holders extends role_assign_user_selector_base {
protected $strhidden;
public function __construct($name, $options) { public function __construct($name, $options) {
parent::__construct($name, $options); parent::__construct($name, $options);
$this->strhidden = get_string('hiddenassign');
} }
public function find_users($search) { public function find_users($search) {
global $DB; global $DB;
list($wherecondition, $params) = $this->search_sql($search, 'u'); list($wherecondition, $params) = $this->search_sql($search, 'u');
list($ctxcondition, $ctxparams) = $DB->get_in_or_equal(get_parent_contexts($this->context, true)); list($ctxcondition, $ctxparams) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx00');
$params = array_merge($params, $ctxparams); $params = array_merge($params, $ctxparams);
$params[] = $this->roleid; $params['roleid'] = $this->roleid;
$sql = "SELECT ra.id as raid," . $this->required_fields_sql('u') . ",ra.hidden,ra.contextid $sql = "SELECT ra.id as raid," . $this->required_fields_sql('u') . ",ra.contextid
FROM {role_assignments} ra FROM {role_assignments} ra
JOIN {user} u ON u.id = ra.userid JOIN {user} u ON u.id = ra.userid
JOIN {context} ctx ON ra.contextid = ctx.id JOIN {context} ctx ON ra.contextid = ctx.id
WHERE WHERE
$wherecondition AND $wherecondition AND
ctx.id $ctxcondition AND ctx.id $ctxcondition AND
ra.roleid = ? ra.roleid = :roleid
ORDER BY ctx.depth DESC, u.lastname, u.firstname"; ORDER BY ctx.depth DESC, u.lastname, u.firstname";
$contextusers = $DB->get_records_sql($sql, $params); $contextusers = $DB->get_records_sql($sql, $params);
@ -1314,34 +1269,6 @@ class existing_role_holders extends role_assign_user_selector_base {
return get_string('usersfrom', 'role', $contextname); return get_string('usersfrom', 'role', $contextname);
} }
} }
// Override to add (hidden) to hidden role assignments.
public function output_user($user) {
$output = parent::output_user($user);
if ($user->hidden) {
$output .= ' (' . $this->strhidden . ')';
}
return $output;
}
}
/**
* A special subclass to use when unassigning admins at site level. Disables
* the option for admins to unassign themselves.
*/
class existing_role_holders_site_admin extends existing_role_holders {
public function find_users($search) {
global $USER;
$groupedusers = parent::find_users($search);
foreach ($groupedusers as $group) {
foreach ($group as &$user) {
if ($user->id == $USER->id) {
$user->disabled = true;
}
}
}
return $groupedusers;
}
} }
/** /**
@ -1590,3 +1517,82 @@ function roles_get_potential_user_selector($context, $name, $options) {
return $potentialuserselector; return $potentialuserselector;
} }
class admins_potential_selector extends user_selector_base {
/**
* @param string $name control name
* @param array $options should have two elements with keys groupid and courseid.
*/
public function __construct() {
global $CFG, $USER;
$admins = explode(',', $CFG->siteadmins);
parent::__construct('addselect', array('multiselect'=>false, 'exclude'=>$admins));
}
public function find_users($search) {
global $DB;
list($wherecondition, $params) = $this->search_sql($search, '');
$fields = 'SELECT ' . $this->required_fields_sql('');
$countfields = 'SELECT COUNT(1)';
$sql = " FROM {user}
WHERE $wherecondition";
$order = ' ORDER BY lastname ASC, firstname ASC';
$availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
if (empty($availableusers)) {
return array();
}
if ($search) {
$groupname = get_string('potusersmatching', 'role', $search);
} else {
$groupname = get_string('potusers', 'role');
}
return array($groupname => $availableusers);
}
}
class admins_existing_selector extends user_selector_base {
/**
* @param string $name control name
* @param array $options should have two elements with keys groupid and courseid.
*/
public function __construct() {
global $CFG, $USER;
parent::__construct('removeselect', array('multiselect'=>false));
}
public function find_users($search) {
global $DB, $CFG;
list($wherecondition, $params) = $this->search_sql($search, '');
$fields = 'SELECT ' . $this->required_fields_sql('');
$countfields = 'SELECT COUNT(1)';
if ($wherecondition) {
$wherecondition = "$wherecondition AND id IN ($CFG->siteadmins)";
} else {
$wherecondition = "id IN ($CFG->siteadmins)";
}
$sql = " FROM {user}
WHERE $wherecondition";
$order = ' ORDER BY lastname ASC, firstname ASC';
$availableusers = $DB->get_records_sql($fields . $sql . $order, $params);
if (empty($availableusers)) {
return array();
}
if ($search) {
$groupname = get_string('extusersmatching', 'role', $search);
} else {
$groupname = get_string('extusers', 'role');
}
return array($groupname => $availableusers);
}
}

View File

@ -61,11 +61,6 @@
$undeletableroles[$CFG->guestroleid] = 1; $undeletableroles[$CFG->guestroleid] = 1;
$undeletableroles[$CFG->defaultuserroleid] = 1; $undeletableroles[$CFG->defaultuserroleid] = 1;
$undeletableroles[$CFG->defaultcourseroleid] = 1; $undeletableroles[$CFG->defaultcourseroleid] = 1;
// If there is only one admin role, add that to $undeletableroles too.
$adminroles = get_admin_roles();
if (count($adminroles) == 1) {
$undeletableroles[reset($adminroles)->id] = 1;
}
///.Process submitted data. ///.Process submitted data.
$confirmed = optional_param('confirm', false, PARAM_BOOL) && data_submitted() && confirm_sesskey(); $confirmed = optional_param('confirm', false, PARAM_BOOL) && data_submitted() && confirm_sesskey();
@ -160,7 +155,7 @@
$a->id = $roleid; $a->id = $roleid;
$a->name = $roles[$roleid]->name; $a->name = $roles[$roleid]->name;
$a->shortname = $roles[$roleid]->shortname; $a->shortname = $roles[$roleid]->shortname;
$a->legacytype = get_legacy_type($roleid); $a->legacytype = $roles[$roleid]->archetype;
if (empty($a->legacytype)) { if (empty($a->legacytype)) {
$warning = get_string('resetrolesurenolegacy', 'role', $a); $warning = get_string('resetrolesurenolegacy', 'role', $a);
} else { } else {
@ -168,22 +163,21 @@
} }
$formcontinue = new single_button(new moodle_url('manage.php', $optionsyes), get_string('yes')); $formcontinue = new single_button(new moodle_url('manage.php', $optionsyes), get_string('yes'));
$formcancel = new single_button(new moodle_url('manage.php', $optionsno), get_string('no'), 'get'); $formcancel = new single_button(new moodle_url('manage.php', $optionsno), get_string('no'), 'get');
echo $OUTPUT->confirm(get_string('confirmmessage', 'bulkusers', $usernames), $formcontinue, $formcancel); echo $OUTPUT->confirm($warning, $formcontinue, $formcancel);
echo $OUTPUT->footer(); echo $OUTPUT->footer();
die; die;
} }
// Do the reset. // Do the reset.
$legacytype = get_legacy_type($roleid); if ($roles[$roleid]->archetype) {
if ($legacytype) { set_role_contextlevels($roleid, get_default_contextlevels($roles[$roleid]->archetype));
set_role_contextlevels($roleid, get_default_contextlevels($legacytype));
} }
reset_role_capabilities($roleid); reset_role_capabilities($roleid);
// Mark context dirty, log and redirect. // Mark context dirty, log and redirect.
mark_context_dirty($systemcontext->path); mark_context_dirty($systemcontext->path);
add_to_log(SITEID, 'role', 'reset', 'admin/roles/manage.php?action=reset&roleid=' . $roleid, $roles[$roleid]->localname, '', $USER->id); add_to_log(SITEID, 'role', 'reset', 'admin/roles/manage.php?action=reset&roleid=' . $roleid, $roles[$roleid]->localname, '', $USER->id);
redirect($defineurl . '?action=view&amp;roleid=' . $roleid); redirect($defineurl . '?action=view&roleid=' . $roleid);
break; break;
} }

View File

@ -128,7 +128,7 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
$temp->add(new admin_setting_configtext('mycoursesperpage', get_string('mycoursesperpage', 'admin'), get_string('configmycoursesperpage', 'admin'), 21, PARAM_INT)); $temp->add(new admin_setting_configtext('mycoursesperpage', get_string('mycoursesperpage', 'admin'), get_string('configmycoursesperpage', 'admin'), 21, PARAM_INT));
$ADMIN->add('appearance', $temp); $ADMIN->add('appearance', $temp);
// new CFG variable for coursemanager (what roles to display) // coursemanager is the person responsible for course - usually manages enrolments, receives notification, etc.
$temp = new admin_settingpage('coursemanager', get_string('coursemanager', 'admin')); $temp = new admin_settingpage('coursemanager', get_string('coursemanager', 'admin'));
$temp->add(new admin_setting_special_coursemanager()); $temp->add(new admin_setting_special_coursemanager());
$ADMIN->add('appearance', $temp); $ADMIN->add('appearance', $temp);

View File

@ -17,7 +17,11 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
$temp->add(new admin_setting_configcheckbox('forcelogin', get_string('forcelogin', 'admin'), get_string('configforcelogin', 'admin'), 0)); $temp->add(new admin_setting_configcheckbox('forcelogin', get_string('forcelogin', 'admin'), get_string('configforcelogin', 'admin'), 0));
$temp->add(new admin_setting_configcheckbox('forceloginforprofiles', get_string('forceloginforprofiles', 'admin'), get_string('configforceloginforprofiles', 'admin'), 1)); $temp->add(new admin_setting_configcheckbox('forceloginforprofiles', get_string('forceloginforprofiles', 'admin'), get_string('configforceloginforprofiles', 'admin'), 1));
$temp->add(new admin_setting_configcheckbox('opentogoogle', get_string('opentogoogle', 'admin'), get_string('configopentogoogle', 'admin'), 0)); $temp->add(new admin_setting_configcheckbox('opentogoogle', get_string('opentogoogle', 'admin'), get_string('configopentogoogle', 'admin'), 0));
$temp->add(new admin_setting_pickroles('profileroles',
get_string('profileroles','admin'),
get_string('configprofileroles', 'admin'),
array('student', 'teacher', 'editingteacher')));
$max_upload_choices = get_max_upload_sizes(); $max_upload_choices = get_max_upload_sizes();
// maxbytes set to 0 will allow the maxium server lmit for uploads // maxbytes set to 0 will allow the maxium server lmit for uploads
$max_upload_choices[0] = get_string('serverlimit', 'admin'); $max_upload_choices[0] = get_string('serverlimit', 'admin');

View File

@ -37,7 +37,7 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
$optionalsubsystems->add(new admin_setting_pickroles('progresstrackedroles', $optionalsubsystems->add(new admin_setting_pickroles('progresstrackedroles',
get_string('progresstrackedroles','completion'), get_string('progresstrackedroles','completion'),
get_string('configprogresstrackedroles', 'completion'), get_string('configprogresstrackedroles', 'completion'),
array('moodle/legacy:student'))); array('student')));
$optionalsubsystems->add(new admin_setting_configcheckbox('enableavailability', $optionalsubsystems->add(new admin_setting_configcheckbox('enableavailability',
get_string('enableavailability','condition'), get_string('enableavailability','condition'),
get_string('configenableavailability','condition'), 0)); get_string('configenableavailability','condition'), 0));

View File

@ -84,65 +84,78 @@ if ($hassiteconfig
if ($ADMIN->fulltree) { if ($ADMIN->fulltree) {
if (!during_initial_install()) { if (!during_initial_install()) {
$context = get_context_instance(CONTEXT_SYSTEM); $context = get_context_instance(CONTEXT_SYSTEM);
if (!$guestrole = get_guest_role()) { $allroles = array();
$guestrole->id = 0; $generalroles = array();
} $guestroles = array();
if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) { $userroles = array();
$studentrole = array_shift($studentroles); /// Take the first one $studentroles = array();
} else { $teacherroles = array();
$studentrole->id = 0; $creatornewroles = array();
}
if ($userroles = get_roles_with_capability('moodle/legacy:user', CAP_ALLOW)) { foreach (get_all_roles() as $role) {
$userrole = array_shift($userroles); /// Take the first one $rolename = strip_tags(format_string($role->name)) . ' ('. $role->shortname . ')';
} else { $allroles[$role->id] = $rolename;
$userrole->id = 0; switch ($role->archetype) {
} case 'manager':
if (empty($CFG->creatornewroleid)) { $creatornewroles[$role->id] = $rolename;
if ($teacherroles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, $context)) { break;
$teachereditrole = array_shift($teacherroles); case 'coursecreator':
set_config('creatornewroleid', $teachereditrole->id); break;
} else { case 'editingteacher':
set_config('creatornewroleid', 0); $teacherroles[$role->id] = $rolename;
$creatornewroles[$role->id] = $rolename;
break;
case 'teacher':
$creatornewroles[$role->id] = $rolename;
break;
case 'student':
$studentroles[$role->id] = $rolename;
break;
case 'guest':
$guestroles[$role->id] = $rolename;
break;
case 'user':
$userroles[$role->id] = $rolename;
break;
case 'frontpage':
break;
default:
$creatornewroles[$role->id] = $rolename;
$generalroles[$role->id] = $rolename;
break;
} }
} }
if (!$guestroles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
$guestroles = array();
$defaultguestid = null;
} else {
$defaultguestid = reset($guestroles);
$defaultguestid = $defaultguestid->id;
}
// we must not use assignable roles here: reset($guestroles);
// 1/ unsetting roles as assignable for admin might bork the settings! $defaultguestid = key($guestroles);
// 2/ default user role should not be assignable anyway reset($studentroles);
$allroles = array(); $defaultstudentid = key($studentroles);
$nonguestroles = array(); reset($teacherroles);
if ($roles = get_all_roles()) { $defaultteacherid = key($teacherroles);
foreach ($roles as $role) {
$rolename = strip_tags(format_string($role->name, true)); if ($userroles) {
$allroles[$role->id] = $rolename; reset($userroles);
if (!isset($guestroles[$role->id])) { $defaultuserid = key($userroles);
$nonguestroles[$role->id] = $rolename; } else {
} $userroles = array('0'=>get_string('none'));
} $defaultuserid = 0;
} }
$temp->add(new admin_setting_configselect('notloggedinroleid', get_string('notloggedinroleid', 'admin'), $temp->add(new admin_setting_configselect('notloggedinroleid', get_string('notloggedinroleid', 'admin'),
get_string('confignotloggedinroleid', 'admin'), $defaultguestid, $allroles )); get_string('confignotloggedinroleid', 'admin'), $defaultguestid, ($guestroles + $generalroles)));
$temp->add(new admin_setting_configselect('guestroleid', get_string('guestroleid', 'admin'), $temp->add(new admin_setting_configselect('guestroleid', get_string('guestroleid', 'admin'),
get_string('configguestroleid', 'admin'), $defaultguestid, $allroles)); get_string('configguestroleid', 'admin'), $defaultguestid, ($guestroles + $generalroles)));
$temp->add(new admin_setting_configselect('defaultuserroleid', get_string('defaultuserroleid', 'admin'), $temp->add(new admin_setting_configselect('defaultuserroleid', get_string('defaultuserroleid', 'admin'),
get_string('configdefaultuserroleid', 'admin'), $userrole->id, $nonguestroles)); // guest role here breaks a lot of stuff get_string('configdefaultuserroleid', 'admin'), $defaultuserid, ($userroles + $generalroles)));
} }
$temp->add(new admin_setting_configcheckbox('nodefaultuserrolelists', get_string('nodefaultuserrolelists', 'admin'), get_string('confignodefaultuserrolelists', 'admin'), 0)); $temp->add(new admin_setting_configcheckbox('nodefaultuserrolelists', get_string('nodefaultuserrolelists', 'admin'), get_string('confignodefaultuserrolelists', 'admin'), 0));
if (!during_initial_install()) { if (!during_initial_install()) {
$temp->add(new admin_setting_configselect('defaultcourseroleid', get_string('defaultcourseroleid', 'admin'), $temp->add(new admin_setting_configselect('defaultcourseroleid', get_string('defaultcourseroleid', 'admin'),
get_string('configdefaultcourseroleid', 'admin'), $studentrole->id, $allroles)); get_string('configdefaultcourseroleid', 'admin'), $defaultstudentid, $allroles));
$temp->add(new admin_setting_configselect('creatornewroleid', get_string('creatornewroleid', 'admin'), $temp->add(new admin_setting_configselect('creatornewroleid', get_string('creatornewroleid', 'admin'),
get_string('configcreatornewroleid', 'admin'), $CFG->creatornewroleid, $allroles)); get_string('configcreatornewroleid', 'admin'), $defaultteacherid, $creatornewroles));
} }
$temp->add(new admin_setting_configcheckbox('autologinguests', get_string('autologinguests', 'admin'), get_string('configautologinguests', 'admin'), 0)); $temp->add(new admin_setting_configcheckbox('autologinguests', get_string('autologinguests', 'admin'), get_string('configautologinguests', 'admin'), 0));
@ -174,6 +187,9 @@ if ($hassiteconfig
} }
$ADMIN->add('roles', $temp); $ADMIN->add('roles', $temp);
if (is_siteadmin()) {
$ADMIN->add('roles', new admin_externalpage('admins', get_string('siteadministrators', 'role'), "$CFG->wwwroot/$CFG->admin/roles/admins.php"));
}
$ADMIN->add('roles', new admin_externalpage('defineroles', get_string('defineroles', 'role'), "$CFG->wwwroot/$CFG->admin/roles/manage.php", 'moodle/role:manage')); $ADMIN->add('roles', new admin_externalpage('defineroles', get_string('defineroles', 'role'), "$CFG->wwwroot/$CFG->admin/roles/manage.php", 'moodle/role:manage'));
$ADMIN->add('roles', new admin_externalpage('assignroles', get_string('assignglobalroles', 'role'), "$CFG->wwwroot/$CFG->admin/roles/assign.php?contextid=".$systemcontext->id, 'moodle/role:assign')); $ADMIN->add('roles', new admin_externalpage('assignroles', get_string('assignglobalroles', 'role'), "$CFG->wwwroot/$CFG->admin/roles/assign.php?contextid=".$systemcontext->id, 'moodle/role:assign'));
$ADMIN->add('roles', new admin_externalpage('checkpermissions', get_string('checkglobalpermissions', 'role'), "$CFG->wwwroot/$CFG->admin/roles/check.php?contextid=".$systemcontext->id, array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'))); $ADMIN->add('roles', new admin_externalpage('checkpermissions', get_string('checkglobalpermissions', 'role'), "$CFG->wwwroot/$CFG->admin/roles/check.php?contextid=".$systemcontext->id, array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage')));

View File

@ -322,7 +322,7 @@ if ($formdata = $mform->is_cancelled()) {
continue; continue;
} }
if ($existinguser) { if ($existinguser) {
if (has_capability('moodle/site:doanything', $systemcontext, $existinguser->id)) { if (is_siteadmin($existinguser->id)) {
$upt->track('status', $strusernotdeletedadmin, 'error'); $upt->track('status', $strusernotdeletedadmin, 'error');
$deleteerrors++; $deleteerrors++;
continue; continue;
@ -360,7 +360,7 @@ if ($formdata = $mform->is_cancelled()) {
if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$user->mnethostid))) { if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$user->mnethostid))) {
$upt->track('id', $olduser->id, 'normal', false); $upt->track('id', $olduser->id, 'normal', false);
if (has_capability('moodle/site:doanything', $systemcontext, $olduser->id)) { if (is_siteadmin($olduser->id)) {
$upt->track('status', $strusernotrenamedadmin, 'error'); $upt->track('status', $strusernotrenamedadmin, 'error');
$renameerrors++; $renameerrors++;
continue; continue;
@ -423,7 +423,7 @@ if ($formdata = $mform->is_cancelled()) {
if ($existinguser) { if ($existinguser) {
$user->id = $existinguser->id; $user->id = $existinguser->id;
if (has_capability('moodle/site:doanything', $systemcontext, $user->id)) { if (is_siteadmin($user->id)) {
$upt->track('status', $strusernotupdatedadmin, 'error'); $upt->track('status', $strusernotupdatedadmin, 'error');
$userserrors++; $userserrors++;
continue; continue;
@ -668,7 +668,7 @@ if ($formdata = $mform->is_cancelled()) {
// find group to add to // find group to add to
if (!empty($user->{'group'.$i})) { if (!empty($user->{'group'.$i})) {
// make sure user is enrolled into course before adding into groups // make sure user is enrolled into course before adding into groups
if (!has_capability('moodle/course:view', $coursecontext, $user->id, false)) { if (!is_enrolled($coursecontext, $user->id)) {
$upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $gname), 'error'); $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $gname), 'error');
continue; continue;
} }
@ -1175,12 +1175,6 @@ function uu_allowed_roles($shortname=false) {
$choices[$role->id] = format_string($role->name); $choices[$role->id] = format_string($role->name);
} }
} }
// get rid of all admin roles
if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW)) {
foreach($adminroles as $adminrole) {
unset($choices[$adminrole->id]);
}
}
return $choices; return $choices;
} }

View File

@ -121,7 +121,7 @@ class admin_uploaduser_form2 extends moodleform {
unset($choices[0]); unset($choices[0]);
$mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'admin'), $choices); $mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'admin'), $choices);
if ($editteacherroles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) { if ($editteacherroles = get_archetype_roles('editingteacher')) {
$editteacherrole = array_shift($editteacherroles); /// Take the first one $editteacherrole = array_shift($editteacherroles); /// Take the first one
$mform->setDefault('uulegacy2', $editteacherrole->id); $mform->setDefault('uulegacy2', $editteacherrole->id);
unset($editteacherroles); unset($editteacherroles);
@ -130,7 +130,7 @@ class admin_uploaduser_form2 extends moodleform {
} }
$mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'admin'), $choices); $mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'admin'), $choices);
if ($teacherroles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW)) { if ($teacherroles = get_archetype_roles('teacher')) {
$teacherrole = array_shift($teacherroles); /// Take the first one $teacherrole = array_shift($teacherroles); /// Take the first one
$mform->setDefault('uulegacy3', $teacherrole->id); $mform->setDefault('uulegacy3', $teacherrole->id);
unset($teacherroles); unset($teacherroles);

View File

@ -59,7 +59,7 @@ class service_user_selector extends user_selector_base {
//by default wherecondition retrieves all users except the deleted, not //by default wherecondition retrieves all users except the deleted, not
//confirmed and guest //confirmed and guest
list($wherecondition, $params) = $this->search_sql($search, 'u'); list($wherecondition, $params) = $this->search_sql($search, 'u');
$params[] = $this->serviceid; $params['serviceid'] = $this->serviceid;
$fields = 'SELECT ' . $this->required_fields_sql('u'); $fields = 'SELECT ' . $this->required_fields_sql('u');
@ -70,13 +70,13 @@ class service_user_selector extends user_selector_base {
$sql = " FROM {user} u, {external_services_users} esu $sql = " FROM {user} u, {external_services_users} esu
WHERE $wherecondition WHERE $wherecondition
AND esu.userid = u.id AND esu.userid = u.id
AND esu.externalserviceid = ?"; AND esu.externalserviceid = :serviceid";
} }
else { else {
///the following SQL retrieve all users that are not allowed to the serviceid ///the following SQL retrieve all users that are not allowed to the serviceid
$sql = " FROM {user} u WHERE $wherecondition $sql = " FROM {user} u WHERE $wherecondition
AND NOT EXISTS (SELECT esu.userid FROM {external_services_users} esu AND NOT EXISTS (SELECT esu.userid FROM {external_services_users} esu
WHERE esu.externalserviceid = ? WHERE esu.externalserviceid = :serviceid
AND esu.userid = u.id)"; AND esu.userid = u.id)";
} }

View File

@ -797,7 +797,7 @@ if ( !is_object($PHPCAS_CLIENT) ) {
$sitecontext = get_context_instance(CONTEXT_SYSTEM); $sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (!empty($this->config->creators) and !empty($this->config->memberattribute) if (!empty($this->config->creators) and !empty($this->config->memberattribute)
and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { and $roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
} else { } else {
$creatorrole = false; $creatorrole = false;
@ -846,7 +846,7 @@ if ( !is_object($PHPCAS_CLIENT) ) {
$sitecontext = get_context_instance(CONTEXT_SYSTEM); $sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (!empty($this->config->creators) and !empty($this->config->memberattribute) if (!empty($this->config->creators) and !empty($this->config->memberattribute)
and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { and $roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
} else { } else {
$creatorrole = false; $creatorrole = false;
@ -1118,7 +1118,7 @@ if (!empty($this->config->attrcreators)) {
if ($iscreator === null) { if ($iscreator === null) {
return; //nothing to sync - creators not configured return; //nothing to sync - creators not configured
} }
if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { if ($roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
$systemcontext = get_context_instance(CONTEXT_SYSTEM); $systemcontext = get_context_instance(CONTEXT_SYSTEM);
if ($iscreator) { // Following calls will not create duplicates if ($iscreator) { // Following calls will not create duplicates

View File

@ -178,7 +178,7 @@ class auth_plugin_fc extends auth_plugin_base {
return; //nothing to sync - creators not configured return; //nothing to sync - creators not configured
} }
if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { if ($roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
$systemcontext = get_context_instance(CONTEXT_SYSTEM); $systemcontext = get_context_instance(CONTEXT_SYSTEM);

View File

@ -724,7 +724,7 @@ class auth_plugin_ldap extends auth_plugin_base {
$sitecontext = get_context_instance(CONTEXT_SYSTEM); $sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (!empty($this->config->creators) and !empty($this->config->memberattribute) if (!empty($this->config->creators) and !empty($this->config->memberattribute)
and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { and $roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
} else { } else {
$creatorrole = false; $creatorrole = false;
@ -774,7 +774,7 @@ class auth_plugin_ldap extends auth_plugin_base {
$sitecontext = get_context_instance(CONTEXT_SYSTEM); $sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (!empty($this->config->creators) and !empty($this->config->memberattribute) if (!empty($this->config->creators) and !empty($this->config->memberattribute)
and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { and $roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
} else { } else {
$creatorrole = false; $creatorrole = false;
@ -1945,7 +1945,7 @@ class auth_plugin_ldap extends auth_plugin_base {
return; //nothing to sync - creators not configured return; //nothing to sync - creators not configured
} }
if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) { if ($roles = get_archetype_roles('coursecreator')) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one $creatorrole = array_shift($roles); // We can only use one, let's use the first one
$systemcontext = get_context_instance(CONTEXT_SYSTEM); $systemcontext = get_context_instance(CONTEXT_SYSTEM);

View File

@ -141,8 +141,8 @@ class auth_plugin_mnet extends auth_plugin_base {
// check remote login permissions // check remote login permissions
if (! has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM)) if (! has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM))
or is_mnet_remote_user($USER) or is_mnet_remote_user($USER)
or $USER->username == 'guest' or isguestuser()
or empty($USER->id)) { or !isloggedin()) {
print_error('notpermittedtojump', 'mnet'); print_error('notpermittedtojump', 'mnet');
} }

View File

@ -162,10 +162,10 @@
function backup_get_enrolled_users ($courseid) { function backup_get_enrolled_users ($courseid) {
global $CFG; global $CFG;
// get all users with moodle/course:view capability, this will include people // get all users with moodle/course:participate capability, this will include people
// assigned at cat level, or site level // assigned at cat level, or site level
// but it should be ok if they have no direct assignment at course, mod, block level // but it should be ok if they have no direct assignment at course, mod, block level
return get_users_by_capability(get_context_instance(CONTEXT_COURSE, $courseid), 'moodle/course:view', '', '', '', '', '', '', false); return get_users_by_capability(get_context_instance(CONTEXT_COURSE, $courseid), 'moodle/course:participate', '', '', '', '', '', '', false);
} }
//Returns all users ids (every record in users table) //Returns all users ids (every record in users table)
@ -2911,7 +2911,6 @@
if (backup_getid($preferences->backup_unique_code, 'user', $assignment->userid)) { if (backup_getid($preferences->backup_unique_code, 'user', $assignment->userid)) {
fwrite ($bf, start_tag("ASSIGNMENT", $startlevel+3, true)); fwrite ($bf, start_tag("ASSIGNMENT", $startlevel+3, true));
fwrite ($bf, full_tag("USERID", $startlevel+4, false, $assignment->userid)); fwrite ($bf, full_tag("USERID", $startlevel+4, false, $assignment->userid));
fwrite ($bf, full_tag("HIDDEN", $startlevel+4, false, $assignment->hidden));
fwrite ($bf, full_tag("TIMESTART", $startlevel+4, false, $assignment->timestart)); fwrite ($bf, full_tag("TIMESTART", $startlevel+4, false, $assignment->timestart));
fwrite ($bf, full_tag("TIMEEND", $startlevel+4, false, $assignment->timeend)); fwrite ($bf, full_tag("TIMEEND", $startlevel+4, false, $assignment->timeend));
fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $assignment->timemodified)); fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $assignment->timemodified));

View File

@ -636,7 +636,7 @@ if ($restoreuserinfo) {
echo ('</td><td algin="left">'); echo ('</td><td algin="left">');
// get the first teacheredit legacy // get the first teacheredit legacy
$roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM)); $roles = get_archetype_roles('editingteacher');
$editteacher = reset($roles); $editteacher = reset($roles);
echo html_writer::select($siterolesarray, "defaultteacheredit", $editteacher->id, array(''=>'new role')); echo html_writer::select($siterolesarray, "defaultteacheredit", $editteacher->id, array(''=>'new role'));
@ -649,7 +649,7 @@ if ($restoreuserinfo) {
echo ('</td><td algin="left">'); echo ('</td><td algin="left">');
// get the first teacheredit legacy // get the first teacheredit legacy
$roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM)); $roles = get_archetype_roles('teacher');
$teacher = reset($roles); $teacher = reset($roles);
echo html_writer::select($siterolesarray, "defaultteacher", $teacher->id, array(''=>'new role')); echo html_writer::select($siterolesarray, "defaultteacher", $teacher->id, array(''=>'new role'));
@ -662,7 +662,7 @@ if ($restoreuserinfo) {
echo ('</td><td algin="left">'); echo ('</td><td algin="left">');
// get the first teacheredit legacy // get the first teacheredit legacy
$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM)); $roles = get_archetype_roles('student');
$studentrole = array_shift($roles); $studentrole = array_shift($roles);
echo html_writer::select($siterolesarray, "defaultstudent", $studentrole->id, array(''=>'new role')); echo html_writer::select($siterolesarray, "defaultstudent", $studentrole->id, array(''=>'new role'));

View File

@ -1557,7 +1557,7 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
// anything except id // anything except id
$restore->userswhocanviewcourse=get_users_by_capability( $restore->userswhocanviewcourse=get_users_by_capability(
get_context_instance(CONTEXT_COURSE, $restore->course_id), get_context_instance(CONTEXT_COURSE, $restore->course_id),
'moodle/course:view','u.id'); 'moodle/course:participate','u.id');
} }
foreach($info->completiondata as $data) { foreach($info->completiondata as $data) {
@ -5952,9 +5952,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
$this->info->tempuser = $this->getContents(); $this->info->tempuser = $this->getContents();
$this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents(); $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
break; break;
case "HIDDEN":
$this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
break;
case "TIMESTART": case "TIMESTART":
$this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents(); $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
break; break;
@ -6175,9 +6172,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
$this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents(); $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
break; break;
case "HIDDEN":
$this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
break;
case "TIMESTART": case "TIMESTART":
$this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents(); $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
break; break;
@ -6428,9 +6422,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
$this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents(); $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
break; break;
case "HIDDEN":
$this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
break;
case "TIMESTART": case "TIMESTART":
$this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents(); $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
break; break;
@ -7315,9 +7306,6 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
$this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->userid = $this->getContents(); $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->userid = $this->getContents();
break; break;
case "HIDDEN":
$this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->hidden = $this->getContents();
break;
case "TIMESTART": case "TIMESTART":
$this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timestart = $this->getContents(); $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timestart = $this->getContents();
break; break;
@ -9171,7 +9159,7 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
if ($CFG->creatornewroleid) { if ($CFG->creatornewroleid) {
role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id); role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id);
} else { } else {
if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM))) { if ($legacyteachers = get_archetype_roles('editingteacher')) {
if ($legacyteacher = array_shift($legacyteachers)) { if ($legacyteacher = array_shift($legacyteachers)) {
role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id); role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id);
} }

View File

@ -20,16 +20,15 @@ class block_admin extends block_list {
$course = $this->page->course; $course = $this->page->course;
if (!has_capability('moodle/course:view', $this->page->context)) { // Just return
return $this->content;
}
if (empty($CFG->loginhttps)) { if (empty($CFG->loginhttps)) {
$securewwwroot = $CFG->wwwroot; $securewwwroot = $CFG->wwwroot;
} else { } else {
$securewwwroot = str_replace('http:','https:',$CFG->wwwroot); $securewwwroot = str_replace('http:','https:',$CFG->wwwroot);
} }
$isenrolled = is_enrolled($this->page->context);
$isviewing = is_viewing($this->page->context);
/// Course editing on/off /// Course editing on/off
if ($course->id !== SITEID and has_capability('moodle/course:update', $this->page->context)) { if ($course->id !== SITEID and has_capability('moodle/course:update', $this->page->context)) {
$this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/edit') . '" class="icon" alt="" />'; $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/edit') . '" class="icon" alt="" />';
@ -56,7 +55,7 @@ class block_admin extends block_list {
/// View course grades (or just your own grades, same link) /// View course grades (or just your own grades, same link)
/// find all accessible reports /// find all accessible reports
if ($course->id !== SITEID) { if ($course->id !== SITEID and ($isenrolled or $isviewing)) {
$reportavailable = false; $reportavailable = false;
if (has_capability('moodle/grade:viewall', $this->page->context)) { if (has_capability('moodle/grade:viewall', $this->page->context)) {
$reportavailable = true; $reportavailable = true;
@ -194,17 +193,23 @@ class block_admin extends block_list {
/// Unenrol link /// Unenrol link
if (empty($course->metacourse) && ($course->id!==SITEID)) { if (empty($course->metacourse) && ($course->id!==SITEID)) {
if (has_capability('moodle/legacy:guest', $this->page->context, NULL, false)) { // Are a guest now if ($isenrolled) {
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[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
$this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
}
} else if ($isviewing) {
// inspector, manager, etc. - do not show anything
} else {
// access because otherwise they would not get into this course at all
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>'; $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
$this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />'; $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
} else 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[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
$this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" class="icon" alt="" />';
} }
} }
/// Link to the user own profile (except guests) /// Link to the user own profile if they are enrolled
if (!isguestuser() and isloggedin()) { if ($isenrolled) {
$this->content->items[]='<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&amp;course='.$course->id.'">'.get_string('profile').'</a>'; $this->content->items[]='<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&amp;course='.$course->id.'">'.get_string('profile').'</a>';
$this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" alt="" />'; $this->content->icons[]='<img src="'.$OUTPUT->pix_url('i/user') . '" alt="" />';
} }

View File

@ -108,7 +108,7 @@ class block_admin_tree extends block_base {
} }
if (isguestuser() or !isloggedin()) { if (isguestuser() or !isloggedin()) {
// these users can not change any settings // shortcut - these users can not change any settings
$this->content = ''; $this->content = '';
return ''; return '';
} }

View File

@ -38,9 +38,10 @@ class block_comments extends block_base {
} }
$this->content->footer = ''; $this->content->footer = '';
$this->content->text = ''; $this->content->text = '';
//TODO: guest and not-logged-in shoudl be able to read comments, right?
if (isloggedin() && !isguestuser()) { // Show the block if (isloggedin() && !isguestuser()) { // Show the block
$cmt = new stdclass; $cmt = new stdclass;
$cmt->context = $this->instance->context; $cmt->context = $this->context;
$cmt->area = 'block_comments'; $cmt->area = 'block_comments';
$cmt->itemid = $this->instance->id; $cmt->itemid = $this->instance->id;
$cmt->course = $this->page->course; $cmt->course = $this->page->course;

View File

@ -34,10 +34,8 @@ class block_course_list extends block_list {
} }
} }
if (empty($CFG->disablemycourses) and if (empty($CFG->disablemycourses) and isloggedin() and !isguestuser() and
!empty($USER->id) and !(has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM)) and $adminseesall)) { // Just print My Courses
!(has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM)) and $adminseesall) and
!isguestuser()) { // Just print My Courses
if ($courses = get_my_courses($USER->id, 'visible DESC, fullname ASC')) { if ($courses = get_my_courses($USER->id, 'visible DESC, fullname ASC')) {
foreach ($courses as $course) { foreach ($courses as $course) {
if ($course->id == SITEID) { if ($course->id == SITEID) {
@ -118,7 +116,7 @@ class block_course_list extends block_list {
$icon = '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />'; $icon = '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
// only for logged in users! // shortcut - the rest is only for logged in users!
if (!isloggedin() || isguestuser()) { if (!isloggedin() || isguestuser()) {
return false; return false;
} }

View File

@ -94,7 +94,7 @@ class block_global_navigation_tree extends block_tree {
global $CFG, $OUTPUT; global $CFG, $OUTPUT;
// First check if we have already generated, don't waste cycles // First check if we have already generated, don't waste cycles
if ($this->contentgenerated === true) { if ($this->contentgenerated === true) {
return true; return $this->content;
} }
$this->page->requires->yui2_lib('dom'); $this->page->requires->yui2_lib('dom');
// JS for navigation moved to the standard theme, the code will probably have to depend on the actual page structure // JS for navigation moved to the standard theme, the code will probably have to depend on the actual page structure
@ -158,7 +158,7 @@ class block_global_navigation_tree extends block_tree {
$module = array('name'=>'block_navigation', 'fullpath'=>'/blocks/global_navigation_tree/navigation.js', 'requires'=>array('core_dock', 'io', 'node', 'dom', 'event-custom', 'json-parse')); $module = array('name'=>'block_navigation', 'fullpath'=>'/blocks/global_navigation_tree/navigation.js', 'requires'=>array('core_dock', 'io', 'node', 'dom', 'event-custom', 'json-parse'));
$arguments = array($this->instance->id, array('expansions'=>$expandable, 'instance'=>$this->instance->id, 'candock'=>$this->instance_can_be_docked())); $arguments = array($this->instance->id, array('expansions'=>$expandable, 'instance'=>$this->instance->id, 'candock'=>$this->instance_can_be_docked()));
$this->page->requires->js_init_call('M.block_navigation.init_add_tree', $arguments, false, $module); $this->page->requires->js_init_call('M.block_navigation.init_add_tree', $arguments, false, $module);
// Grab the items to display // Grab the items to display
$this->content->items = array($this->page->navigation); $this->content->items = array($this->page->navigation);
@ -168,7 +168,8 @@ class block_global_navigation_tree extends block_tree {
// Set content generated to true so that we know it has been done // Set content generated to true so that we know it has been done
$this->contentgenerated = true; $this->contentgenerated = true;
return true;
return $this->content;
} }
/** /**

View File

@ -25,7 +25,7 @@ class block_messages extends block_base {
$this->content->text = ''; $this->content->text = '';
$this->content->footer = ''; $this->content->footer = '';
if (empty($this->instance) or empty($USER->id) or isguestuser() or empty($CFG->messaging)) { if (empty($this->instance) or !isloggedin() or isguestuser() or empty($CFG->messaging)) {
return $this->content; return $this->content;
} }

View File

@ -21,7 +21,7 @@ class block_mnet_hosts extends block_list {
function get_content() { function get_content() {
global $CFG, $USER, $DB, $OUTPUT; global $CFG, $USER, $DB, $OUTPUT;
// only for logged in users! // shortcut - only for logged in users!
if (!isloggedin() || isguestuser()) { if (!isloggedin() || isguestuser()) {
return false; return false;
} }

View File

@ -555,11 +555,7 @@ class block_base {
$this->config = unserialize(base64_decode($instance->configdata)); $this->config = unserialize(base64_decode($instance->configdata));
} }
$this->instance = $instance; $this->instance = $instance;
if (isset($instance->context)) { $this->context = get_context_instance(CONTEXT_BLOCK, $instance->id);
$this->context = $instance->context;
} else {
$this->context = get_context_instance(CONTEXT_BLOCK, $instance->id);
}
$this->page = $page; $this->page = $page;
$this->specialization(); $this->specialization();
$this->get_required_javascript(); $this->get_required_javascript();

View File

@ -102,7 +102,7 @@ class block_news_items extends block_base {
} else { } else {
$tooltiptext = get_string('rsssubscriberssposts','forum',format_string($forum->name)); $tooltiptext = get_string('rsssubscriberssposts','forum',format_string($forum->name));
} }
if (empty($USER->id)) { if (!isloggedin()) {
$userid = 0; $userid = 0;
} else { } else {
$userid = $USER->id; $userid = $USER->id;

View File

@ -55,12 +55,14 @@ class block_online_users extends block_base {
$params['currentgroup'] = $currentgroup; $params['currentgroup'] = $currentgroup;
} }
$userfields = user_picture::fields('u').', username';
if ($this->page->course->id == SITEID) { // Site-level if ($this->page->course->id == SITEID) { // Site-level
$sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.picture, MAX(u.lastaccess) AS lastaccess $sql = "SELECT $userfields, MAX(u.lastaccess) AS lastaccess
FROM {user} u $groupmembers FROM {user} u $groupmembers
WHERE u.lastaccess > $timefrom WHERE u.lastaccess > $timefrom
$groupselect $groupselect
GROUP BY u.id, u.username, u.firstname, u.lastname, u.picture GROUP BY $userfields
ORDER BY lastaccess DESC "; ORDER BY lastaccess DESC ";
$csql = "SELECT COUNT(u.id), u.id $csql = "SELECT COUNT(u.id), u.id
@ -69,24 +71,26 @@ class block_online_users extends block_base {
$groupselect $groupselect
GROUP BY u.id"; GROUP BY u.id";
} else { // Course-level } else {
if (!has_capability('moodle/role:viewhiddenassigns', $this->page->context)) { // Course level - show only enrolled users for now
$pcontext = get_related_contexts_string($this->page->context); // TODO: add a new capability for viewing of all users (guests+enrolled+viewing)
$rafrom = ", {role_assignments} ra";
$rawhere = " AND ra.userid = u.id AND ra.contextid $pcontext AND ra.hidden = 0";
}
$sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.picture, MAX(ul.timeaccess) AS lastaccess list($esqljoin, $eparams) = get_enrolled_sql($this->page->context);
$params = array_merge($params, $eparams);
$sql = "SELECT $userfields, MAX(ul.timeaccess) AS lastaccess
FROM {user_lastaccess} ul, {user} u $groupmembers $rafrom FROM {user_lastaccess} ul, {user} u $groupmembers $rafrom
JOIN ($esqljoin) euj ON euj.id = u.id
WHERE ul.timeaccess > $timefrom WHERE ul.timeaccess > $timefrom
AND u.id = ul.userid AND u.id = ul.userid
AND ul.courseid = :courseid AND ul.courseid = :courseid
$groupselect $rawhere $groupselect $rawhere
GROUP BY u.id, u.username, u.firstname, u.lastname, u.picture GROUP BY $userfields
ORDER BY lastaccess DESC"; ORDER BY lastaccess DESC";
$csql = "SELECT u.id $csql = "SELECT u.id
FROM {user_lastaccess} ul, {user} u $groupmembers $rafrom FROM {user_lastaccess} ul, {user} u $groupmembers $rafrom
JOIN ($esqljoin) euj ON euj.id = u.id
WHERE ul.timeaccess > $timefrom WHERE ul.timeaccess > $timefrom
AND u.id = ul.userid AND u.id = ul.userid
AND ul.courseid = :courseid AND ul.courseid = :courseid
@ -131,7 +135,7 @@ class block_online_users extends block_base {
//Accessibility: Don't want 'Alt' text for the user picture; DO want it for the envelope/message link (existing lang string). //Accessibility: Don't want 'Alt' text for the user picture; DO want it for the envelope/message link (existing lang string).
//Accessibility: Converted <div> to <ul>, inherit existing classes & styles. //Accessibility: Converted <div> to <ul>, inherit existing classes & styles.
$this->content->text .= "<ul class='list'>\n"; $this->content->text .= "<ul class='list'>\n";
if (!empty($USER->id) && has_capability('moodle/site:sendmessage', $this->page->context) if (isloggedin() && has_capability('moodle/site:sendmessage', $this->page->context)
&& !empty($CFG->messaging) && !isguestuser()) { && !empty($CFG->messaging) && !isguestuser()) {
$canshowicon = true; $canshowicon = true;
} else { } else {

View File

@ -35,7 +35,7 @@ $capabilities = array(
'student' => CAP_ALLOW, 'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )
); );

View File

@ -286,7 +286,7 @@ class block_quiz_results extends block_base {
case SEPARATEGROUPS: case SEPARATEGROUPS:
// This is going to be just like no-groups mode, only we 'll filter // This is going to be just like no-groups mode, only we 'll filter
// out the grades from people not in our group. // out the grades from people not in our group.
if(empty($USER) || empty($USER->id)) { if (!isloggedin()) {
// Not logged in, so show nothing // Not logged in, so show nothing
return $this->content; return $this->content;
} }

View File

@ -37,7 +37,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -48,7 +48,7 @@ $capabilities = array(
'captype' => 'write', 'captype' => 'write',
'contextlevel' => CONTEXT_BLOCK, 'contextlevel' => CONTEXT_BLOCK,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -102,7 +102,7 @@ class block_section_links extends block_base {
} }
} }
if (!empty($USER->id)) { if (isloggedin()) {
$display = $DB->get_field('course_display', 'display', array('course'=>$this->page->course->id, 'userid'=>$USER->id)); $display = $DB->get_field('course_display', 'display', array('course'=>$this->page->course->id, 'userid'=>$USER->id));
} }
if (!empty($display)) { if (!empty($display)) {

View File

@ -79,8 +79,7 @@ class block_tags extends block_base {
// Permissions and page awareness // Permissions and page awareness
$systemcontext = get_context_instance(CONTEXT_SYSTEM); $systemcontext = get_context_instance(CONTEXT_SYSTEM);
$isguest = has_capability('moodle/legacy:guest', $systemcontext, $USER->id, false); $loggedin = isloggedin() && !isguestuser();
$loggedin = isloggedin() && !$isguest;
$coursepage = $canedit = false; $coursepage = $canedit = false;
$coursepage = (isset($this->page->course->id) && $this->page->course->id != SITEID); $coursepage = (isset($this->page->course->id) && $this->page->course->id != SITEID);
$mymoodlepage = ($SCRIPT == '/my/index.php') ? true : false; $mymoodlepage = ($SCRIPT == '/my/index.php') ? true : false;

View File

@ -132,7 +132,7 @@ class blog_edit_form extends moodleform {
$coursecontext = $DB->get_record('context', array('id' => $data['courseassoc'], 'contextlevel' => CONTEXT_COURSE)); $coursecontext = $DB->get_record('context', array('id' => $data['courseassoc'], 'contextlevel' => CONTEXT_COURSE));
if ($coursecontext) { if ($coursecontext) {
if (!has_capability('moodle/course:view', $coursecontext, $USER->id)) { if (!is_enrolled($coursecontext) and !is_viewing($coursecontext)) {
$errors['courseassoc'] = get_string('studentnotallowed', '', fullname($USER, true)); $errors['courseassoc'] = get_string('studentnotallowed', '', fullname($USER, true));
} }
} else { } else {
@ -161,7 +161,7 @@ class blog_edit_form extends moodleform {
} }
// ensure the user has access to each mod's course // ensure the user has access to each mod's course
if (!has_capability('moodle/course:view', $coursecontext)) { if (!is_enrolled($modcontext) and !is_viewing($modcontext)) {
$errors['modassoc'] = get_string('studentnotallowed', '', fullname($USER, true)); $errors['modassoc'] = get_string('studentnotallowed', '', fullname($USER, true));
} }
} else { } else {

View File

@ -67,7 +67,7 @@ function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
return false; // blog system disabled return false; // blog system disabled
} }
if (!empty($USER->id) && $USER->id == $targetuserid) { if (isloggdin() && $USER->id == $targetuserid) {
return true; // can view own entries in any case return true; // can view own entries in any case
} }
@ -92,7 +92,7 @@ function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
break; break;
case BLOG_SITE_LEVEL: case BLOG_SITE_LEVEL:
if (!empty($USER->id)) { // not logged in viewers forbidden if (isloggedin()) { // not logged in viewers forbidden
return true; return true;
} }
return false; return false;
@ -366,7 +366,6 @@ function blog_get_headers() {
$cm = $DB->get_record('course_modules', array('id' => $modid)); $cm = $DB->get_record('course_modules', array('id' => $modid));
$cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module)); $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
$cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance)); $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
$cm->context = get_context_instance(CONTEXT_MODULE, $modid);
$a->type = get_string('modulename', $cm->modname); $a->type = get_string('modulename', $cm->modname);
$PAGE->set_cm($cm, $course); $PAGE->set_cm($cm, $course);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a); $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);

View File

@ -588,7 +588,7 @@ class blog_entry {
return false; // blog system disabled or user has no blog view capability return false; // blog system disabled or user has no blog view capability
} }
if (!empty($USER->id) && $USER->id == $targetuserid) { if (isloggedin() && $USER->id == $targetuserid) {
return true; // can view own entries in any case return true; // can view own entries in any case
} }
@ -612,7 +612,7 @@ class blog_entry {
break; break;
case BLOG_SITE_LEVEL: case BLOG_SITE_LEVEL:
if (!empty($USER->id)) { // not logged in viewers forbidden if (isloggedin()) { // not logged in viewers forbidden
return true; return true;
} }
return false; return false;
@ -743,7 +743,7 @@ class blog_listing {
// don't add permission constraints // don't add permission constraints
} else { } else {
if (isloggedin() && !has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM, SITEID), $userid, false)) { if (isloggedin() and !isguestuser()) {
$assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
//begin permission sql clause //begin permission sql clause

View File

@ -9,8 +9,8 @@ function blog_rss_print_link($filtertype, $filterselect, $tagid=0, $tooltiptext=
global $CFG, $USER, $OUTPUT; global $CFG, $USER, $OUTPUT;
if (empty($USER->id)) { if (!isloggedin()) {
$userid = 1; $userid = $CFG->siteguest;
} else { } else {
$userid = $USER->id; $userid = $USER->id;
} }

View File

@ -105,23 +105,13 @@ if(!checkdate($mon, $day, $yr)) {
} }
$time = make_timestamp($yr, $mon, $day); $time = make_timestamp($yr, $mon, $day);
$isguest = has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false); if (!isloggedin() or isguestuser()) {
if (empty($USER->id) or $isguest) {
$defaultcourses = calendar_get_default_courses(); $defaultcourses = calendar_get_default_courses();
calendar_set_filters($courses, $groups, $users, $defaultcourses, $defaultcourses); calendar_set_filters($courses, $groups, $users, $defaultcourses, $defaultcourses);
} else { } else {
calendar_set_filters($courses, $groups, $users); calendar_set_filters($courses, $groups, $users);
} }
if (empty($USER->id) or $isguest) {
$defaultcourses = calendar_get_default_courses();
calendar_set_filters($courses, $groups, $users, $defaultcourses, $defaultcourses);
} else {
calendar_set_filters($courses, $groups, $users);
}
$strcalendar = get_string('calendar', 'calendar'); $strcalendar = get_string('calendar', 'calendar');
$prefsbutton = calendar_preferences_button(); $prefsbutton = calendar_preferences_button();

View File

@ -858,7 +858,7 @@ function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses
} }
if(!empty($USER->id) && !has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) { if (isloggedin() && !isguestuser()) {
$content .= "</tr>\n<tr>"; $content .= "</tr>\n<tr>";
if($groupevents) { if($groupevents) {
@ -1191,8 +1191,8 @@ function calendar_session_vars($course=null) {
// The empty() instead of !isset() here makes a whole world of difference, // The empty() instead of !isset() here makes a whole world of difference,
// as it will automatically change to the user's id when the user first logs // as it will automatically change to the user's id when the user first logs
// in. With !isset(), it would never do that. // in. With !isset(), it would never do that.
$SESSION->cal_users_shown = !empty($USER->id) ? $USER->id : false; $SESSION->cal_users_shown = isloggedin() ? $USER->id : false;
} else if(is_numeric($SESSION->cal_users_shown) && !empty($USER->id) && $SESSION->cal_users_shown != $USER->id) { } else if(is_numeric($SESSION->cal_users_shown) && isloggedin() && $SESSION->cal_users_shown != $USER->id) {
// Follow the white rabbit, for example if a teacher logs in as a student // Follow the white rabbit, for example if a teacher logs in as a student
$SESSION->cal_users_shown = $USER->id; $SESSION->cal_users_shown = $USER->id;
} }
@ -1312,7 +1312,7 @@ function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NU
} }
// If the user is an editing teacher in there, // If the user is an editing teacher in there,
if (!empty($USER->id) && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) { if (isloggedin() && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
// If this course has groups, show events from all of them // If this course has groups, show events from all of them
if(is_int($groupeventsfrom)) { if(is_int($groupeventsfrom)) {
if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221 if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
@ -1412,7 +1412,7 @@ function calendar_get_default_courses($ignoreref = false) {
return array($SESSION->cal_course_referer => 1); return array($SESSION->cal_course_referer => 1);
} }
if(empty($USER->id)) { if (!isloggedin()) {
return array(); return array();
} }
@ -1438,7 +1438,7 @@ function calendar_preferences_button() {
global $CFG, $USER; global $CFG, $USER;
// Guests have no preferences // Guests have no preferences
if (empty($USER->id) || has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) { if (!isloggedin() || isguestuser()) {
return ''; return '';
} }
@ -1559,7 +1559,7 @@ function calendar_get_filters_status() {
function calendar_set_filters_status($packed_bitfield) { function calendar_set_filters_status($packed_bitfield) {
global $SESSION, $USER; global $SESSION, $USER;
if(!isset($USER) || empty($USER->id)) { if (!isloggedin()) {
return false; return false;
} }
@ -1617,7 +1617,7 @@ function calendar_add_event_allowed($event) {
global $USER, $DB; global $USER, $DB;
// can not be using guest account // can not be using guest account
if (empty($USER->id) or $USER->username == 'guest') { if (!isloggedin() or isguestuser()) {
return false; return false;
} }

View File

@ -128,7 +128,7 @@ if (!empty($courseid)) {
$course = null; $course = null;
} }
if (empty($USER->id) or has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) { if (!isloggedin() or isguestuser()) {
$defaultcourses = calendar_get_default_courses(); $defaultcourses = calendar_get_default_courses();
calendar_set_filters($courses, $groups, $users, $defaultcourses, $defaultcourses); calendar_set_filters($courses, $groups, $users, $defaultcourses, $defaultcourses);
@ -182,7 +182,7 @@ echo $OUTPUT->container_start('bottom');
if (!empty($CFG->enablecalendarexport)) { if (!empty($CFG->enablecalendarexport)) {
echo $OUTPUT->single_button(new moodle_url('export.php', array('course'=>$courseid)), get_string('exportcalendar', 'calendar')); echo $OUTPUT->single_button(new moodle_url('export.php', array('course'=>$courseid)), get_string('exportcalendar', 'calendar'));
if (!empty($USER->id)) { if (isloggedin()) {
$authtoken = sha1($USER->username . $USER->password . $CFG->calendar_exportsalt); $authtoken = sha1($USER->username . $USER->password . $CFG->calendar_exportsalt);
$usernameencoded = urlencode($USER->username); $usernameencoded = urlencode($USER->username);
@ -257,7 +257,7 @@ function calendar_show_day($d, $m, $y, $courses, $groups, $users, $courseid) {
$events = calendar_get_upcoming($courses, $groups, $users, 1, 100, $starttime); $events = calendar_get_upcoming($courses, $groups, $users, 1, 100, $starttime);
$text = ''; $text = '';
if (!has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false) && !empty($USER->id) && calendar_user_can_add_event()) { if (!isguestuser() && isloggedin() && calendar_user_can_add_event()) {
$text.= '<div class="buttons">'; $text.= '<div class="buttons">';
$text.= '<form action="'.CALENDAR_URL.'event.php" method="get">'; $text.= '<form action="'.CALENDAR_URL.'event.php" method="get">';
$text.= '<div>'; $text.= '<div>';
@ -403,7 +403,7 @@ function calendar_show_month_detailed($m, $y, $courses, $groups, $users, $course
calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses); calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
$text = ''; $text = '';
if(!has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false) && !empty($USER->id) && calendar_user_can_add_event()) { if(!isguestuser() && isloggedin() && calendar_user_can_add_event()) {
$text.= '<div class="buttons"><form action="'.CALENDAR_URL.'event.php" method="get">'; $text.= '<div class="buttons"><form action="'.CALENDAR_URL.'event.php" method="get">';
$text.= '<div>'; $text.= '<div>';
$text.= '<input type="hidden" name="action" value="new" />'; $text.= '<input type="hidden" name="action" value="new" />';
@ -562,7 +562,7 @@ function calendar_show_month_detailed($m, $y, $courses, $groups, $users, $course
echo "</tr>\n"; echo "</tr>\n";
if(!empty($USER->id) && !has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) { if(isloggedin() && !isguestuser()) {
echo '<tr>'; echo '<tr>';
// Group events // Group events
if($SESSION->cal_show_groups) { if($SESSION->cal_show_groups) {
@ -593,7 +593,7 @@ function calendar_show_upcoming_events($courses, $groups, $users, $futuredays, $
$text = ''; $text = '';
if(!has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false) && !empty($USER->id) && calendar_user_can_add_event()) { if(!isguestuser() && isloggedin() && calendar_user_can_add_event()) {
$text.= '<div class="buttons">'; $text.= '<div class="buttons">';
$text.= '<form action="'.CALENDAR_URL.'event.php" method="get">'; $text.= '<form action="'.CALENDAR_URL.'event.php" method="get">';
$text.= '<div>'; $text.= '<div>';
@ -629,7 +629,7 @@ function calendar_show_upcoming_events($courses, $groups, $users, $futuredays, $
function calendar_course_filter_selector($getvars = '') { function calendar_course_filter_selector($getvars = '') {
global $USER, $SESSION, $OUTPUT; global $USER, $SESSION, $OUTPUT;
if (empty($USER->id) or has_capability('moodle/legacy:guest', get_context_instance(CONTEXT_SYSTEM), 0, false)) { if (!isloggedin() or isguestuser()) {
return ''; return '';
} }

View File

@ -29,12 +29,6 @@ list($context, $course, $cm) = get_context_info_array($contextid);
require_login($course, true, $cm); require_login($course, true, $cm);
require_sesskey(); require_sesskey();
if (isguestuser()) {
$err = new stdclass;
$err->error = get_string('loggedinnot');
die(json_encode($err));
}
$action = optional_param('action', '', PARAM_ALPHA); $action = optional_param('action', '', PARAM_ALPHA);
$area = optional_param('area', '', PARAM_ALPHAEXT); $area = optional_param('area', '', PARAM_ALPHAEXT);
$client_id = optional_param('client_id', '', PARAM_RAW); $client_id = optional_param('client_id', '', PARAM_RAW);

View File

@ -27,10 +27,6 @@ list($context, $course, $cm) = get_context_info_array($contextid);
require_login($course, true, $cm); require_login($course, true, $cm);
require_sesskey(); require_sesskey();
if (isguestuser()) {
print_error('loggedinnot');
}
$action = optional_param('action', '', PARAM_ALPHA); $action = optional_param('action', '', PARAM_ALPHA);
$area = optional_param('area', '', PARAM_ALPHAEXT); $area = optional_param('area', '', PARAM_ALPHAEXT);
$commentid = optional_param('commentid', -1, PARAM_INT); $commentid = optional_param('commentid', -1, PARAM_INT);

View File

@ -307,11 +307,7 @@
$spacer = '<img src="'.$CFG->wwwroot.'/pix/spacer.gif" class="iconsmall" alt="" /> '; $spacer = '<img src="'.$CFG->wwwroot.'/pix/spacer.gif" class="iconsmall" alt="" /> ';
foreach ($courses as $acourse) { foreach ($courses as $acourse) {
if (isset($acourse->context)) { $coursecontext = get_context_instance(CONTEXT_COURSE, $acourse->id);
$coursecontext = $acourse->context;
} else {
$coursecontext = get_context_instance(CONTEXT_COURSE, $acourse->id);
}
$count++; $count++;
$up = ($count > 1 || !$atfirstpage); $up = ($count > 1 || !$atfirstpage);

View File

@ -12,7 +12,7 @@ class delete_category_form extends moodleform {
$mform =& $this->_form; $mform =& $this->_form;
$category = $this->_customdata; $category = $this->_customdata;
ensure_context_subobj_present($category, CONTEXT_COURSECAT); $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
$this->_category = $category; $this->_category = $category;
/// Check permissions, to see if it OK to give the option to delete /// Check permissions, to see if it OK to give the option to delete
@ -26,7 +26,8 @@ class delete_category_form extends moodleform {
$checkcat = array_pop($tocheck); $checkcat = array_pop($tocheck);
$childcategoryids[] = $checkcat->id; $childcategoryids[] = $checkcat->id;
$tocheck = $tocheck + get_child_categories($checkcat->id); $tocheck = $tocheck + get_child_categories($checkcat->id);
if ($candeletecontent && !has_capability('moodle/category:manage', $checkcat->context)) { $chcontext = get_context_instance(CONTEXT_COURSECAT, $checkcat->id);
if ($candeletecontent && !has_capability('moodle/category:manage', $chcontext)) {
$candeletecontent = false; $candeletecontent = false;
} }
} }
@ -47,7 +48,7 @@ class delete_category_form extends moodleform {
} }
/// Are there any questions in the question bank here? /// Are there any questions in the question bank here?
$containsquestions = question_context_has_any_questions($category->context); $containsquestions = question_context_has_any_questions($categorycontext);
/// Get the list of categories we might be able to move to. /// Get the list of categories we might be able to move to.
$testcaps = array(); $testcaps = array();

View File

@ -105,7 +105,7 @@
$DB->update_record('course', $editordata); $DB->update_record('course', $editordata);
// assign default role to creator if not already having permission to manage course assignments // assign default role to creator if not already having permission to manage course assignments
if (!has_capability('moodle/course:view', $context) or !has_capability('moodle/role:assign', $context)) { if (!is_viewing($context, NULL, 'moodle/role:assign') and !is_enrolled($context, NULL, 'moodle/role:assign')) {
role_assign($CFG->creatornewroleid, $USER->id, 0, $context->id); role_assign($CFG->creatornewroleid, $USER->id, 0, $context->id);
} }

View File

@ -35,7 +35,7 @@ class course_edit_form extends moodleform {
// users with metacourse manage permission are exception // users with metacourse manage permission are exception
// please note that we do not need exact results - anything unexpected here prevents metacourse // please note that we do not need exact results - anything unexpected here prevents metacourse
$managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id'); $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
$enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext); $enrolroles = get_roles_with_capability('moodle/course:participate', CAP_ALLOW, $coursecontext);
if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) { if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
foreach($users as $user) { foreach($users as $user) {
if (!isset($managers[$user->id])) { if (!isset($managers[$user->id])) {

View File

@ -38,7 +38,7 @@ if ($loginasguest !== 0) {
} }
$PAGE->set_url($url); $PAGE->set_url($url);
if (!isloggedin()) { if (!isloggedin() or isguestuser()) {
// do not use require_login here because we are usually comming from it // do not use require_login here because we are usually comming from it
redirect(get_login_url()); redirect(get_login_url());
} }
@ -66,7 +66,7 @@ load_all_capabilities();
/// thus got to this script by mistake. This might occur if enrolments /// thus got to this script by mistake. This might occur if enrolments
/// changed during this session or something /// changed during this session or something
if (has_capability('moodle/course:view', $context) and !has_capability('moodle/legacy:guest', $context, NULL, false)) { if (has_capability('moodle/course:participate', $context)) {
if (!empty($SESSION->wantsurl)) { if (!empty($SESSION->wantsurl)) {
$destination = $SESSION->wantsurl; $destination = $SESSION->wantsurl;
unset($SESSION->wantsurl); unset($SESSION->wantsurl);

View File

@ -84,7 +84,7 @@ final class course_external extends moodle_external {
*/ */
static function get_courses($params) { static function get_courses($params) {
global $USER; global $USER;
if (has_capability('moodle/course:view', get_context_instance(CONTEXT_SYSTEM))) { if (has_capability('moodle/course:participate', get_context_instance(CONTEXT_SYSTEM))) {
$courses = array(); $courses = array();
foreach ($params as $param) { foreach ($params as $param) {
$course = new stdClass(); $course = new stdClass();
@ -681,7 +681,7 @@ final class course_external extends moodle_external {
*/ */
static function get_course_modules($params, $type=null) { static function get_course_modules($params, $type=null) {
global $DB; global $DB;
if (has_capability('moodle/course:view', get_context_instance(CONTEXT_SYSTEM))) { if (has_capability('moodle/course:participate', get_context_instance(CONTEXT_SYSTEM))) {
$modules = array(); $modules = array();
foreach ($params as $courseparams) { foreach ($params as $courseparams) {
if (array_key_exists('id', $courseparams)) { if (array_key_exists('id', $courseparams)) {

View File

@ -61,13 +61,12 @@
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', $course->id); $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', $course->id);
echo format_text($course->summary, $course->summaryformat, NULL, $course->id); echo format_text($course->summary, $course->summaryformat, NULL, $course->id);
if ($managerroles = get_config('', 'coursemanager')) { if (!empty($CFG->coursemanager)) {
$coursemanagerroles = split(',', $managerroles); $coursemanagerroles = explode(',', $CFG->coursemanager);
foreach ($coursemanagerroles as $roleid) { foreach ($coursemanagerroles as $roleid) {
$role = $DB->get_record('role', array('id'=>$roleid)); $role = $DB->get_record('role', array('id'=>$roleid));
$canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
$roleid = (int) $roleid; $roleid = (int) $roleid;
if ($users = get_role_users($roleid, $context, true, '', 'u.lastname ASC', $canseehidden)) { if ($users = get_role_users($roleid, $context, true)) {
foreach ($users as $teacher) { foreach ($users as $teacher) {
$fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context)); $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
$namesarray[] = format_string(role_get_name($role, $context)).': <a href="'.$CFG->wwwroot.'/user/view.php?id='. $namesarray[] = format_string(role_get_name($role, $context)).': <a href="'.$CFG->wwwroot.'/user/view.php?id='.

View File

@ -889,7 +889,7 @@ function print_recent_activity($course) {
$timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
if (!has_capability('moodle/legacy:guest', $context, NULL, false)) { if (!isguestuser()) {
if (!empty($USER->lastcourseaccess[$course->id])) { if (!empty($USER->lastcourseaccess[$course->id])) {
if ($USER->lastcourseaccess[$course->id] > $timestart) { if ($USER->lastcourseaccess[$course->id] > $timestart) {
$timestart = $USER->lastcourseaccess[$course->id]; $timestart = $USER->lastcourseaccess[$course->id];
@ -1184,7 +1184,7 @@ function course_set_display($courseid, $display=0) {
$display = 0; $display = 0;
} }
if (empty($USER->id) or $USER->username == 'guest') { if (!isloggedin() or isguestuser()) {
//do not store settings in db for guests //do not store settings in db for guests
} else if ($DB->record_exists("course_display", array("userid" => $USER->id, "course"=>$courseid))) { } else if ($DB->record_exists("course_display", array("userid" => $USER->id, "course"=>$courseid))) {
$DB->set_field("course_display", "display", $display, array("userid"=>$USER->id, "course"=>$courseid)); $DB->set_field("course_display", "display", $display, array("userid"=>$USER->id, "course"=>$courseid));
@ -2036,7 +2036,7 @@ function print_course_request_buttons($systemcontext) {
if (empty($CFG->enablecourserequests)) { if (empty($CFG->enablecourserequests)) {
return; return;
} }
if (isloggedin() && !isguestuser() && !has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) { if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
/// Print a button to request a new course /// Print a button to request a new course
echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get'); echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
} }
@ -2121,8 +2121,8 @@ function print_courses($category) {
if ($courses) { if ($courses) {
echo '<ul class="unlist">'; echo '<ul class="unlist">';
foreach ($courses as $course) { foreach ($courses as $course) {
if ($course->visible == 1 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
|| has_capability('moodle/course:viewhiddencourses',$course->context)) { if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
echo '<li>'; echo '<li>';
print_course($course); print_course($course);
echo "</li>\n"; echo "</li>\n";
@ -2151,11 +2151,7 @@ function print_courses($category) {
function print_course($course, $highlightterms = '') { function print_course($course, $highlightterms = '') {
global $CFG, $USER, $DB, $OUTPUT; global $CFG, $USER, $DB, $OUTPUT;
if (isset($course->context)) { $context = get_context_instance(CONTEXT_COURSE, $course->id);
$context = $course->context;
} else {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
}
// Rewrite file URLs so that they are correct // Rewrite file URLs so that they are correct
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', $course->id); $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)) { if (!empty($CFG->coursemanager)) {
$managerroles = split(',', $CFG->coursemanager); $managerroles = split(',', $CFG->coursemanager);
$canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
$namesarray = array(); $namesarray = array();
if (isset($course->managers)) { if (isset($course->managers)) {
if (count($course->managers)) { if (count($course->managers)) {
@ -2194,27 +2189,20 @@ function print_course($course, $highlightterms = '') {
} }
$usersshown[] = $ra->user->id; $usersshown[] = $ra->user->id;
if ($ra->hidden == 0 || $canseehidden) { $fullname = fullname($ra->user, $canviewfullnames);
$fullname = fullname($ra->user, $canviewfullnames);
if ($ra->hidden == 1) {
$status = " <img src=\"" . $OUTPUT->pix_url('t/show') . "\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
} else {
$status = '';
}
if (isset($aliasnames[$ra->roleid])) { if (isset($aliasnames[$ra->roleid])) {
$ra->rolename = $aliasnames[$ra->roleid]->name; $ra->rolename = $aliasnames[$ra->roleid]->name;
}
$namesarray[] = format_string($ra->rolename)
. ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
. $fullname . '</a>' . $status;
} }
$namesarray[] = format_string($ra->rolename)
. ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
. $fullname . '</a>';
} }
} }
} else { } else {
$rusers = get_role_users($managerroles, $context, $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)) { if (is_array($rusers) && count($rusers)) {
$canviewfullnames = has_capability('moodle/site:viewfullnames', $context); $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
@ -2268,7 +2256,7 @@ function print_course($course, $highlightterms = '') {
function print_my_moodle() { function print_my_moodle() {
global $USER, $CFG, $DB, $OUTPUT; global $USER, $CFG, $DB, $OUTPUT;
if (empty($USER->id)) { if (!isloggedin() or isguestuser()) {
print_error('nopermissions', '', '', 'See My Moodle'); print_error('nopermissions', '', '', 'See My Moodle');
} }
@ -3402,43 +3390,6 @@ function update_course($data) {
return false; 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) { function get_course_by_id ($id) {
global $DB; global $DB;
return $DB->get_record('course', array('id' => $id)); return $DB->get_record('course', array('id' => $id));
@ -3759,8 +3710,8 @@ class course_request {
if ($course->id) { if ($course->id) {
$course = $DB->get_record('course', array('id' => $course->id)); $course = $DB->get_record('course', array('id' => $course->id));
blocks_add_default_course_blocks($course); blocks_add_default_course_blocks($course);
$course->context = get_context_instance(CONTEXT_COURSE, $course->id); $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
role_assign($CFG->creatornewroleid, $this->properties->requester, 0, $course->context->id); // assing teacher role role_assign($CFG->creatornewroleid, $this->properties->requester, 0, $coursecontext->id); // assing teacher role
if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
// if we're all or requested we're ok. // if we're all or requested we're ok.
$allowedmods = explode(',',$CFG->defaultallowedmodules); $allowedmods = explode(',',$CFG->defaultallowedmodules);
@ -3823,8 +3774,9 @@ class course_request {
$fs = get_file_storage(); $fs = get_file_storage();
$files = $fs->get_area_files(self::summary_editor_context()->id, self::summary_editor_filearea(), $this->properties->id); $files = $fs->get_area_files(self::summary_editor_context()->id, self::summary_editor_filearea(), $this->properties->id);
foreach ($files as $file) { foreach ($files as $file) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
if (!$file->is_directory()) { 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); $fs->create_file_from_storedfile($filerecord, $file);
} }
} }

View File

@ -49,19 +49,19 @@
require_login(); require_login();
if (has_capability('moodle/user:loginas', $systemcontext)) { if (has_capability('moodle/user:loginas', $systemcontext)) {
if (has_capability('moodle/site:doanything', $systemcontext, $userid, false)) { if (is_siteadmin($userid)) {
print_error('nologinas'); print_error('nologinas');
} }
$context = $systemcontext; $context = $systemcontext;
} else { } else {
require_login($course); require_login($course);
require_capability('moodle/user:loginas', $coursecontext); require_capability('moodle/user:loginas', $coursecontext);
if (!has_capability('moodle/course:view', $coursecontext, $userid, false)) { if (is_siteadmin($userid)) {
print_error('usernotincourse');
}
if (has_capability('moodle/site:doanything', $coursecontext, $userid, false)) {
print_error('nologinas'); print_error('nologinas');
} }
if (!is_enrolled($coursecontext, $userid)) {
print_error('usernotincourse');
}
$context = $coursecontext; $context = $coursecontext;
} }

View File

@ -52,14 +52,14 @@ class recent_form extends moodleform {
if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS) { if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS) {
$groups = groups_get_user_groups($COURSE->id); $groups = groups_get_user_groups($COURSE->id);
$groups = $groups[0]; $group = $groups[0];
} else { } else {
$groups = ''; $group = '';
} }
if ($courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.id, u.firstname, u.lastname', 'lastname ASC, firstname DESC', '', '', $groups)) { if ($enrolled = get_enrolled_users($context, null, $group, user_picture::fields('u'))) {
foreach ($courseusers as $courseuser) { foreach ($enrolled as $euser) {
$options[$courseuser->id] = fullname($courseuser, $viewfullnames); $options[$euser->id] = fullname($euser, $viewfullnames);
} }
} }
$mform->addElement('select', 'user', get_string('participants'), $options); $mform->addElement('select', 'user', get_string('participants'), $options);

View File

@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',
@ -45,7 +45,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',
@ -58,7 +58,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',

View File

@ -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 looking at a different host, we're interested in all our site users
if ($hostid == $CFG->mnet_localhost_id && $course->id != SITEID) { 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 { } else {
// this may be a lot of users :-( // this may be a lot of users :-(
$courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber', $limitfrom, $limitnum); $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(); $users = array();
if ($course->id != SITEID) { 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 { } else {
// this may be a lot of users :-( // this may be a lot of users :-(
$courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber'); $courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber');

View File

@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',

View File

@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',

View File

@ -101,6 +101,7 @@
} }
$roleoptions = array(); $roleoptions = array();
// TODO: we need a new list of roles that are visible here
if ($roles = get_roles_used_in_context($context)) { if ($roles = get_roles_used_in_context($context)) {
foreach ($roles as $r) { foreach ($roles as $r) {
$roleoptions[$r->id] = $r->name; $roleoptions[$r->id] = $r->name;

View File

@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',

View File

@ -32,7 +32,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
), ),
'clonepermissionsfrom' => 'moodle/site:viewreports', 'clonepermissionsfrom' => 'moodle/site:viewreports',

View File

@ -225,11 +225,7 @@
if (!$adminediting) { if (!$adminediting) {
foreach ($courses as $course) { foreach ($courses as $course) {
if (isset($course->context)) { $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$coursecontext = $course->context;
} else {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
}
$course->summary .= "<br /><p class=\"category\">"; $course->summary .= "<br /><p class=\"category\">";
$course->summary .= "$strcategory: <a href=\"category.php?id=$course->category\">"; $course->summary .= "$strcategory: <a href=\"category.php?id=$course->category\">";
@ -253,11 +249,7 @@
foreach ($courses as $course) { foreach ($courses as $course) {
if (isset($course->context)) { $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$coursecontext = $course->context;
} else {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
}
$linkcss = $course->visible ? "" : " class=\"dimmed\" "; $linkcss = $course->visible ? "" : " class=\"dimmed\" ";

View File

@ -54,7 +54,7 @@ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$personalcontext = get_context_instance(CONTEXT_USER, $user->id); $personalcontext = get_context_instance(CONTEXT_USER, $user->id);
require_login(); 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 ;-) // do not require parents to be enrolled in courses ;-)
$PAGE->set_course($course); $PAGE->set_course($course);
} else { } else {

View File

@ -7,7 +7,7 @@ $capabilities = array(
'captype' => 'write', 'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM, 'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -16,7 +16,7 @@ $capabilities = array(
'captype' => 'write', 'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM, 'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -31,7 +31,7 @@
/// Only SITE users can access to this page /// Only SITE users can access to this page
require_login(); // Don't use $courseid! User may want to see old orders. 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'); print_error('noguest');
} }

View File

@ -197,12 +197,10 @@ function get_access_icons($course) {
if ($fields[1] == "student") { 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) { foreach ($teachers as $u) {
if (!$u->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) { $teacher = $u;
$teacher = $u;
break;
}
} }
} }
@ -233,22 +231,19 @@ function get_access_icons($course) {
if (!empty($CFG->enrol_mailteachers) && $teachers) { if (!empty($CFG->enrol_mailteachers) && $teachers) {
foreach($teachers as $teacher) { foreach($teachers as $teacher) {
$a->course = "$course->fullname";
$a->user = fullname($user);
if (!$u->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) { $eventdata = new object();
$a->course = "$course->fullname"; $eventdata->modulename = 'moodle';
$a->user = fullname($user); $eventdata->userfrom = $user;
$eventdata->userto = $teacher;
$eventdata = new object(); $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
$eventdata->modulename = 'moodle'; $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
$eventdata->userfrom = $user; $eventdata->fullmessageformat = FORMAT_PLAIN;
$eventdata->userto = $teacher; $eventdata->fullmessagehtml = '';
$eventdata->subject = get_string("enrolmentnew", '', $course->shortname); $eventdata->smallmessage = '';
$eventdata->fullmessage = get_string('enrolmentnewuser', '', $a); message_send($eventdata);
$eventdata->fullmessageformat = FORMAT_PLAIN;
$eventdata->fullmessagehtml = '';
$eventdata->smallmessage = '';
message_send($eventdata);
}
} }
} }
} }

View File

@ -62,7 +62,7 @@ function print_entry($course) {
if ($course->password == '') { // no password, so enrol 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()); add_to_log($course->id, 'course', 'guest', 'view.php?id='.$course->id, getremoteaddr());
} else if (empty($_GET['confirm']) && empty($_GET['cancel'])) { } 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 * A bit clunky because I didn't want to change the standard strings
*/ */
function print_enrolmentkeyfrom($course) { function print_enrolmentkeyfrom($course) {
global $CFG; global $CFG, $USER;
global $USER;
$context = get_context_instance(CONTEXT_SYSTEM); $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) // if a keyholder role is defined we list teachers in that role (if any exist)
$contactslisted = false; $contactslisted = false;
$canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
if (!empty($CFG->enrol_manual_keyholderrole)) { 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 // guest user has a slightly different message
if ($guest) { if (isguestuser()) {
print_string('enrolmentkeyfromguest', '', ':<br />' ); print_string('enrolmentkeyfromguest', '', ':<br />' );
} }
else { else {
@ -444,7 +441,7 @@ function print_enrolmentkeyfrom($course) {
} }
// guest user has a slightly different message // guest user has a slightly different message
if ($guest) { if (isguestuser()) {
print_string('enrolmentkeyfromguest', '', $teachername ); print_string('enrolmentkeyfromguest', '', $teachername );
} }
else { else {

View File

@ -25,7 +25,7 @@
$destination = "$CFG->wwwroot/course/view.php?id=$course->id"; $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)); redirect($destination, get_string('paymentthanks', '', $course->fullname));
} else { /// Somehow they aren't enrolled yet! :-( } else { /// Somehow they aren't enrolled yet! :-(

View File

@ -13,17 +13,11 @@
/// options to be filtered (In HTML form). /// options to be filtered (In HTML form).
class censor_filter extends moodle_text_filter { class censor_filter extends moodle_text_filter {
private function _canseecensor() { private function _canseecensor() {
$cansee = false; return is_siteadmin(); //TODO: add proper access control
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (has_capability('moodle/site:doanything', $context)) {
$cansee = true;
}
return $cansee;
} }
function hash(){ function hash(){
$cap = "mod/filter:censor"; $cap = "mod/filter:censor";
$context = get_context_instance(CONTEXT_SYSTEM, SITEID); if (is_siteadmin()) { //TODO: add proper access control
if (has_capability('moodle/site:doanything', $context)) {
$cap = "mod/filter:seecensor"; $cap = "mod/filter:seecensor";
} }
return $cap; return $cap;

View File

@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -33,7 +33,7 @@ $capabilities = array(
'captype' => 'read', 'captype' => 'read',
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -22,7 +22,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )
); );

View File

@ -22,7 +22,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
@ -30,7 +30,7 @@ $capabilities = array(
'captype' => 'write', 'captype' => 'write',
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )
); );

View File

@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )
); );

View File

@ -24,7 +24,7 @@ $capabilities = array(
'legacy' => array( 'legacy' => array(
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -23,7 +23,7 @@ $capabilities = array(
'contextlevel' => CONTEXT_COURSE, 'contextlevel' => CONTEXT_COURSE,
'legacy' => array( 'legacy' => array(
'student' => CAP_ALLOW, 'student' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
) )

View File

@ -25,7 +25,7 @@ $capabilities = array(
'student' => CAP_ALLOW, 'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW, 'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW,
'admin' => CAP_ALLOW 'manager' => CAP_ALLOW
) )
), ),
); );

View File

@ -90,8 +90,7 @@ if ($currentmembers) {
$coursemanagerroles = split(',', $managerroles); $coursemanagerroles = split(',', $managerroles);
foreach ($coursemanagerroles as $roleid) { foreach ($coursemanagerroles as $roleid) {
$role = $DB->get_record('role', array('id'=>$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');
$managers = get_role_users($roleid, $context, true, 'u.id', 'u.id ASC', $canseehidden);
} }
} }
} else { } else {

View File

@ -42,17 +42,8 @@ $error = '';
/// Get applicable roles /// Get applicable roles
$rolenames = array(); $rolenames = array();
if ($roles = get_roles_used_in_context($context, true)) { if ($roles = get_profile_roles($context)) {
$canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
$doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext);
foreach ($roles as $role) { 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 $rolenames[$role->id] = strip_tags(role_get_name($role, $context)); // Used in menus etc later on
} }
} }

View File

@ -368,8 +368,10 @@ class moodle_group_external extends external_api {
require_capability('moodle/course:managegroups', $context); require_capability('moodle/course:managegroups', $context);
// now make sure user is enrolled in course - this is mandatory requirement, // now make sure user is enrolled in course - this is mandatory requirement,
// unfortunately this is extermely slow // unfortunately this is slow
require_capability('moodle/course:view', $context, $userid, false); if (!is_enrolled($context, $userid)) {
throw new invalid_parameter_exception('Only enrolled users may be members of groups');
}
groups_add_member($group, $user); groups_add_member($group, $user);
} }

View File

@ -20,21 +20,18 @@ $userid = optional_param('user', false, PARAM_INT);
$action = groups_param_action(); $action = groups_param_action();
// Support either single group= parameter, or array groups[] // Support either single group= parameter, or array groups[]
if ($groupid) { if ($groupid) {
$groupids=array($groupid); $groupids = array($groupid);
} else { } else {
$groupids = optional_param('groups', array(), PARAM_INT); $groupids = optional_param('groups', array(), PARAM_INT);
} }
$singlegroup=count($groupids) == 1; $singlegroup = (count($groupids) == 1);
$returnurl = $CFG->wwwroot.'/group/index.php?id='.$courseid; $returnurl = $CFG->wwwroot.'/group/index.php?id='.$courseid;
// Get the course information so we can print the header and // Get the course information so we can print the header and
// check the course id is valid // check the course id is valid
if (!$course = $DB->get_record('course', array('id'=>$courseid))) { $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
$success = false;
print_error('invalidcourse'); //'The course ID is invalid'
}
$url = new moodle_url('/group/index.php', array('id'=>$courseid)); $url = new moodle_url('/group/index.php', array('id'=>$courseid));
if ($userid) { if ($userid) {
@ -48,19 +45,19 @@ $PAGE->set_url($url);
// Make sure that the user has permissions to manage groups. // Make sure that the user has permissions to manage groups.
require_login($course); require_login($course);
$context = get_context_instance(CONTEXT_COURSE, $courseid); $context = get_context_instance(CONTEXT_COURSE, $course->id);
if (! has_capability('moodle/course:managegroups', $context)) { if (!has_capability('moodle/course:managegroups', $context)) {
redirect(); //"group.php?id=$course->id"); // Not allowed to see all groups redirect('/course/view.php', array('id'=>$course->id)); // Not allowed to manage all groups
} }
// Check for multiple/no group errors // Check for multiple/no group errors
if(!$singlegroup) { if (!$singlegroup) {
switch($action) { switch($action) {
case 'ajax_getmembersingroup': case 'ajax_getmembersingroup':
case 'showgroupsettingsform': case 'showgroupsettingsform':
case 'showaddmembersform': case 'showaddmembersform':
case 'updatemembers': case 'updatemembers':
print_error('errorselectone','group',$returnurl); print_error('errorselectone', 'group', $returnurl);
} }
} }
@ -70,41 +67,41 @@ switch ($action) {
case 'ajax_getmembersingroup': case 'ajax_getmembersingroup':
$roles = array(); $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) { foreach($groupmemberroles as $roleid=>$roledata) {
$shortroledata=new StdClass; $shortroledata = new stdClass();
$shortroledata->name=$roledata->name; $shortroledata->name = $roledata->name;
$shortroledata->users=array(); $shortroledata->users = array();
foreach($roledata->users as $member) { foreach($roledata->users as $member) {
$shortmember=new StdClass; $shortmember = new stdClass();
$shortmember->id=$member->id; $shortmember->id = $member->id;
$shortmember->name=fullname($member, true); $shortmember->name = fullname($member, true);
$shortroledata->users[]=$shortmember; $shortroledata->users[] = $shortmember;
} }
$roles[]=$shortroledata; $roles[] = $shortroledata;
} }
} }
echo json_encode($roles); echo json_encode($roles);
die; // Client side JavaScript takes it from here. die; // Client side JavaScript takes it from here.
case 'deletegroup': case 'deletegroup':
if(count($groupids)==0) { if (count($groupids) == 0) {
print_error('errorselectsome','group',$returnurl); print_error('errorselectsome','group',$returnurl);
} }
$groupidlist=implode(',',$groupids); $groupidlist = implode(',', $groupids);
redirect('delete.php?courseid='.$courseid.'&groups='.$groupidlist); redirect(new moodle_url('/group/delete.php', array('courseid'=>$courseid, 'groups'=>$groupidlist)));
break; break;
case 'showcreateorphangroupform': case 'showcreateorphangroupform':
redirect('group.php?courseid='.$courseid); redirect(new moodle_url('/group/group.php', array('courseid'=>$courseid)));
break; break;
case 'showautocreategroupsform': case 'showautocreategroupsform':
redirect('autogroup.php?courseid='.$courseid); redirect(new moodle_url('/group/autogroup.php', array('courseid'=>$courseid)));
break; break;
case 'showgroupsettingsform': case 'showgroupsettingsform':
redirect('group.php?courseid='.$courseid.'&amp;id='.$groupids[0]); redirect(new moodle_url('/group/group.php', array('courseid'=>$courseid, 'id'=>$groupids[0])));
break; break;
case 'updategroups': //Currently reloading. case 'updategroups': //Currently reloading.
@ -114,17 +111,15 @@ switch ($action) {
break; break;
case 'showaddmembersform': case 'showaddmembersform':
redirect('members.php?group='.$groupids[0]); redirect(new moodle_url('/group/members.php', array('group'=>$groupids[0])));
break; break;
case 'updatemembers': //Currently reloading. case 'updatemembers': //Currently reloading.
break; break;
default: //ERROR. default: //ERROR.
if (debugging()) { print_error('unknowaction', '', $returnurl);
print_error('unknowaction', '', $returnurl);
break; break;
}
} }
// Print the page and form // Print the page and form

View File

@ -40,7 +40,7 @@ function groups_add_member($grouporid, $userorid) {
} }
//check if the user a participant of the group course //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; return false;
} }
@ -487,25 +487,12 @@ function groups_delete_groupings($courseid, $showfeedback=false) {
* @return Array of role ID integers, or false if error/none. * @return Array of role ID integers, or false if error/none.
*/ */
function groups_get_possible_roles($context) { function groups_get_possible_roles($context) {
$capability = 'moodle/course:view'; $capability = 'moodle/course:participate';
$doanything = false;
// find all possible "student" roles // find all possible "student" roles
if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) { 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(); $validroleids = array();
foreach ($possibleroles as $possiblerole) { 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 ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
$validroleids[] = $possiblerole->id; $validroleids[] = $possiblerole->id;
@ -529,64 +516,30 @@ function groups_get_possible_roles($context) {
* @param string $orderby The colum to sort users by * @param string $orderby The colum to sort users by
* @return array An array of the users * @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; global $DB;
$context = get_context_instance(CONTEXT_COURSE, $courseid); $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 // we are looking for all users with this role assigned in this context or higher
if ($usercontexts = get_parent_contexts($context)) { $listofcontexts = get_related_contexts_string($context);
$listofcontexts = 'IN ('.implode(',', $usercontexts).')';
} else {
$listofcontexts = '='.$sitecontext->id.')'; // must be site
}
list($esql, $params) = get_enrolled_sql($context);
if ($roleid) { if ($roleid) {
$selectrole = "AND r.roleid = :roleid";
$params['roleid'] = $roleid; $params['roleid'] = $roleid;
$where = "WHERE u.id IN (SELECT userid
FROM {role_assignments}
WHERE roleid = :roleid AND contextid $listofcontexts)";
} else { } else {
$selectrole = ""; $where = "";
} }
$sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
FROM {user} u FROM {user} u
JOIN {role_assignments} r on u.id=r.userid JOIN ($esql) e ON e.id = u.id
WHERE (r.contextid = :contextid OR r.contextid $listofcontexts) $where
AND u.deleted = 0 AND u.username != 'guest'
$selectrole $adminroles
ORDER BY $orderby"; ORDER BY $orderby";
$params['contextid'] = $context->id;
return $DB->get_records_sql($sql, $params); 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 $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 $sort SQL ORDER BY clause, default 'u.lastname ASC'
* @param string $extrawheretest extra SQL conditions ANDed with the existing where clause. * @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 * @return array Complex array as described above
*/ */
function groups_get_members_by_role($groupid, $courseid, $fields='u.*', 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 {user} u ON u.id = gm.userid
JOIN {role_assignments} ra ON ra.userid = u.id JOIN {role_assignments} ra ON ra.userid = u.id
JOIN {role} r ON r.id = ra.roleid JOIN {role} r ON r.id = ra.roleid
WHERE gm.groupid=? WHERE gm.groupid=:mgroupid
AND ra.contextid ".get_related_contexts_string($context). AND ra.contextid ".get_related_contexts_string($context).
$extrawheretest." $extrawheretest."
ORDER BY r.sortorder, $sort"; ORDER BY r.sortorder, $sort";
array_unshift($whereparams, $groupid); $whereparams['mgroupid'] = $groupid;
$rs = $DB->get_recordset_sql($sql, $whereparams); $rs = $DB->get_recordset_sql($sql, $whereparams);
return groups_calculate_role_people($rs, $context); return groups_calculate_role_people($rs, $context);

View File

@ -14,33 +14,26 @@ require_once($CFG->dirroot . '/user/selector/lib.php');
require_once($CFG->dirroot . '/course/lib.php'); require_once($CFG->dirroot . '/course/lib.php');
$groupid = required_param('group', PARAM_INT); $groupid = required_param('group', PARAM_INT);
$cancel = optional_param('cancel', false, PARAM_BOOL);
if (!$group = $DB->get_record('groups', array('id'=>$groupid))) { $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
print_error('invalidgroupid'); $course = $DB->get_record('course', array('id'=>$group->courseid), '*', MUST_EXIST);
}
if (!$course = $DB->get_record('course', array('id'=>$group->courseid))) {
print_error('invalidcourse');
}
$courseid = $course->id;
$PAGE->set_url('/groups/members.php', array('id'=>$groupid)); $PAGE->set_url('/groups/members.php', array('id'=>$groupid));
require_login($course); require_login($course);
$context = get_context_instance(CONTEXT_COURSE, $courseid); $context = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:managegroups', $context); 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); redirect($returnurl);
} }
$groupmembersselector = new group_members_selector('removeselect', $groupmembersselector = new group_members_selector('removeselect', array('groupid' => $groupid, 'courseid' => $course->id));
array('groupid' => $groupid, 'courseid' => $course->id));
$groupmembersselector->set_extra_fields(array()); $groupmembersselector->set_extra_fields(array());
$potentialmembersselector = new group_non_members_selector('addselect', $potentialmembersselector = new group_non_members_selector('addselect', array('groupid' => $groupid, 'courseid' => $course->id));
array('groupid' => $groupid, 'courseid' => $course->id));
$potentialmembersselector->set_extra_fields(array()); $potentialmembersselector->set_extra_fields(array());
if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) { 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->yui2_lib('connection');
$PAGE->requires->js('/group/clientlib.js'); $PAGE->requires->js('/group/clientlib.js');
$PAGE->navbar->add($strparticipants, new moodle_url('/user/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'=>$courseid))); $PAGE->navbar->add($strgroups, new moodle_url('/group/index.php', array('id'=>$course->id)));
$PAGE->navbar->add($stradduserstogroup); $PAGE->navbar->add($stradduserstogroup);
/// Print header /// Print header

View File

@ -62,7 +62,7 @@
set_moodle_cookie('nobody'); // To help search for cookies on login page 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); add_to_log(SITEID, 'course', 'view', 'view.php?id='.SITEID, SITEID);
} }
@ -142,7 +142,7 @@
print_error('cannotfindorcreateforum', 'forum'); print_error('cannotfindorcreateforum', 'forum');
} }
if (!empty($USER->id)) { if (isloggedin()) {
$SESSION->fromdiscussion = $CFG->wwwroot; $SESSION->fromdiscussion = $CFG->wwwroot;
$subtext = ''; $subtext = '';
if (forum_is_subscribed($USER->id, $newsforum)) { if (forum_is_subscribed($USER->id, $newsforum)) {

View File

@ -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['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['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['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['configproxybypass'] = 'Comma separated list of (partial) hostnames or IPs that should bypass proxy (e.g., 192.168., .mydomain.com)';
$string['configproxyhost'] = 'If this <b>server</b> needs to use a proxy computer (eg a firewall) to access the Internet, then provide the proxy hostname here. Otherwise leave it blank.'; $string['configproxyhost'] = 'If this <b>server</b> 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).'; $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['profilemenutoofewoptions'] = 'You must provide at least 2 options';
$string['profilename'] = 'Name'; $string['profilename'] = 'Name';
$string['profilenofieldsdefined'] = 'No fields have been defined'; $string['profilenofieldsdefined'] = 'No fields have been defined';
$string['profileroles'] = 'Profile visible roles';
$string['profileshortname'] = 'Short name (must be unique)'; $string['profileshortname'] = 'Short name (must be unique)';
$string['profileshortnamenotunique'] = 'This short name is already in use'; $string['profileshortnamenotunique'] = 'This short name is already in use';
$string['profilesignup'] = 'Display on signup page?'; $string['profilesignup'] = 'Display on signup page?';

View File

@ -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['allowroletoswitch'] = 'Allow users with role $a->fromrole to switch roles to the role $a->targetrole';
$string['allowswitch'] = 'Allow role switches'; $string['allowswitch'] = 'Allow role switches';
$string['allsiteusers'] = 'All site users'; $string['allsiteusers'] = 'All site users';
$string['archetype'] = 'Role archetype';
$string['assignanotherrole'] = 'Assign another role'; $string['assignanotherrole'] = 'Assign another role';
$string['assignerror'] = 'Error while assigning the role $a->role to user $a->user.'; $string['assignerror'] = 'Error while assigning the role $a->role to user $a->user.';
$string['assignrolenameincontext'] = 'Assign role \'$a->role\' in $a->context'; $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['assignglobalroles'] = 'Assign system roles';
$string['assignmentcontext'] = 'Assignment context'; $string['assignmentcontext'] = 'Assignment context';
$string['assignmentoptions'] = 'Assignment options'; $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['backtoallroles'] = 'Back to the list of all roles';
$string['backup:backupcourse'] = 'Backup courses'; $string['backup:backupcourse'] = 'Backup courses';
$string['backup:downloadfile'] = 'Download files from backup areas'; $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:delete'] = 'Delete comments';
$string['comment:post'] = 'Post comments'; $string['comment:post'] = 'Post comments';
$string['comment:view'] = 'Read comments'; $string['comment:view'] = 'Read comments';
$string['confirmaddadmin'] = 'Do you really want to add user <strong>$a</strong> as new site administrator?';
$string['confirmdeladmin'] = 'Do you really want to remove user <strong>$a</strong> from the list of site administrators?';
$string['context'] = 'Context'; $string['context'] = 'Context';
$string['course:activityvisibility'] = 'Hide/show activities'; $string['course:activityvisibility'] = 'Hide/show activities';
$string['course:bulkmessaging'] = 'Send a message to many people'; $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:managegroups'] = 'Manage groups';
$string['course:managemetacourse'] = 'Manage metacourse'; $string['course:managemetacourse'] = 'Manage metacourse';
$string['course:managescales'] = 'Manage scales'; $string['course:managescales'] = 'Manage scales';
$string['course:participate'] = 'Participate in courses';
$string['course:request'] = 'Request new courses'; $string['course:request'] = 'Request new courses';
$string['course:reset'] = 'Reset course'; $string['course:reset'] = 'Reset course';
$string['course:sectionvisibility'] = 'Control section visibility'; $string['course:sectionvisibility'] = 'Control section visibility';
$string['course:setcurrentsection'] = 'Set current section'; $string['course:setcurrentsection'] = 'Set current section';
$string['course:update'] = 'Update course settings'; $string['course:update'] = 'Update course settings';
$string['course:useremail'] = 'Enable/disable email address'; $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:viewhiddenactivities'] = 'View hidden activities';
$string['course:viewhiddencourses'] = 'View hidden courses'; $string['course:viewhiddencourses'] = 'View hidden courses';
$string['course:viewhiddensections'] = 'View hidden sections'; $string['course:viewhiddensections'] = 'View hidden sections';
@ -110,14 +122,16 @@ $string['errorbadrolename'] = 'Incorrect role name';
$string['errorbadroleshortname'] = 'Incorrect role short name'; $string['errorbadroleshortname'] = 'Incorrect role short name';
$string['errorexistsrolename'] = 'Role name already exists'; $string['errorexistsrolename'] = 'Role name already exists';
$string['errorexistsroleshortname'] = 'Role name already exists'; $string['errorexistsroleshortname'] = 'Role name already exists';
$string['existingadmins'] = 'Current site administrators';
$string['existingusers'] = '$a existing users'; $string['existingusers'] = '$a existing users';
$string['explanation'] = 'Explanation'; $string['explanation'] = 'Explanation';
$string['explainpermission'] = 'Explain permission'; $string['explainpermission'] = 'Explain permission';
$string['explainpermissionsinfo'] = '<p>To use this table:</p><ol><li>First look to see if there are any Prohibits. If there are, has_capability will return false.</li><li>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.</li><li>If no cell has different numbers of Prevents and Allows, then has_capability will return false.</li></ol>'; $string['explainpermissionsinfo'] = '<p>To use this table:</p><ol><li>First look to see if there are any Prohibits. If there are, has_capability will return false.</li><li>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.</li><li>If no cell has different numbers of Prevents and Allows, then has_capability will return false.</li></ol>';
$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['extusers'] = 'Existing users';
$string['extusersmatching'] = 'Existing users matching \'$a\''; $string['extusersmatching'] = 'Existing users matching \'$a\'';
$string['filter:manage'] = 'Manage local filter settings'; $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['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['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'; $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['legacytype'] = 'Legacy role type';
$string['listallroles'] = 'List all roles'; $string['listallroles'] = 'List all roles';
$string['localroles'] = 'Locally assigned roles'; $string['localroles'] = 'Locally assigned roles';
$string['manageadmins'] = 'Manage site administrators';
$string['manageroles'] = 'Manage roles'; $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['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['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.'; $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['question:viewmine'] = 'View your own questions';
$string['resetrole'] = 'Reset to defaults'; $string['resetrole'] = 'Reset to defaults';
$string['resetrolenolegacy'] = 'Clear permissions'; $string['resetrolenolegacy'] = 'Clear permissions';
$string['resetrolesure'] = 'Are you sure that you want to reset role \"$a->name ($a->shortname)\" to defaults?<p></p>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?<p></p>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['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:createuser'] = 'Create users on restore';
$string['restore:restorecourse'] = 'Restore courses'; $string['restore:restorecourse'] = 'Restore courses';
@ -226,6 +243,7 @@ $string['selectanotheruser'] = 'Select another user';
$string['selectrole'] = 'Select a role'; $string['selectrole'] = 'Select a role';
$string['showallroles'] = 'Show all roles'; $string['showallroles'] = 'Show all roles';
$string['showthisuserspermissions'] = 'Show this user\'s permissions'; $string['showthisuserspermissions'] = 'Show this user\'s permissions';
$string['siteadministrators'] = 'Site administrators';
$string['site:accessallgroups'] = 'Access all groups'; $string['site:accessallgroups'] = 'Access all groups';
$string['site:approvecourse'] = 'Approve course creation'; $string['site:approvecourse'] = 'Approve course creation';
$string['site:backup'] = 'Backup courses'; $string['site:backup'] = 'Backup courses';

File diff suppressed because it is too large Load Diff

View File

@ -969,7 +969,7 @@ class admin_externalpage implements part_of_admin_tree {
global $CFG; global $CFG;
$context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context; $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
foreach($this->req_capability as $cap) { foreach($this->req_capability as $cap) {
if (is_valid_capability($cap) and has_capability($cap, $context)) { if (has_capability($cap, $context)) {
return true; return true;
} }
} }
@ -1144,7 +1144,7 @@ class admin_settingpage implements part_of_admin_tree {
global $CFG; global $CFG;
$context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context; $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
foreach($this->req_capability as $cap) { foreach($this->req_capability as $cap) {
if (is_valid_capability($cap) and has_capability($cap, $context)) { if (has_capability($cap, $context)) {
return true; return true;
} }
} }
@ -3732,9 +3732,8 @@ class admin_setting_pickroles extends admin_setting_configmulticheckbox {
* @param string $name Name of config variable * @param string $name Name of config variable
* @param string $visiblename Display name * @param string $visiblename Display name
* @param string $description Description * @param string $description Description
* @param array $types Array of capabilities (usually moodle/legacy:something) * @param array $types Array of archetypes which identify
* which identify roles that will be enabled by default. Default is the * roles that will be enabled by default.
* student role
*/ */
public function __construct($name, $visiblename, $description, $types) { public function __construct($name, $visiblename, $description, $types) {
parent::__construct($name, $visiblename, $description, NULL, NULL); parent::__construct($name, $visiblename, $description, NULL, NULL);
@ -3776,8 +3775,8 @@ class admin_setting_pickroles extends admin_setting_configmulticheckbox {
return null; return null;
} }
$result = array(); $result = array();
foreach($this->types as $capability) { foreach($this->types as $archetype) {
if ($caproles = get_roles_with_capability($capability, CAP_ALLOW)) { if ($caproles = get_archetype_roles($archetype)) {
foreach ($caproles as $caprole) { foreach ($caproles as $caprole) {
$result[$caprole->id] = 1; $result[$caprole->id] = 1;
} }
@ -4074,7 +4073,7 @@ class admin_setting_special_gradebookroles extends admin_setting_pickroles {
public function __construct() { public function __construct() {
parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'), parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
get_string('configgradebookroles', '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() { public function __construct() {
parent::__construct('coursemanager', get_string('coursemanager', 'admin'), parent::__construct('coursemanager', get_string('coursemanager', 'admin'),
get_string('configcoursemanager', 'admin'), get_string('configcoursemanager', 'admin'),
array('moodle/legacy:editingteacher')); array('editingteacher'));
} }
} }

View File

@ -307,6 +307,7 @@ class block_manager {
* @return boolean Whether there is anything in this region. * @return boolean Whether there is anything in this region.
*/ */
public function region_has_content($region, $output) { public function region_has_content($region, $output) {
if (!$this->is_known_region($region)) { if (!$this->is_known_region($region)) {
return false; return false;
} }
@ -448,13 +449,14 @@ class block_manager {
list($pagetypepatterntest, $pagetypepatternparams) = list($pagetypepatterntest, $pagetypepatternparams) =
$DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest0000'); $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest0000');
list($ccselect, $ccjoin) = context_instance_preload_sql('b.id', CONTEXT_BLOCK, 'ctx');
$params = array( $params = array(
'subpage1' => $this->page->subpage, 'subpage1' => $this->page->subpage,
'subpage2' => $this->page->subpage, 'subpage2' => $this->page->subpage,
'contextid1' => $context->id, 'contextid1' => $context->id,
'contextid2' => $context->id, 'contextid2' => $context->id,
'pagetype' => $this->page->pagetype, 'pagetype' => $this->page->pagetype,
'contextblock' => CONTEXT_BLOCK,
); );
$sql = "SELECT $sql = "SELECT
bi.id, bi.id,
@ -469,11 +471,8 @@ class block_manager {
COALESCE(bp.visible, 1) AS visible, COALESCE(bp.visible, 1) AS visible,
COALESCE(bp.region, bi.defaultregion) AS region, COALESCE(bp.region, bi.defaultregion) AS region,
COALESCE(bp.weight, bi.defaultweight) AS weight, COALESCE(bp.weight, bi.defaultweight) AS weight,
bi.configdata, bi.configdata
ctx.id AS ctxid, $ccselect
ctx.path AS ctxpath,
ctx.depth AS ctxdepth,
ctx.contextlevel AS ctxlevel
FROM {block_instances} bi FROM {block_instances} bi
JOIN {block} b ON bi.blockname = b.name JOIN {block} b ON bi.blockname = b.name
@ -481,8 +480,7 @@ class block_manager {
AND bp.contextid = :contextid1 AND bp.contextid = :contextid1
AND bp.pagetype = :pagetype AND bp.pagetype = :pagetype
AND bp.subpage = :subpage1 AND bp.subpage = :subpage1
JOIN {context} ctx ON ctx.contextlevel = :contextblock $ccjoin
AND ctx.instanceid = bi.id
WHERE WHERE
$contexttest $contexttest
@ -500,7 +498,7 @@ class block_manager {
$this->birecordsbyregion = $this->prepare_per_region_arrays(); $this->birecordsbyregion = $this->prepare_per_region_arrays();
$unknown = array(); $unknown = array();
foreach ($blockinstances as $bi) { foreach ($blockinstances as $bi) {
$bi = make_context_subobj($bi); context_instance_preload($bi);
if ($this->is_known_region($bi->region)) { if ($this->is_known_region($bi->region)) {
$this->birecordsbyregion[$bi->region][] = $bi; $this->birecordsbyregion[$bi->region][] = $bi;
} else { } else {
@ -824,7 +822,6 @@ class block_manager {
if ($this->movingblock && $lastblock != $this->movingblock) { if ($this->movingblock && $lastblock != $this->movingblock) {
$results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight + 1)); $results[] = new block_move_target($strmoveblockhere, $this->get_move_target_url($region, $lastweight + 1));
} }
return $results; return $results;
} }
@ -890,10 +887,10 @@ class block_manager {
//TODO: please note it is sloppy to pass urls through page parameters!! //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 // 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. // 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 = $this->page->url->out(false);
$return = str_replace($CFG->wwwroot . '/', '', $return); $return = str_replace($CFG->wwwroot . '/', '', $return);
$controls[] = array('url' => $CFG->wwwroot . '/' . $CFG->admin . $controls[] = array('url' => $CFG->wwwroot . '/' . $CFG->admin .
'/roles/assign.php?contextid=' . $block->context->id . '&returnurl=' . urlencode($return), '/roles/assign.php?contextid=' . $block->context->id . '&returnurl=' . urlencode($return),
'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role')); 'icon' => 'i/roles', 'caption' => get_string('assignroles', 'role'));

View File

@ -27,21 +27,22 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
/** /**
* The maximum courses in a category * The maximum courses in a category
* MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer! * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/ */
define('MAX_COURSES_IN_CATEGORY', 10000); define('MAX_COURSES_IN_CATEGORY', 10000);
/** /**
* The maximum number of course categories * The maximum number of course categories
* MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer! * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/ */
define('MAX_COURSE_CATEGORIES', 10000); define('MAX_COURSE_CATEGORIES', 10000);
/** /**
* Number of seconds to wait before updating lastaccess information in DB. * Number of seconds to wait before updating lastaccess information in DB.
*/ */
define('LASTACCESS_UPDATE_SECS', 60); define('LASTACCESS_UPDATE_SECS', 60);
/** /**
* Returns $user object of the main admin user * Returns $user object of the main admin user
@ -51,44 +52,33 @@ define('MAX_COURSE_CATEGORIES', 10000);
* @static object $myadmin * @static object $myadmin
* @return object An associative array representing the admin user. * @return object An associative array representing the admin user.
*/ */
function get_admin () { function get_admin() {
static $myadmin; static $mainadmin = null;
if (! isset($admin)) { if (!isset($mainadmin)) {
if (! $admins = get_admins()) { if (! $admins = get_admins()) {
return false; 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 * Returns list of all admins, using 1 DB query
* but does not depend on the v1.9 datastructures (context.path, etc).
* *
* @global object
* @return array * @return array
*/ */
function get_admins() { function get_admins() {
global $DB; global $DB, $CFG;
$sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid $sql = "SELECT u.*
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
FROM {user} u FROM {user} u
JOIN ($sql) ra WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
ON u.id=ra.userid
ORDER BY ra.adminid ASC";
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(); $visiblecourses = array();
$sql = "SELECT $fields, list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel $sql = "SELECT $fields $ccselect
FROM {course} c FROM {course} c
JOIN {context} ctx $ccjoin
ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
$categoryselect $categoryselect
$sortstatement"; $sortstatement";
@ -468,10 +457,10 @@ function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*")
// loop throught them // loop throught them
foreach ($courses as $course) { foreach ($courses as $course) {
$course = make_context_subobj($course); context_instance_preload($course);
if (isset($course->visible) && $course->visible <= 0) { if (isset($course->visible) && $course->visible <= 0) {
// for hidden courses, require visibility check // 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; $visiblecourses [$course->id] = $course;
} }
} else { } else {
@ -517,12 +506,11 @@ function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c
$categoryselect = ""; $categoryselect = "";
} }
$sql = "SELECT $fields, list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel $sql = "SELECT $fields $ccselect
FROM {course} c FROM {course} c
JOIN {context} ctx $ccjoin
ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
$categoryselect $categoryselect
ORDER BY $sort"; 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 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
$visiblecourses = array(); $visiblecourses = array();
foreach($rs as $course) { foreach($rs as $course) {
$course = make_context_subobj($course); context_instance_preload($course);
if ($course->visible <= 0) { if ($course->visible <= 0) {
// for hidden courses, require visibility check // 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++; $totalcount++;
if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) { if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
$visiblecourses [$course->id] = $course; $visiblecourses [$course->id] = $course;
@ -566,7 +554,6 @@ function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c
* role assignments, etc. * role assignments, etc.
* *
* The returned array is indexed on c.id, and each course will have * 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 * - $course->managers - array containing RA objects that include a $user obj
* with the minimal fields needed for fullname() * 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 // pull out all courses matching the cat
$sql = "SELECT $coursefields, list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
ctx.id AS ctxid, ctx.path AS ctxpath, $sql = "SELECT $coursefields $ccselect
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course} c FROM {course} c
JOIN {context} ctx $ccjoin
ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
$where $where
$sortstatement"; $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 // the context, and prepping data to fetch the
// managers efficiently later... // managers efficiently later...
foreach ($courses as $k => $course) { 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(); $courses[$k]->managers = array();
if ($allcats === false) { if ($allcats === false) {
// single cat, so take just the first one... // single cat, so take just the first one...
if ($catpath === NULL) { if ($catpath === NULL) {
$catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path); $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
} }
} else { } else {
// chop off the contextid of the course itself // chop off the contextid of the course itself
// like dirname() does... // like dirname() does...
$catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path); $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
} }
} }
} else { } 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, $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
ra.hidden,
r.id AS roleid, r.name as rolename, r.id AS roleid, r.name as rolename,
u.id AS userid, u.firstname, u.lastname u.id AS userid, u.firstname, u.lastname
FROM {role_assignments} ra 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 // This loop is fairly stupid as it stands - might get better
// results doing an initial pass clustering RAs by path. // results doing an initial pass clustering RAs by path.
foreach($rs as $ra) { foreach($rs as $ra) {
$user = new StdClass; $user = new stdClass;
$user->id = $ra->userid; unset($ra->userid); $user->id = $ra->userid; unset($ra->userid);
$user->firstname = $ra->firstname; unset($ra->firstname); $user->firstname = $ra->firstname; unset($ra->firstname);
$user->lastname = $ra->lastname; unset($ra->lastname); $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) { foreach ($courses as $k => $course) {
$courses[$k]->managers[] = $ra; $courses[$k]->managers[] = $ra;
} }
} elseif ($ra->contextlevel == CONTEXT_COURSECAT) { } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
if ($allcats === false) { if ($allcats === false) {
// It always applies // It always applies
foreach ($courses as $k => $course) { foreach ($courses as $k => $course) {
@ -759,15 +745,16 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a
} }
} else { } else {
foreach ($courses as $k => $course) { foreach ($courses as $k => $course) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
// Note that strpos() returns 0 as "matched at pos 0" // 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 // Only add it to subpaths
$courses[$k]->managers[] = $ra; $courses[$k]->managers[] = $ra;
} }
} }
} }
} else { // course-level } 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 //this course is not in a list, probably a frontpage course
continue; 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) { function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
global $CFG, $USER, $DB; global $CFG, $USER, $DB;
// Guest's do not have any courses // Guest account does not have any courses
$sitecontext = get_context_instance(CONTEXT_SYSTEM); if (isguestuser()) {
if (has_capability('moodle/legacy:guest', $sitecontext, $userid, false)) {
return(array()); return(array());
} }
@ -902,14 +888,11 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
// the same... // the same...
// (but here we don't need to check has_cap) // (but here we don't need to check has_cap)
$coursefields = 'c.' .join(',c.', $fields); $coursefields = 'c.' .join(',c.', $fields);
$sql = "SELECT $coursefields, list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
ctx.id AS ctxid, ctx.path AS ctxpath, $sql = "SELECT $coursefields $ccselect, cc.path AS categorypath
ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
cc.path AS categorypath
FROM {course} c FROM {course} c
JOIN {course_categories} cc ON c.category=cc.id JOIN {course_categories} cc ON c.category=cc.id
JOIN {context} ctx $ccjoin
ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
WHERE c.id IN ($courseids) WHERE c.id IN ($courseids)
$orderby"; $orderby";
$rs = $DB->get_recordset_sql($sql); $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 $cc = 0; // keep count
foreach ($rs as $c) { foreach ($rs as $c) {
// build the context obj // build the context obj
$c = make_context_subobj($c); context_instance_preload($c);
if ($limit > 0 && $cc >= $limit) { if ($limit > 0 && $cc >= $limit) {
break; 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, $doanything, $sort, $fields,
$limit); $limit);
@ -947,12 +930,10 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
// If we have to walk category visibility // If we have to walk category visibility
// to eval course visibility, get the categories // to eval course visibility, get the categories
if (empty($CFG->allowvisiblecoursesinhiddencategories)) { if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
$sql = "SELECT cc.id, cc.path, cc.visible, list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
ctx.id AS ctxid, ctx.path AS ctxpath, $sql = "SELECT cc.id, cc.path, cc.visible $ccselect
ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course_categories} cc FROM {course_categories} cc
JOIN {context} ctx ON (cc.id = ctx.instanceid) $ccjoin
WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
ORDER BY cc.id"; ORDER BY cc.id";
$rs = $DB->get_recordset_sql($sql); $rs = $DB->get_recordset_sql($sql);
@ -960,7 +941,7 @@ function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NUL
$categories = array(); $categories = array();
foreach($rs as $course_cat) { foreach($rs as $course_cat) {
// build the context obj // build the context obj
$course_cat = make_context_subobj($course_cat); context_instance_preload($course_cat);
$categories[$course_cat->id] = $course_cat; $categories[$course_cat->id] = $course_cat;
} }
$rs->close(); $rs->close();
@ -1142,12 +1123,10 @@ function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $record
$searchcond = implode(" AND ", $searchcond); $searchcond = implode(" AND ", $searchcond);
$sql = "SELECT c.*, list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
ctx.id AS ctxid, ctx.path AS ctxpath, $sql = "SELECT c.* $ccselect
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course} c FROM {course} c
JOIN {context} ctx $ccjoin
ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
WHERE $searchcond AND c.id <> ".SITEID." WHERE $searchcond AND c.id <> ".SITEID."
ORDER BY $sort"; ORDER BY $sort";
$courses = array(); $courses = array();
@ -1159,8 +1138,9 @@ function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $record
$limitto = $limitfrom + $recordsperpage; $limitto = $limitfrom + $recordsperpage;
foreach($rs as $course) { foreach($rs as $course) {
$course = make_context_subobj($course); context_instance_preload($course);
if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) { $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 // Don't exit this loop till the end
// we need to count all the visible courses // we need to count all the visible courses
// to update $totalcount // to update $totalcount
@ -1207,34 +1187,27 @@ function get_categories($parent='none', $sort=NULL, $shallow=true) {
$sort = "ORDER BY $sort"; $sort = "ORDER BY $sort";
} }
list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
if ($parent === 'none') { if ($parent === 'none') {
$sql = "SELECT cc.*, $sql = "SELECT cc.* $ccselect
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course_categories} cc FROM {course_categories} cc
JOIN {context} ctx $ccjoin
ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
$sort"; $sort";
$params = array(); $params = array();
} elseif ($shallow) { } elseif ($shallow) {
$sql = "SELECT cc.*, $sql = "SELECT cc.* $ccselect
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course_categories} cc FROM {course_categories} cc
JOIN {context} ctx $ccjoin
ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
WHERE cc.parent=? WHERE cc.parent=?
$sort"; $sort";
$params = array($parent); $params = array($parent);
} else { } else {
$sql = "SELECT cc.*, $sql = "SELECT cc.* $ccselect
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course_categories} cc FROM {course_categories} cc
JOIN {context} ctx $ccjoin
ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
JOIN {course_categories} ccp JOIN {course_categories} ccp
ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").") ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").")
WHERE ccp.id=? WHERE ccp.id=?
@ -1245,8 +1218,9 @@ function get_categories($parent='none', $sort=NULL, $shallow=true) {
if( $rs = $DB->get_recordset_sql($sql, $params) ){ if( $rs = $DB->get_recordset_sql($sql, $params) ){
foreach($rs as $cat) { foreach($rs as $cat) {
$cat = make_context_subobj($cat); context_instance_preload($cat);
if ($cat->visible || has_capability('moodle/category:viewhiddencategories',$cat->context)) { $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
$categories[$cat->id] = $cat; $categories[$cat->id] = $cat;
} }
} }
@ -2289,7 +2263,7 @@ function get_logs_userday($userid, $courseid, $daystart) {
* *
* @global object * @global object
* @uses CONTEXT_SYSTEM * @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 $username The username we are searching for
* @param string $lastlogin The date from which we are searching * @param string $lastlogin The date from which we are searching
* @return int * @return int
@ -2302,12 +2276,12 @@ function count_login_failures($mode, $username, $lastlogin) {
$count = new object(); $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)) { if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
$count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)'); $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
return $count; 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)) { if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
return $count; return $count;
} }

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More