2803fe38ad57cc9981ead7ca362abe7c5e5d7622
[mdk.git] / mdk / scripts / enrol.php
1 <?php
2 /**
3 * Enrol users in all the courses.
4 *
5 * Users with username starting with:
6 * - s become students
7 * - t become teachers
8 * - m become managers
9 *
10 * In every single course on the site.
11 */
12
13 define('CLI_SCRIPT', true);
14 require(__DIR__ . '/config.php');
15 require_once($CFG->libdir . '/accesslib.php');
16 require_once($CFG->dirroot . '/enrol/manual/lib.php');
17
18 function mdk_get_enrol_instance($courseid) {
19 global $DB;
20 static $coursecache = array();
21 if (!isset($coursecache[$courseid])) {
22 $coursecache[$courseid] = $DB->get_record('enrol', array('courseid' => $courseid, 'enrol' => 'manual'));
23 }
24 return $coursecache[$courseid];
25 }
26
27 function mdk_get_role($username) {
28 static $rolecache = array();
29 $letter = substr($username, 0, 1);
30 switch ($letter) {
31 case 's':
32 $archetype = 'student';
33 break;
34 case 't':
35 $archetype = 'editingteacher';
36 break;
37 case 'm':
38 $archetype = 'manager';
39 break;
40 default:
41 return false;
42 }
43 if (!isset($rolecache[$archetype])) {
44 $role = get_archetype_roles($archetype);
45 $rolecache[$archetype] = reset($role);
46 }
47 return $rolecache[$archetype];
48 }
49
50 $sql = "SELECT id, username
51 FROM {user}
52 WHERE (username LIKE 's%'
53 OR username LIKE 't%'
54 OR username LIKE 'm%')
55 AND deleted = 0
56 AND username NOT LIKE 'tool_generator_%'";
57 $users = $DB->get_recordset_sql($sql, array());
58 $courses = $DB->get_records_select('course', 'id > ?', array(1), '', 'id, startdate');
59 $plugin = new enrol_manual_plugin();
60
61 foreach ($users as $user) {
62 mtrace('Enrolling ' . $user->username);
63 $role = mdk_get_role($user->username);
64 if (!$role) {
65 continue;
66 }
67 foreach ($courses as $course) {
68 $instance = mdk_get_enrol_instance($course->id);
69 // Enrol the day before the course startdate, because if we create a course today its default
70 // startdate is tomorrow, and we would never realise why the enrolments do not work.
71 $plugin->enrol_user($instance, $user->id, $role->id, $course->startdate - 86400, 0);
72 }
73 }
74
75 $users->close();