2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * The purpose of this file is to allow the user to switch roles and be redirected
19 * back to the page that they were on.
21 * This functionality is also supported in {@link /course/view.php} in order to comply
22 * with backwards compatibility.
23 * The reason that we created this file was so that user didn't get redirected back
24 * to the course view page only to be redirected again.
28 * @copyright 2009 Sam Hemelryk
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 require_once('../config.php');
33 require_once($CFG->dirroot
.'/course/lib.php');
35 $id = required_param('id', PARAM_INT
);
36 $switchrole = optional_param('switchrole', -1, PARAM_INT
);
37 $returnurl = optional_param('returnurl', '', PARAM_RAW
);
39 if (strpos($returnurl, '?') === false) {
40 // Looks like somebody did not set proper page url, better go to course page.
41 $returnurl = new moodle_url('/course/view.php', array('id' => $id));
43 if (strpos($returnurl, $CFG->wwwroot
) !== 0) {
44 $returnurl = $CFG->wwwroot
.$returnurl;
46 $returnurl = clean_param($returnurl, PARAM_URL
);
49 $PAGE->set_url('/course/switchrole.php', array('id'=>$id));
53 if (!$course = $DB->get_record('course', array('id'=>$id))) {
54 redirect(new moodle_url('/'));
57 $context = context_course
::instance($course->id
);
59 // Remove any switched roles before checking login.
60 if ($switchrole == 0) {
61 role_switch(0, $context);
63 require_login($course);
65 // Switchrole - sanity check in cost-order...
66 if ($switchrole > 0 && has_capability('moodle/role:switchroles', $context)) {
67 // Is this role assignable in this context?
68 // inquiring minds want to know...
69 $aroles = get_switchable_roles($context);
70 if (is_array($aroles) && isset($aroles[$switchrole])) {
71 role_switch($switchrole, $context);