Merge branch 'MDL-59367-master' of git://github.com/damyon/moodle

This commit is contained in:
Andrew Nicols 2017-07-25 15:02:55 +08:00
commit e18ebf3999
6 changed files with 378 additions and 1 deletions

View File

@ -54,7 +54,7 @@ class user_groups_editable extends \core\output\inplace_editable {
* @param \context $context The course context
* @param \stdClass $user The current user
* @param \stdClass[] $coursegroups The list of course groups from groups_get_all_groups with membership.
* @param string $value JSON Encoded list of group ids.
* @param string $value Array of groupids.
*/
public function __construct($course, $context, $user, $coursegroups, $value) {
// Check capabilities to get editable value.

View File

@ -0,0 +1,197 @@
<?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/>.
/**
* Contains class core_user\output\user_roles_editable
*
* @package core_user
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_user\output;
use context_course;
use core_user;
use core_external;
use coding_exception;
defined('MOODLE_INTERNAL') || die();
/**
* Class to display list of user roles.
*
* @package core_user
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class user_roles_editable extends \core\output\inplace_editable {
/** @var $context */
private $context = null;
/** @var $courseroles Array */
private $courseroles = null;
/**
* Constructor.
*
* @param \stdClass $course The current course
* @param \context $context The course context
* @param \stdClass $user The current user
* @param \stdClass[] $courseroles The list of course roles.
* @param \stdClass[] $assignableroles The list of assignable roles in this course.
* @param string $value Array of role ids.
*/
public function __construct($course, $context, $user, $courseroles, $assignableroles, $value) {
// Check capabilities to get editable value.
$editable = has_capability('moodle/role:assign', $context);
// Invent an itemid.
$itemid = $course->id . ':' . $user->id;
$value = json_encode($value);
// Remember these for the display value.
$this->courseroles = $courseroles;
$this->context = $context;
parent::__construct('core_user', 'user_roles', $itemid, $editable, $value, $value);
// Assignable roles.
$options = $assignableroles;
$this->edithint = get_string('xroleassignments', 'role', fullname($user));
$this->editlabel = get_string('xroleassignments', 'role', fullname($user));
$attributes = ['multiple' => true];
$this->set_type_autocomplete($options, $attributes);
}
/**
* Export this data so it can be used as the context for a mustache template.
*
* @param \renderer_base $output
* @return array
*/
public function export_for_template(\renderer_base $output) {
$listofroles = [];
$roleids = json_decode($this->value);
foreach ($roleids as $id) {
$listofroles[] = format_string($this->courseroles[$id]->localname, true, ['context' => $this->context]);
}
if (!empty($listofroles)) {
$this->displayvalue = implode($listofroles, ', ');
} else {
$this->displayvalue = get_string('noroles', 'role');
}
return parent::export_for_template($output);
}
/**
* Updates the value in database and returns itself, called from inplace_editable callback
*
* @param int $itemid
* @param mixed $newvalue
* @return \self
*/
public static function update($itemid, $newvalue) {
global $DB, $CFG;
require_once($CFG->libdir . '/external/externallib.php');
// Check caps.
// Do the thing.
// Return one of me.
// Validate the inputs.
list($courseid, $userid) = explode(':', $itemid, 2);
$courseid = clean_param($courseid, PARAM_INT);
$userid = clean_param($userid, PARAM_INT);
$roleids = json_decode($newvalue);
foreach ($roleids as $index => $roleid) {
$roleids[$index] = clean_param($roleid, PARAM_INT);
}
// Check user is enrolled in the course.
$context = context_course::instance($courseid);
core_external::validate_context($context);
// Check permissions.
require_capability('moodle/role:assign', $context);
if (!is_enrolled($context, $userid)) {
throw new coding_exception('User does not belong to the course');
}
// Check that all the groups belong to the course.
$allroles = role_fix_names(get_all_roles($context), $context);
$assignableroles = get_assignable_roles($context, ROLENAME_ALIAS, false);
$userroles = get_user_roles($context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
$ids = [];
foreach ($userroles as $role) {
$ids[$role->roleid] = $role->roleid;
}
$byid = [];
foreach ($roleids as $roleid) {
if (!isset($assignableroles[$roleid])) {
throw new coding_exception('Role cannot be assigned in this course.');
}
$byid[$roleid] = $roleid;
}
$roleids = $byid;
// Process adds.
foreach ($roleids as $roleid) {
if (!isset($ids[$roleid])) {
// Add them.
role_assign($roleid, $userid, $context);
// Keep this variable in sync.
$ids[$roleid] = $roleid;
}
}
// Process removals.
foreach ($assignableroles as $id => $role) {
if (isset($ids[$id]) && !isset($roleids[$id])) {
$ras = $DB->get_records('role_assignments', ['contextid' => $context->id, 'userid' => $userid, 'roleid' => $id]);
$allremoved = true;
foreach ($ras as $ra) {
if ($ra->component) {
if (strpos($ra->component, 'enrol_') !== 0) {
continue;
}
if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
continue;
}
if ($plugin->roles_protected()) {
$allremoved = false;
continue;
}
}
role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
}
if ($allremoved) {
unset($ids[$id]);
}
}
}
$course = get_course($courseid);
$user = core_user::get_user($userid);
return new self($course, $context, $user, $allroles, $assignableroles, array_values(array_unique($ids)));
}
}

View File

@ -95,6 +95,16 @@ class participants_table extends \table_sql {
*/
protected $context;
/**
* @var \stdClass[] List of roles indexed by roleid.
*/
protected $allroles;
/**
* @var \stdClass[] Assignable roles in this course.
*/
protected $assignableroles;
/**
* Sets up the table.
*
@ -134,6 +144,9 @@ class participants_table extends \table_sql {
$columns[] = $field;
}
$headers[] = get_string('roles');
$columns[] = 'roles';
// Load and cache the course groupinfo.
// Add column for groups.
$headers[] = get_string('groups');
@ -175,6 +188,8 @@ class participants_table extends \table_sql {
$this->extrafields = $extrafields;
$this->context = $context;
$this->groups = groups_get_all_groups($courseid, 0, 0, 'g.*', true);
$this->allroles = role_fix_names(get_all_roles($this->context), $this->context);
$this->assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false);
}
/**
@ -204,6 +219,31 @@ class participants_table extends \table_sql {
return $OUTPUT->user_picture($data, array('size' => 35, 'courseid' => $this->course->id, 'includefullname' => true));
}
/**
* User roles column.
*
* @param \stdClass $data
* @return string
*/
public function col_roles($data) {
global $OUTPUT;
$roles = get_user_roles($this->context, $data->id, true, 'c.contextlevel DESC, r.sortorder ASC');
$getrole = function($role) {
return $role->roleid;
};
$ids = array_values(array_unique(array_map($getrole, $roles)));
$editable = new \core_user\output\user_roles_editable($this->course,
$this->context,
$data,
$this->allroles,
$this->assignableroles,
$ids);
return $OUTPUT->render_from_template('core/inplace_editable', $editable->export_for_template($OUTPUT));
}
/**
* Generate the groups column.
*

View File

@ -1385,3 +1385,17 @@ function user_get_user_lastaccess_sql($accesssince = null, $tableprefix = 'u') {
return $tableprefix . '.lastaccess != 0 AND u.lastaccess < ' . $accesssince;
}
}
/**
* Callback for inplace editable API.
*
* @param string $itemtype - Only user_roles is supported.
* @param string $itemid - Courseid and userid separated by a :
* @param string $newvalue - json encoded list of roleids.
* @return \core\output\inplace_editable
*/
function core_user_inplace_editable($itemtype, $itemid, $newvalue) {
if ($itemtype === 'user_roles') {
return \core_user\output\user_roles_editable::update($itemid, $newvalue);
}
}

View File

@ -0,0 +1,41 @@
@core @core_user
Feature: Edit user roles
In order to administer users in course
As a teacher
I need to be able to assign and unassign roles in the course
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | 1 | teacher1@example.com |
| student1 | Student | 1 | student1@example.com |
| student2 | Student | 2 | student2@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
| student2 | C1 | student |
@javascript
Scenario: Assign roles on participants page
Given I log in as "teacher1"
And I am on "Course 1" course homepage
And I navigate to course participants
And I click on "Student 1's role assignments" "link"
And I open the autocomplete suggestions list
And I click on "Non-editing teacher" item in the autocomplete list
When I click on "Save changes" "link"
Then I should see "Student, Non-editing teacher" in the "Student 1" "table_row"
@javascript
Scenario: Remove roles on participants page
Given I log in as "teacher1"
And I am on "Course 1" course homepage
And I navigate to course participants
And I click on "Student 1's role assignments" "link"
And I click on ".form-autocomplete-selection [aria-selected=true]" "css_element"
When I click on "Save changes" "link"
Then I should see "No roles" in the "Student 1" "table_row"

View File

@ -0,0 +1,85 @@
<?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/>.
/**
* Unit tests for user/lib.php.
*
* @package core_user
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Unit tests for user roles editable class.
*
* @package core_user
* @copyright 2017 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class userroleseditable_testcase extends advanced_testcase {
/**
* Test user roles editable.
*/
public function test_update() {
global $DB;
$this->resetAfterTest();
// Create user and modify user profile.
$user1 = $this->getDataGenerator()->create_user();
$user2 = $this->getDataGenerator()->create_user();
$course1 = $this->getDataGenerator()->create_course();
$coursecontext = context_course::instance($course1->id);
$teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->getDataGenerator()->enrol_user($user1->id, $course1->id);
$this->getDataGenerator()->enrol_user($user2->id, $course1->id);
role_assign($teacherrole->id, $user1->id, $coursecontext->id);
role_assign($teacherrole->id, $user2->id, $coursecontext->id);
$this->setAdminUser();
accesslib_clear_all_caches_for_unit_testing();
// Use the userroleseditable api to remove all roles from user1 and give user2 student and teacher.
$itemid = $course1->id . ':' . $user1->id;
$newvalue = json_encode([]);
$result = \core_user\output\user_roles_editable::update($itemid, $newvalue);
$this->assertTrue($result instanceof \core_user\output\user_roles_editable);
$currentroles = get_user_roles_in_course($user1->id, $course1->id);
$this->assertEmpty($currentroles);
$this->setAdminUser();
accesslib_clear_all_caches_for_unit_testing();
$itemid = $course1->id . ':' . $user2->id;
$newvalue = json_encode([$teacherrole->id, $studentrole->id]);
$result = \core_user\output\user_roles_editable::update($itemid, $newvalue);
$this->assertTrue($result instanceof \core_user\output\user_roles_editable);
$currentroles = get_user_roles_in_course($user2->id, $course1->id);
$this->assertContains('Non-editing teacher', $currentroles);
$this->assertContains('Student', $currentroles);
}
}