MDL-22787 Fixed remote unenrol - blame copy & paste
[moodle.git] / enrol / mnet / enrol.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Implements the XML-RPC methods this plugin publishes to MNet peers
20  *
21  * This file must be named enrol.php because current MNet framework has the
22  * filename hardcoded in XML-RPC path and we want to be compatible with
23  * Moodle 1.x MNet clients. There is a proposal in MDL-21993 to allow
24  * map XMP-RPC calls to whatever file, function, class or methods. Once this
25  * is fixed, this file will be probably renamed to mnetlib.php (which could
26  * be a common name of a plugin library containing functions/methods callable
27  * via MNet framework.
28  *
29  * @package    enrol
30  * @subpackage mnet
31  * @copyright  2010 David Mudrak <david@moodle.com>
32  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33  */
35 defined('MOODLE_INTERNAL') || die();
36 defined('MNET_SERVER') || die();
38 /**
39  * MNet server-side methods that are part of mnetservice_enrol
40  *
41  * The weird name of the class tries to follow a pattern
42  * {plugintype}_{pluginnname}_mnetservice_{servicename}
43  *
44  * Class methods are compatible with API 1 of the service used by Moodle 1.x
45  * and 2.0 peers. The API version might become a part of class name but it is
46  * not neccessary due to how xml-rcp methods are/will be mapped to php methods.
47  */
48 class enrol_mnet_mnetservice_enrol {
50     /**
51      * Returns list of courses that we offer to the caller for remote enrolment of their users
52      *
53      * Since Moodle 2.0, courses are made available for MNet peers by creating an instance
54      * of enrol_mnet plugin for the course. Hidden courses are not returned. If there are two
55      * instances - one specific for the host and one for 'All hosts', the setting of the specific
56      * one is used. The id of the peer is kept in customint1, no other custom fields are used.
57      *
58      * @uses mnet_remote_client Callable via XML-RPC only
59      * @return array
60      */
61     public function available_courses() {
62         global $CFG, $DB;
63         require_once($CFG->libdir.'/filelib.php');
65         if (!$client = get_mnet_remote_client()) {
66             die('Callable via XML-RPC only');
67         }
69         // we call our id as 'remoteid' because it will be sent to the peer
70         // the column aliases are required by MNet protocol API for clients 1.x and 2.0
71         $sql = "SELECT c.id AS remoteid, c.fullname, c.shortname, c.idnumber, c.summary, c.summaryformat,
72                        c.sortorder, c.startdate, cat.id AS cat_id, cat.name AS cat_name,
73                        cat.description AS cat_description, cat.descriptionformat AS cat_descriptionformat,
74                        e.cost, e.currency, e.roleid AS defaultroleid, r.name AS defaultrolename,
75                        e.customint1
76                   FROM {enrol} e
77             INNER JOIN {course} c ON c.id = e.courseid
78             INNER JOIN {course_categories} cat ON cat.id = c.category
79             INNER JOIN {role} r ON r.id = e.roleid
80                  WHERE e.enrol = 'mnet'
81                        AND (e.customint1 = 0 OR e.customint1 = ?)
82                        AND c.visible = 1
83               ORDER BY cat.sortorder, c.sortorder, c.shortname";
85         $rs = $DB->get_recordset_sql($sql, array($client->id));
87         $courses = array();
88         foreach ($rs as $course) {
89             // use the record if it does not exist yet or is host-specific
90             if (empty($courses[$course->remoteid]) or ($course->customint1 > 0)) {
91                 unset($course->customint1); // the client does not need to know this
92                 $context = get_context_instance(CONTEXT_COURSE, $course->remoteid);
93                 // Rewrite file URLs so that they are correct
94                 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary');
95                 $courses[$course->remoteid] = $course;
96             }
97         }
98         $rs->close();
100         return array_values($courses); // can not use keys for backward compatibility
101     }
103     /**
104      * This method has never been implemented in Moodle MNet API
105      *
106      * @uses mnet_remote_client Callable via XML-RPC only
107      * @return array empty array
108      */
109     public function user_enrolments() {
110         global $CFG, $DB;
112         if (!$client = get_mnet_remote_client()) {
113             die('Callable via XML-RPC only');
114         }
115         return array();
116     }
118     /**
119      * Enrol remote user to our course
120      *
121      * If we do not have local record for the remote user in our database,
122      * it gets created here.
123      *
124      * @uses mnet_remote_client Callable via XML-RPC only
125      * @param array $userdata user details {@see mnet_fields_to_import()}
126      * @param int $courseid our local course id
127      * @return bool true if the enrolment has been successful, throws exception otherwise
128      */
129     public function enrol_user(array $userdata, $courseid) {
130         global $CFG, $DB;
131         require_once(dirname(__FILE__).'/lib.php');
133         if (!$client = get_mnet_remote_client()) {
134             die('Callable via XML-RPC only');
135         }
137         if (empty($userdata['username'])) {
138             throw new mnet_server_exception(5021, 'emptyusername', 'enrol_mnet');
139         }
141         // do we know the remote user?
142         $user = $DB->get_record('user', array('username'=>$userdata['username'], 'mnethostid'=>$client->id));
144         if ($user === false) {
145             // here we could check the setting if the enrol_mnet is allowed to auto-register
146             // users {@link http://tracker.moodle.org/browse/MDL-21327}
147             $user = mnet_strip_user((object)$userdata, mnet_fields_to_import($client));
148             $user->mnethostid = $client->id;
149             if (!$user->id = $DB->insert_record('user', $user)) {
150                 throw new mnet_server_exception(5011, 'couldnotcreateuser', 'enrol_mnet');
151             }
152         }
154         if (! $course = $DB->get_record('course', array('id'=>$courseid))) {
155             throw new mnet_server_exception(5012, 'coursenotfound', 'enrol_mnet');
156         }
158         $courses = $this->available_courses();
159         $isavailable = false;
160         foreach ($courses as $available) {
161             if ($available->remoteid == $course->id) {
162                 $isavailable = true;
163                 break;
164             }
165         }
166         if (!$isavailable) {
167             throw new mnet_server_exception(5013, 'courseunavailable', 'enrol_mnet');
168         }
170         // try to load host specific enrol_mnet instance first
171         $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>$client->id), '*', IGNORE_MISSING);
173         if ($instance === false) {
174             // if not found, try to load instance for all hosts
175             $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>0), '*', IGNORE_MISSING);
176         }
178         if ($instance === false) {
179             // this should not happen as the course was returned by {@see self::available_courses()}
180             throw new mnet_server_exception(5017, 'noenrolinstance', 'enrol_mnet');
181         }
183         if (!$enrol = enrol_get_plugin('mnet')) {
184             throw new mnet_server_exception(5018, 'couldnotinstantiate', 'enrol_mnet');
185         }
187         try {
188             $enrol->enrol_user($instance, $user->id, $instance->roleid, time());
190         } catch (Exception $e) {
191             throw new mnet_server_exception(5019, 'couldnotenrol', 'enrol_mnet', $e->getMessage());
192         }
194         return true;
195     }
197     /**
198      * Unenrol remote user from our course
199      *
200      * Only users enrolled via enrol_mnet plugin can be unenrolled remotely. If the
201      * remote user is enrolled into the local course via some other enrol plugin
202      * (enrol_manual for example), the remote host can't touch such enrolment. Please
203      * do not report this behaviour as bug, it is a feature ;-)
204      *
205      * @uses mnet_remote_client Callable via XML-RPC only
206      * @param string $username of the remote user
207      * @param int $courseid of our local course
208      * @return bool true if the unenrolment has been successful, throws exception otherwise
209      */
210     public function unenrol_user($username, $courseid) {
211         global $CFG, $DB;
213         if (!$client = get_mnet_remote_client()) {
214             die('Callable via XML-RPC only');
215         }
217         $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$client->id));
219         if ($user === false) {
220             throw new mnet_exception(5014, 'usernotfound', 'enrol_mnet');
221         }
223         if (! $course = $DB->get_record('course', array('id'=>$courseid))) {
224             throw new mnet_server_exception(5012, 'coursenotfound', 'enrol_mnet');
225         }
227         $courses = $this->available_courses();
228         $isavailable = false;
229         foreach ($courses as $available) {
230             if ($available->remoteid == $course->id) {
231                 $isavailable = true;
232                 break;
233             }
234         }
235         if (!$isavailable) {
236             // if they can not enrol, they can not unenrol
237             throw new mnet_server_exception(5013, 'courseunavailable', 'enrol_mnet');
238         }
240         // try to load host specific enrol_mnet instance first
241         $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>$client->id), '*', IGNORE_MISSING);
243         if ($instance === false) {
244             // if not found, try to load instance for all hosts
245             $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>0), '*', IGNORE_MISSING);
246             $instanceforall = true;
247         }
249         if ($instance === false) {
250             // this should not happen as the course was returned by {@see self::available_courses()}
251             throw new mnet_server_exception(5017, 'noenrolinstance', 'enrol_mnet');
252         }
254         if (!$enrol = enrol_get_plugin('mnet')) {
255             throw new mnet_server_exception(5018, 'couldnotinstantiate', 'enrol_mnet');
256         }
258         if ($DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
259             try {
260                 $enrol->unenrol_user($instance, $user->id);
262             } catch (Exception $e) {
263                 throw new mnet_server_exception(5020, 'couldnotunenrol', 'enrol_mnet', $e->getMessage());
264             }
265         }
267         if (empty($instanceforall)) {
268             // if the user was enrolled via 'All hosts' instance and the specific one
269             // was created after that, the first enrolment would be kept.
270             $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>0), '*', IGNORE_MISSING);
272             if ($instance) {
273                 // repeat the same procedure for 'All hosts' instance, too. Note that as the host specific
274                 // instance exists, it will be used for the future enrolments
276                 if ($DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
277                     try {
278                         $enrol->unenrol_user($instance, $user->id);
280                     } catch (Exception $e) {
281                         throw new mnet_server_exception(5020, 'couldnotunenrol', 'enrol_mnet', $e->getMessage());
282                     }
283                 }
284             }
285         }
287         return true;
288     }
290     /**
291      * Returns a list of users from the client server who are enrolled in our course
292      *
293      * Suitable instance of enrol_mnet must be created in the course. This method will not
294      * return any information about the enrolments in courses that are not available for
295      * remote enrolment, even if their users are enrolled into them via other plugin
296      * (note the difference from {@link self::user_enrolments()}).
297      *
298      * This method will return enrolment information for users from hosts regardless
299      * the enrolment plugin. It does not matter if the user was enrolled remotely by
300      * their admin or locally. Once the course is available for remote enrolments, we
301      * will tell them everything about their users.
302      *
303      * In Moodle 1.x the returned array used to be indexed by username. The side effect
304      * of MDL-19219 fix is that we do not need to use such index and therefore we can
305      * return all enrolment records. MNet clients 1.x will only use the last record for
306      * the student, if she is enrolled via multiple plugins.
307      *
308      * @uses mnet_remote_client Callable via XML-RPC only
309      * @param int $courseid ID of our course
310      * @param string|array $roles comma separated list of role shortnames (or array of them)
311      * @return array
312      */
313     public function course_enrolments($courseid, $roles=null) {
314         global $DB;
316         if (!$client = get_mnet_remote_client()) {
317             die('Callable via XML-RPC only');
318         }
320         $sql = "SELECT u.username, r.shortname, r.name, e.enrol, ue.timemodified
321                   FROM {user_enrolments} ue
322                   JOIN {user} u ON ue.userid = u.id
323                   JOIN {enrol} e ON ue.enrolid = e.id
324                   JOIN {role} r ON e.roleid = r.id
325                  WHERE u.mnethostid = :mnethostid
326                        AND e.courseid = :courseid
327                        AND u.username != 'guest'
328                        AND u.confirmed = 1
329                        AND u.deleted = 0";
330         $params['mnethostid'] = $client->id;
331         $params['courseid'] = $courseid;
333         if (!is_null($roles)) {
334             if (!is_array($roles)) {
335                 $roles = explode(',', $roles);
336             }
337             $roles = array_map('trim', $roles);
338             list($rsql, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED);
339             $sql .= " AND r.shortname $rsql";
340             $params = array_merge($params, $rparams);
341         }
343         $sql .= " ORDER BY u.lastname, u.firstname";
345         $rs = $DB->get_recordset_sql($sql, $params);
346         $list = array();
347         foreach ($rs as $record) {
348             $list[] = $record;
349         }
350         $rs->close();
352         return $list;
353     }