[ Index ] |
PHP Cross Reference of Unnamed Project |
[Summary view] [Print] [Text view]
1 <?php 2 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/>. 17 18 /** 19 * This library includes the basic parts of enrol api. 20 * It is available on each page. 21 * 22 * @package core 23 * @subpackage enrol 24 * @copyright 2010 Petr Skoda {@link http://skodak.org} 25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 26 */ 27 28 defined('MOODLE_INTERNAL') || die(); 29 30 /** Course enrol instance enabled. (used in enrol->status) */ 31 define('ENROL_INSTANCE_ENABLED', 0); 32 33 /** Course enrol instance disabled, user may enter course if other enrol instance enabled. (used in enrol->status)*/ 34 define('ENROL_INSTANCE_DISABLED', 1); 35 36 /** User is active participant (used in user_enrolments->status)*/ 37 define('ENROL_USER_ACTIVE', 0); 38 39 /** User participation in course is suspended (used in user_enrolments->status) */ 40 define('ENROL_USER_SUSPENDED', 1); 41 42 /** @deprecated - enrol caching was reworked, use ENROL_MAX_TIMESTAMP instead */ 43 define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800); 44 45 /** The timestamp indicating forever */ 46 define('ENROL_MAX_TIMESTAMP', 2147483647); 47 48 /** When user disappears from external source, the enrolment is completely removed */ 49 define('ENROL_EXT_REMOVED_UNENROL', 0); 50 51 /** When user disappears from external source, the enrolment is kept as is - one way sync */ 52 define('ENROL_EXT_REMOVED_KEEP', 1); 53 54 /** @deprecated since 2.4 not used any more, migrate plugin to new restore methods */ 55 define('ENROL_RESTORE_TYPE', 'enrolrestore'); 56 57 /** 58 * When user disappears from external source, user enrolment is suspended, roles are kept as is. 59 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook, 60 * assignments, etc. 61 */ 62 define('ENROL_EXT_REMOVED_SUSPEND', 2); 63 64 /** 65 * When user disappears from external source, the enrolment is suspended and roles assigned 66 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas. 67 * */ 68 define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3); 69 70 /** 71 * Returns instances of enrol plugins 72 * @param bool $enabled return enabled only 73 * @return array of enrol plugins name=>instance 74 */ 75 function enrol_get_plugins($enabled) { 76 global $CFG; 77 78 $result = array(); 79 80 if ($enabled) { 81 // sorted by enabled plugin order 82 $enabled = explode(',', $CFG->enrol_plugins_enabled); 83 $plugins = array(); 84 foreach ($enabled as $plugin) { 85 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin"; 86 } 87 } else { 88 // sorted alphabetically 89 $plugins = core_component::get_plugin_list('enrol'); 90 ksort($plugins); 91 } 92 93 foreach ($plugins as $plugin=>$location) { 94 $class = "enrol_{$plugin}_plugin"; 95 if (!class_exists($class)) { 96 if (!file_exists("$location/lib.php")) { 97 continue; 98 } 99 include_once("$location/lib.php"); 100 if (!class_exists($class)) { 101 continue; 102 } 103 } 104 105 $result[$plugin] = new $class(); 106 } 107 108 return $result; 109 } 110 111 /** 112 * Returns instance of enrol plugin 113 * @param string $name name of enrol plugin ('manual', 'guest', ...) 114 * @return enrol_plugin 115 */ 116 function enrol_get_plugin($name) { 117 global $CFG; 118 119 $name = clean_param($name, PARAM_PLUGIN); 120 121 if (empty($name)) { 122 // ignore malformed or missing plugin names completely 123 return null; 124 } 125 126 $location = "$CFG->dirroot/enrol/$name"; 127 128 if (!file_exists("$location/lib.php")) { 129 return null; 130 } 131 include_once("$location/lib.php"); 132 $class = "enrol_{$name}_plugin"; 133 if (!class_exists($class)) { 134 return null; 135 } 136 137 return new $class(); 138 } 139 140 /** 141 * Returns enrolment instances in given course. 142 * @param int $courseid 143 * @param bool $enabled 144 * @return array of enrol instances 145 */ 146 function enrol_get_instances($courseid, $enabled) { 147 global $DB, $CFG; 148 149 if (!$enabled) { 150 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id'); 151 } 152 153 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id'); 154 155 $enabled = explode(',', $CFG->enrol_plugins_enabled); 156 foreach ($result as $key=>$instance) { 157 if (!in_array($instance->enrol, $enabled)) { 158 unset($result[$key]); 159 continue; 160 } 161 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) { 162 // broken plugin 163 unset($result[$key]); 164 continue; 165 } 166 } 167 168 return $result; 169 } 170 171 /** 172 * Checks if a given plugin is in the list of enabled enrolment plugins. 173 * 174 * @param string $enrol Enrolment plugin name 175 * @return boolean Whether the plugin is enabled 176 */ 177 function enrol_is_enabled($enrol) { 178 global $CFG; 179 180 if (empty($CFG->enrol_plugins_enabled)) { 181 return false; 182 } 183 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled)); 184 } 185 186 /** 187 * Check all the login enrolment information for the given user object 188 * by querying the enrolment plugins 189 * 190 * This function may be very slow, use only once after log-in or login-as. 191 * 192 * @param stdClass $user 193 * @return void 194 */ 195 function enrol_check_plugins($user) { 196 global $CFG; 197 198 if (empty($user->id) or isguestuser($user)) { 199 // shortcut - there is no enrolment work for guests and not-logged-in users 200 return; 201 } 202 203 // originally there was a broken admin test, but accidentally it was non-functional in 2.2, 204 // which proved it was actually not necessary. 205 206 static $inprogress = array(); // To prevent this function being called more than once in an invocation 207 208 if (!empty($inprogress[$user->id])) { 209 return; 210 } 211 212 $inprogress[$user->id] = true; // Set the flag 213 214 $enabled = enrol_get_plugins(true); 215 216 foreach($enabled as $enrol) { 217 $enrol->sync_user_enrolments($user); 218 } 219 220 unset($inprogress[$user->id]); // Unset the flag 221 } 222 223 /** 224 * Do these two students share any course? 225 * 226 * The courses has to be visible and enrolments has to be active, 227 * timestart and timeend restrictions are ignored. 228 * 229 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly 230 * to true. 231 * 232 * @param stdClass|int $user1 233 * @param stdClass|int $user2 234 * @return bool 235 */ 236 function enrol_sharing_course($user1, $user2) { 237 return enrol_get_shared_courses($user1, $user2, false, true); 238 } 239 240 /** 241 * Returns any courses shared by the two users 242 * 243 * The courses has to be visible and enrolments has to be active, 244 * timestart and timeend restrictions are ignored. 245 * 246 * @global moodle_database $DB 247 * @param stdClass|int $user1 248 * @param stdClass|int $user2 249 * @param bool $preloadcontexts If set to true contexts for the returned courses 250 * will be preloaded. 251 * @param bool $checkexistsonly If set to true then this function will return true 252 * if the users share any courses and false if not. 253 * @return array|bool An array of courses that both users are enrolled in OR if 254 * $checkexistsonly set returns true if the users share any courses 255 * and false if not. 256 */ 257 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) { 258 global $DB, $CFG; 259 260 $user1 = isset($user1->id) ? $user1->id : $user1; 261 $user2 = isset($user2->id) ? $user2->id : $user2; 262 263 if (empty($user1) or empty($user2)) { 264 return false; 265 } 266 267 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) { 268 return false; 269 } 270 271 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee'); 272 $params['enabled'] = ENROL_INSTANCE_ENABLED; 273 $params['active1'] = ENROL_USER_ACTIVE; 274 $params['active2'] = ENROL_USER_ACTIVE; 275 $params['user1'] = $user1; 276 $params['user2'] = $user2; 277 278 $ctxselect = ''; 279 $ctxjoin = ''; 280 if ($preloadcontexts) { 281 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 282 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 283 $params['contextlevel'] = CONTEXT_COURSE; 284 } 285 286 $sql = "SELECT c.* $ctxselect 287 FROM {course} c 288 JOIN ( 289 SELECT DISTINCT c.id 290 FROM {enrol} e 291 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1) 292 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2) 293 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1) 294 WHERE e.status = :enabled AND e.enrol $plugins 295 ) ec ON ec.id = c.id 296 $ctxjoin"; 297 298 if ($checkexistsonly) { 299 return $DB->record_exists_sql($sql, $params); 300 } else { 301 $courses = $DB->get_records_sql($sql, $params); 302 if ($preloadcontexts) { 303 array_map('context_helper::preload_from_record', $courses); 304 } 305 return $courses; 306 } 307 } 308 309 /** 310 * This function adds necessary enrol plugins UI into the course edit form. 311 * 312 * @param MoodleQuickForm $mform 313 * @param object $data course edit form data 314 * @param object $context context of existing course or parent category if course does not exist 315 * @return void 316 */ 317 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) { 318 $plugins = enrol_get_plugins(true); 319 if (!empty($data->id)) { 320 $instances = enrol_get_instances($data->id, false); 321 foreach ($instances as $instance) { 322 if (!isset($plugins[$instance->enrol])) { 323 continue; 324 } 325 $plugin = $plugins[$instance->enrol]; 326 $plugin->course_edit_form($instance, $mform, $data, $context); 327 } 328 } else { 329 foreach ($plugins as $plugin) { 330 $plugin->course_edit_form(NULL, $mform, $data, $context); 331 } 332 } 333 } 334 335 /** 336 * Validate course edit form data 337 * 338 * @param array $data raw form data 339 * @param object $context context of existing course or parent category if course does not exist 340 * @return array errors array 341 */ 342 function enrol_course_edit_validation(array $data, $context) { 343 $errors = array(); 344 $plugins = enrol_get_plugins(true); 345 346 if (!empty($data['id'])) { 347 $instances = enrol_get_instances($data['id'], false); 348 foreach ($instances as $instance) { 349 if (!isset($plugins[$instance->enrol])) { 350 continue; 351 } 352 $plugin = $plugins[$instance->enrol]; 353 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context)); 354 } 355 } else { 356 foreach ($plugins as $plugin) { 357 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context)); 358 } 359 } 360 361 return $errors; 362 } 363 364 /** 365 * Update enrol instances after course edit form submission 366 * @param bool $inserted true means new course added, false course already existed 367 * @param object $course 368 * @param object $data form data 369 * @return void 370 */ 371 function enrol_course_updated($inserted, $course, $data) { 372 global $DB, $CFG; 373 374 $plugins = enrol_get_plugins(true); 375 376 foreach ($plugins as $plugin) { 377 $plugin->course_updated($inserted, $course, $data); 378 } 379 } 380 381 /** 382 * Add navigation nodes 383 * @param navigation_node $coursenode 384 * @param object $course 385 * @return void 386 */ 387 function enrol_add_course_navigation(navigation_node $coursenode, $course) { 388 global $CFG; 389 390 $coursecontext = context_course::instance($course->id); 391 392 $instances = enrol_get_instances($course->id, true); 393 $plugins = enrol_get_plugins(true); 394 395 // we do not want to break all course pages if there is some borked enrol plugin, right? 396 foreach ($instances as $k=>$instance) { 397 if (!isset($plugins[$instance->enrol])) { 398 unset($instances[$k]); 399 } 400 } 401 402 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users'); 403 404 if ($course->id != SITEID) { 405 // list all participants - allows assigning roles, groups, etc. 406 if (has_capability('moodle/course:enrolreview', $coursecontext)) { 407 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id)); 408 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', '')); 409 } 410 411 // manage enrol plugin instances 412 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) { 413 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id)); 414 } else { 415 $url = NULL; 416 } 417 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances'); 418 419 // each instance decides how to configure itself or how many other nav items are exposed 420 foreach ($instances as $instance) { 421 if (!isset($plugins[$instance->enrol])) { 422 continue; 423 } 424 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance); 425 } 426 427 if (!$url) { 428 $instancesnode->trim_if_empty(); 429 } 430 } 431 432 // Manage groups in this course or even frontpage 433 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) { 434 $url = new moodle_url('/group/index.php', array('id'=>$course->id)); 435 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', '')); 436 } 437 438 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) { 439 // Override roles 440 if (has_capability('moodle/role:review', $coursecontext)) { 441 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id)); 442 } else { 443 $url = NULL; 444 } 445 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override'); 446 447 // Add assign or override roles if allowed 448 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) { 449 if (has_capability('moodle/role:assign', $coursecontext)) { 450 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id)); 451 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); 452 } 453 } 454 // Check role permissions 455 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) { 456 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id)); 457 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', '')); 458 } 459 } 460 461 // Deal somehow with users that are not enrolled but still got a role somehow 462 if ($course->id != SITEID) { 463 //TODO, create some new UI for role assignments at course level 464 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) { 465 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id)); 466 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', '')); 467 } 468 } 469 470 // just in case nothing was actually added 471 $usersnode->trim_if_empty(); 472 473 if ($course->id != SITEID) { 474 if (isguestuser() or !isloggedin()) { 475 // guest account can not be enrolled - no links for them 476 } else if (is_enrolled($coursecontext)) { 477 // unenrol link if possible 478 foreach ($instances as $instance) { 479 if (!isset($plugins[$instance->enrol])) { 480 continue; 481 } 482 $plugin = $plugins[$instance->enrol]; 483 if ($unenrollink = $plugin->get_unenrolself_link($instance)) { 484 $shortname = format_string($course->shortname, true, array('context' => $coursecontext)); 485 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', '')); 486 break; 487 //TODO. deal with multiple unenrol links - not likely case, but still... 488 } 489 } 490 } else { 491 // enrol link if possible 492 if (is_viewing($coursecontext)) { 493 // better not show any enrol link, this is intended for managers and inspectors 494 } else { 495 foreach ($instances as $instance) { 496 if (!isset($plugins[$instance->enrol])) { 497 continue; 498 } 499 $plugin = $plugins[$instance->enrol]; 500 if ($plugin->show_enrolme_link($instance)) { 501 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id)); 502 $shortname = format_string($course->shortname, true, array('context' => $coursecontext)); 503 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', '')); 504 break; 505 } 506 } 507 } 508 } 509 } 510 } 511 512 /** 513 * Returns list of courses current $USER is enrolled in and can access 514 * 515 * - $fields is an array of field names to ADD 516 * so name the fields you really need, which will 517 * be added and uniq'd 518 * 519 * @param string|array $fields 520 * @param string $sort 521 * @param int $limit max number of courses 522 * @return array 523 */ 524 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) { 525 global $DB, $USER; 526 527 // Guest account does not have any courses 528 if (isguestuser() or !isloggedin()) { 529 return(array()); 530 } 531 532 $basefields = array('id', 'category', 'sortorder', 533 'shortname', 'fullname', 'idnumber', 534 'startdate', 'visible', 535 'groupmode', 'groupmodeforce', 'cacherev'); 536 537 if (empty($fields)) { 538 $fields = $basefields; 539 } else if (is_string($fields)) { 540 // turn the fields from a string to an array 541 $fields = explode(',', $fields); 542 $fields = array_map('trim', $fields); 543 $fields = array_unique(array_merge($basefields, $fields)); 544 } else if (is_array($fields)) { 545 $fields = array_unique(array_merge($basefields, $fields)); 546 } else { 547 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()'); 548 } 549 if (in_array('*', $fields)) { 550 $fields = array('*'); 551 } 552 553 $orderby = ""; 554 $sort = trim($sort); 555 if (!empty($sort)) { 556 $rawsorts = explode(',', $sort); 557 $sorts = array(); 558 foreach ($rawsorts as $rawsort) { 559 $rawsort = trim($rawsort); 560 if (strpos($rawsort, 'c.') === 0) { 561 $rawsort = substr($rawsort, 2); 562 } 563 $sorts[] = trim($rawsort); 564 } 565 $sort = 'c.'.implode(',c.', $sorts); 566 $orderby = "ORDER BY $sort"; 567 } 568 569 $wheres = array("c.id <> :siteid"); 570 $params = array('siteid'=>SITEID); 571 572 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) { 573 // list _only_ this course - anything else is asking for trouble... 574 $wheres[] = "courseid = :loginas"; 575 $params['loginas'] = $USER->loginascontext->instanceid; 576 } 577 578 $coursefields = 'c.' .join(',c.', $fields); 579 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 580 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 581 $params['contextlevel'] = CONTEXT_COURSE; 582 $wheres = implode(" AND ", $wheres); 583 584 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there 585 $sql = "SELECT $coursefields $ccselect 586 FROM {course} c 587 JOIN (SELECT DISTINCT e.courseid 588 FROM {enrol} e 589 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid) 590 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2) 591 ) en ON (en.courseid = c.id) 592 $ccjoin 593 WHERE $wheres 594 $orderby"; 595 $params['userid'] = $USER->id; 596 $params['active'] = ENROL_USER_ACTIVE; 597 $params['enabled'] = ENROL_INSTANCE_ENABLED; 598 $params['now1'] = round(time(), -2); // improves db caching 599 $params['now2'] = $params['now1']; 600 601 $courses = $DB->get_records_sql($sql, $params, 0, $limit); 602 603 // preload contexts and check visibility 604 foreach ($courses as $id=>$course) { 605 context_helper::preload_from_record($course); 606 if (!$course->visible) { 607 if (!$context = context_course::instance($id, IGNORE_MISSING)) { 608 unset($courses[$id]); 609 continue; 610 } 611 if (!has_capability('moodle/course:viewhiddencourses', $context)) { 612 unset($courses[$id]); 613 continue; 614 } 615 } 616 $courses[$id] = $course; 617 } 618 619 //wow! Is that really all? :-D 620 621 return $courses; 622 } 623 624 /** 625 * Returns course enrolment information icons. 626 * 627 * @param object $course 628 * @param array $instances enrol instances of this course, improves performance 629 * @return array of pix_icon 630 */ 631 function enrol_get_course_info_icons($course, array $instances = NULL) { 632 $icons = array(); 633 if (is_null($instances)) { 634 $instances = enrol_get_instances($course->id, true); 635 } 636 $plugins = enrol_get_plugins(true); 637 foreach ($plugins as $name => $plugin) { 638 $pis = array(); 639 foreach ($instances as $instance) { 640 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) { 641 debugging('Invalid instances parameter submitted in enrol_get_info_icons()'); 642 continue; 643 } 644 if ($instance->enrol == $name) { 645 $pis[$instance->id] = $instance; 646 } 647 } 648 if ($pis) { 649 $icons = array_merge($icons, $plugin->get_info_icons($pis)); 650 } 651 } 652 return $icons; 653 } 654 655 /** 656 * Returns course enrolment detailed information. 657 * 658 * @param object $course 659 * @return array of html fragments - can be used to construct lists 660 */ 661 function enrol_get_course_description_texts($course) { 662 $lines = array(); 663 $instances = enrol_get_instances($course->id, true); 664 $plugins = enrol_get_plugins(true); 665 foreach ($instances as $instance) { 666 if (!isset($plugins[$instance->enrol])) { 667 //weird 668 continue; 669 } 670 $plugin = $plugins[$instance->enrol]; 671 $text = $plugin->get_description_text($instance); 672 if ($text !== NULL) { 673 $lines[] = $text; 674 } 675 } 676 return $lines; 677 } 678 679 /** 680 * Returns list of courses user is enrolled into. 681 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks ) 682 * 683 * - $fields is an array of fieldnames to ADD 684 * so name the fields you really need, which will 685 * be added and uniq'd 686 * 687 * @param int $userid 688 * @param bool $onlyactive return only active enrolments in courses user may see 689 * @param string|array $fields 690 * @param string $sort 691 * @return array 692 */ 693 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') { 694 global $DB; 695 696 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort); 697 698 // preload contexts and check visibility 699 if ($onlyactive) { 700 foreach ($courses as $id=>$course) { 701 context_helper::preload_from_record($course); 702 if (!$course->visible) { 703 if (!$context = context_course::instance($id)) { 704 unset($courses[$id]); 705 continue; 706 } 707 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) { 708 unset($courses[$id]); 709 continue; 710 } 711 } 712 } 713 } 714 715 return $courses; 716 717 } 718 719 /** 720 * Can user access at least one enrolled course? 721 * 722 * Cheat if necessary, but find out as fast as possible! 723 * 724 * @param int|stdClass $user null means use current user 725 * @return bool 726 */ 727 function enrol_user_sees_own_courses($user = null) { 728 global $USER; 729 730 if ($user === null) { 731 $user = $USER; 732 } 733 $userid = is_object($user) ? $user->id : $user; 734 735 // Guest account does not have any courses 736 if (isguestuser($userid) or empty($userid)) { 737 return false; 738 } 739 740 // Let's cheat here if this is the current user, 741 // if user accessed any course recently, then most probably 742 // we do not need to query the database at all. 743 if ($USER->id == $userid) { 744 if (!empty($USER->enrol['enrolled'])) { 745 foreach ($USER->enrol['enrolled'] as $until) { 746 if ($until > time()) { 747 return true; 748 } 749 } 750 } 751 } 752 753 // Now the slow way. 754 $courses = enrol_get_all_users_courses($userid, true); 755 foreach($courses as $course) { 756 if ($course->visible) { 757 return true; 758 } 759 context_helper::preload_from_record($course); 760 $context = context_course::instance($course->id); 761 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) { 762 return true; 763 } 764 } 765 766 return false; 767 } 768 769 /** 770 * Returns list of courses user is enrolled into without any capability checks 771 * - $fields is an array of fieldnames to ADD 772 * so name the fields you really need, which will 773 * be added and uniq'd 774 * 775 * @param int $userid 776 * @param bool $onlyactive return only active enrolments in courses user may see 777 * @param string|array $fields 778 * @param string $sort 779 * @return array 780 */ 781 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') { 782 global $DB; 783 784 // Guest account does not have any courses 785 if (isguestuser($userid) or empty($userid)) { 786 return(array()); 787 } 788 789 $basefields = array('id', 'category', 'sortorder', 790 'shortname', 'fullname', 'idnumber', 791 'startdate', 'visible', 792 'defaultgroupingid', 793 'groupmode', 'groupmodeforce'); 794 795 if (empty($fields)) { 796 $fields = $basefields; 797 } else if (is_string($fields)) { 798 // turn the fields from a string to an array 799 $fields = explode(',', $fields); 800 $fields = array_map('trim', $fields); 801 $fields = array_unique(array_merge($basefields, $fields)); 802 } else if (is_array($fields)) { 803 $fields = array_unique(array_merge($basefields, $fields)); 804 } else { 805 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()'); 806 } 807 if (in_array('*', $fields)) { 808 $fields = array('*'); 809 } 810 811 $orderby = ""; 812 $sort = trim($sort); 813 if (!empty($sort)) { 814 $rawsorts = explode(',', $sort); 815 $sorts = array(); 816 foreach ($rawsorts as $rawsort) { 817 $rawsort = trim($rawsort); 818 if (strpos($rawsort, 'c.') === 0) { 819 $rawsort = substr($rawsort, 2); 820 } 821 $sorts[] = trim($rawsort); 822 } 823 $sort = 'c.'.implode(',c.', $sorts); 824 $orderby = "ORDER BY $sort"; 825 } 826 827 $params = array('siteid'=>SITEID); 828 829 if ($onlyactive) { 830 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)"; 831 $params['now1'] = round(time(), -2); // improves db caching 832 $params['now2'] = $params['now1']; 833 $params['active'] = ENROL_USER_ACTIVE; 834 $params['enabled'] = ENROL_INSTANCE_ENABLED; 835 } else { 836 $subwhere = ""; 837 } 838 839 $coursefields = 'c.' .join(',c.', $fields); 840 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 841 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 842 $params['contextlevel'] = CONTEXT_COURSE; 843 844 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there 845 $sql = "SELECT $coursefields $ccselect 846 FROM {course} c 847 JOIN (SELECT DISTINCT e.courseid 848 FROM {enrol} e 849 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid) 850 $subwhere 851 ) en ON (en.courseid = c.id) 852 $ccjoin 853 WHERE c.id <> :siteid 854 $orderby"; 855 $params['userid'] = $userid; 856 857 $courses = $DB->get_records_sql($sql, $params); 858 859 return $courses; 860 } 861 862 863 864 /** 865 * Called when user is about to be deleted. 866 * @param object $user 867 * @return void 868 */ 869 function enrol_user_delete($user) { 870 global $DB; 871 872 $plugins = enrol_get_plugins(true); 873 foreach ($plugins as $plugin) { 874 $plugin->user_delete($user); 875 } 876 877 // force cleanup of all broken enrolments 878 $DB->delete_records('user_enrolments', array('userid'=>$user->id)); 879 } 880 881 /** 882 * Called when course is about to be deleted. 883 * @param stdClass $course 884 * @return void 885 */ 886 function enrol_course_delete($course) { 887 global $DB; 888 889 $instances = enrol_get_instances($course->id, false); 890 $plugins = enrol_get_plugins(true); 891 foreach ($instances as $instance) { 892 if (isset($plugins[$instance->enrol])) { 893 $plugins[$instance->enrol]->delete_instance($instance); 894 } 895 // low level delete in case plugin did not do it 896 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id)); 897 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol)); 898 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id)); 899 $DB->delete_records('enrol', array('id'=>$instance->id)); 900 } 901 } 902 903 /** 904 * Try to enrol user via default internal auth plugin. 905 * 906 * For now this is always using the manual enrol plugin... 907 * 908 * @param $courseid 909 * @param $userid 910 * @param $roleid 911 * @param $timestart 912 * @param $timeend 913 * @return bool success 914 */ 915 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) { 916 global $DB; 917 918 //note: this is hardcoded to manual plugin for now 919 920 if (!enrol_is_enabled('manual')) { 921 return false; 922 } 923 924 if (!$enrol = enrol_get_plugin('manual')) { 925 return false; 926 } 927 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) { 928 return false; 929 } 930 $instance = reset($instances); 931 932 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend); 933 934 return true; 935 } 936 937 /** 938 * Is there a chance users might self enrol 939 * @param int $courseid 940 * @return bool 941 */ 942 function enrol_selfenrol_available($courseid) { 943 $result = false; 944 945 $plugins = enrol_get_plugins(true); 946 $enrolinstances = enrol_get_instances($courseid, true); 947 foreach($enrolinstances as $instance) { 948 if (!isset($plugins[$instance->enrol])) { 949 continue; 950 } 951 if ($instance->enrol === 'guest') { 952 // blacklist known temporary guest plugins 953 continue; 954 } 955 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) { 956 $result = true; 957 break; 958 } 959 } 960 961 return $result; 962 } 963 964 /** 965 * This function returns the end of current active user enrolment. 966 * 967 * It deals correctly with multiple overlapping user enrolments. 968 * 969 * @param int $courseid 970 * @param int $userid 971 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never 972 */ 973 function enrol_get_enrolment_end($courseid, $userid) { 974 global $DB; 975 976 $sql = "SELECT ue.* 977 FROM {user_enrolments} ue 978 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid) 979 JOIN {user} u ON u.id = ue.userid 980 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0"; 981 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid); 982 983 if (!$enrolments = $DB->get_records_sql($sql, $params)) { 984 return false; 985 } 986 987 $changes = array(); 988 989 foreach ($enrolments as $ue) { 990 $start = (int)$ue->timestart; 991 $end = (int)$ue->timeend; 992 if ($end != 0 and $end < $start) { 993 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id); 994 continue; 995 } 996 if (isset($changes[$start])) { 997 $changes[$start] = $changes[$start] + 1; 998 } else { 999 $changes[$start] = 1; 1000 } 1001 if ($end === 0) { 1002 // no end 1003 } else if (isset($changes[$end])) { 1004 $changes[$end] = $changes[$end] - 1; 1005 } else { 1006 $changes[$end] = -1; 1007 } 1008 } 1009 1010 // let's sort then enrolment starts&ends and go through them chronologically, 1011 // looking for current status and the next future end of enrolment 1012 ksort($changes); 1013 1014 $now = time(); 1015 $current = 0; 1016 $present = null; 1017 1018 foreach ($changes as $time => $change) { 1019 if ($time > $now) { 1020 if ($present === null) { 1021 // we have just went past current time 1022 $present = $current; 1023 if ($present < 1) { 1024 // no enrolment active 1025 return false; 1026 } 1027 } 1028 if ($present !== null) { 1029 // we are already in the future - look for possible end 1030 if ($current + $change < 1) { 1031 return $time; 1032 } 1033 } 1034 } 1035 $current += $change; 1036 } 1037 1038 if ($current > 0) { 1039 return 0; 1040 } else { 1041 return false; 1042 } 1043 } 1044 1045 /** 1046 * Is current user accessing course via this enrolment method? 1047 * 1048 * This is intended for operations that are going to affect enrol instances. 1049 * 1050 * @param stdClass $instance enrol instance 1051 * @return bool 1052 */ 1053 function enrol_accessing_via_instance(stdClass $instance) { 1054 global $DB, $USER; 1055 1056 if (empty($instance->id)) { 1057 return false; 1058 } 1059 1060 if (is_siteadmin()) { 1061 // Admins may go anywhere. 1062 return false; 1063 } 1064 1065 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id)); 1066 } 1067 1068 1069 /** 1070 * All enrol plugins should be based on this class, 1071 * this is also the main source of documentation. 1072 */ 1073 abstract class enrol_plugin { 1074 protected $config = null; 1075 1076 /** 1077 * Returns name of this enrol plugin 1078 * @return string 1079 */ 1080 public function get_name() { 1081 // second word in class is always enrol name, sorry, no fancy plugin names with _ 1082 $words = explode('_', get_class($this)); 1083 return $words[1]; 1084 } 1085 1086 /** 1087 * Returns localised name of enrol instance 1088 * 1089 * @param object $instance (null is accepted too) 1090 * @return string 1091 */ 1092 public function get_instance_name($instance) { 1093 if (empty($instance->name)) { 1094 $enrol = $this->get_name(); 1095 return get_string('pluginname', 'enrol_'.$enrol); 1096 } else { 1097 $context = context_course::instance($instance->courseid); 1098 return format_string($instance->name, true, array('context'=>$context)); 1099 } 1100 } 1101 1102 /** 1103 * Returns optional enrolment information icons. 1104 * 1105 * This is used in course list for quick overview of enrolment options. 1106 * 1107 * We are not using single instance parameter because sometimes 1108 * we might want to prevent icon repetition when multiple instances 1109 * of one type exist. One instance may also produce several icons. 1110 * 1111 * @param array $instances all enrol instances of this type in one course 1112 * @return array of pix_icon 1113 */ 1114 public function get_info_icons(array $instances) { 1115 return array(); 1116 } 1117 1118 /** 1119 * Returns optional enrolment instance description text. 1120 * 1121 * This is used in detailed course information. 1122 * 1123 * 1124 * @param object $instance 1125 * @return string short html text 1126 */ 1127 public function get_description_text($instance) { 1128 return null; 1129 } 1130 1131 /** 1132 * Makes sure config is loaded and cached. 1133 * @return void 1134 */ 1135 protected function load_config() { 1136 if (!isset($this->config)) { 1137 $name = $this->get_name(); 1138 $this->config = get_config("enrol_$name"); 1139 } 1140 } 1141 1142 /** 1143 * Returns plugin config value 1144 * @param string $name 1145 * @param string $default value if config does not exist yet 1146 * @return string value or default 1147 */ 1148 public function get_config($name, $default = NULL) { 1149 $this->load_config(); 1150 return isset($this->config->$name) ? $this->config->$name : $default; 1151 } 1152 1153 /** 1154 * Sets plugin config value 1155 * @param string $name name of config 1156 * @param string $value string config value, null means delete 1157 * @return string value 1158 */ 1159 public function set_config($name, $value) { 1160 $pluginname = $this->get_name(); 1161 $this->load_config(); 1162 if ($value === NULL) { 1163 unset($this->config->$name); 1164 } else { 1165 $this->config->$name = $value; 1166 } 1167 set_config($name, $value, "enrol_$pluginname"); 1168 } 1169 1170 /** 1171 * Does this plugin assign protected roles are can they be manually removed? 1172 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles 1173 */ 1174 public function roles_protected() { 1175 return true; 1176 } 1177 1178 /** 1179 * Does this plugin allow manual enrolments? 1180 * 1181 * @param stdClass $instance course enrol instance 1182 * All plugins allowing this must implement 'enrol/xxx:enrol' capability 1183 * 1184 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually 1185 */ 1186 public function allow_enrol(stdClass $instance) { 1187 return false; 1188 } 1189 1190 /** 1191 * Does this plugin allow manual unenrolment of all users? 1192 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability 1193 * 1194 * @param stdClass $instance course enrol instance 1195 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments 1196 */ 1197 public function allow_unenrol(stdClass $instance) { 1198 return false; 1199 } 1200 1201 /** 1202 * Does this plugin allow manual unenrolment of a specific user? 1203 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability 1204 * 1205 * This is useful especially for synchronisation plugins that 1206 * do suspend instead of full unenrolment. 1207 * 1208 * @param stdClass $instance course enrol instance 1209 * @param stdClass $ue record from user_enrolments table, specifies user 1210 * 1211 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment 1212 */ 1213 public function allow_unenrol_user(stdClass $instance, stdClass $ue) { 1214 return $this->allow_unenrol($instance); 1215 } 1216 1217 /** 1218 * Does this plugin allow manual changes in user_enrolments table? 1219 * 1220 * All plugins allowing this must implement 'enrol/xxx:manage' capability 1221 * 1222 * @param stdClass $instance course enrol instance 1223 * @return bool - true means it is possible to change enrol period and status in user_enrolments table 1224 */ 1225 public function allow_manage(stdClass $instance) { 1226 return false; 1227 } 1228 1229 /** 1230 * Does this plugin support some way to user to self enrol? 1231 * 1232 * @param stdClass $instance course enrol instance 1233 * 1234 * @return bool - true means show "Enrol me in this course" link in course UI 1235 */ 1236 public function show_enrolme_link(stdClass $instance) { 1237 return false; 1238 } 1239 1240 /** 1241 * Attempt to automatically enrol current user in course without any interaction, 1242 * calling code has to make sure the plugin and instance are active. 1243 * 1244 * This should return either a timestamp in the future or false. 1245 * 1246 * @param stdClass $instance course enrol instance 1247 * @return bool|int false means not enrolled, integer means timeend 1248 */ 1249 public function try_autoenrol(stdClass $instance) { 1250 global $USER; 1251 1252 return false; 1253 } 1254 1255 /** 1256 * Attempt to automatically gain temporary guest access to course, 1257 * calling code has to make sure the plugin and instance are active. 1258 * 1259 * This should return either a timestamp in the future or false. 1260 * 1261 * @param stdClass $instance course enrol instance 1262 * @return bool|int false means no guest access, integer means timeend 1263 */ 1264 public function try_guestaccess(stdClass $instance) { 1265 global $USER; 1266 1267 return false; 1268 } 1269 1270 /** 1271 * Enrol user into course via enrol instance. 1272 * 1273 * @param stdClass $instance 1274 * @param int $userid 1275 * @param int $roleid optional role id 1276 * @param int $timestart 0 means unknown 1277 * @param int $timeend 0 means forever 1278 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates 1279 * @param bool $recovergrades restore grade history 1280 * @return void 1281 */ 1282 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) { 1283 global $DB, $USER, $CFG; // CFG necessary!!! 1284 1285 if ($instance->courseid == SITEID) { 1286 throw new coding_exception('invalid attempt to enrol into frontpage course!'); 1287 } 1288 1289 $name = $this->get_name(); 1290 $courseid = $instance->courseid; 1291 1292 if ($instance->enrol !== $name) { 1293 throw new coding_exception('invalid enrol instance!'); 1294 } 1295 $context = context_course::instance($instance->courseid, MUST_EXIST); 1296 if (!isset($recovergrades)) { 1297 $recovergrades = $CFG->recovergradesdefault; 1298 } 1299 1300 $inserted = false; 1301 $updated = false; 1302 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) { 1303 //only update if timestart or timeend or status are different. 1304 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) { 1305 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend); 1306 } 1307 } else { 1308 $ue = new stdClass(); 1309 $ue->enrolid = $instance->id; 1310 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status; 1311 $ue->userid = $userid; 1312 $ue->timestart = $timestart; 1313 $ue->timeend = $timeend; 1314 $ue->modifierid = $USER->id; 1315 $ue->timecreated = time(); 1316 $ue->timemodified = $ue->timecreated; 1317 $ue->id = $DB->insert_record('user_enrolments', $ue); 1318 1319 $inserted = true; 1320 } 1321 1322 if ($inserted) { 1323 // Trigger event. 1324 $event = \core\event\user_enrolment_created::create( 1325 array( 1326 'objectid' => $ue->id, 1327 'courseid' => $courseid, 1328 'context' => $context, 1329 'relateduserid' => $ue->userid, 1330 'other' => array('enrol' => $name) 1331 ) 1332 ); 1333 $event->trigger(); 1334 // Check if course contacts cache needs to be cleared. 1335 require_once($CFG->libdir . '/coursecatlib.php'); 1336 coursecat::user_enrolment_changed($courseid, $ue->userid, 1337 $ue->status, $ue->timestart, $ue->timeend); 1338 } 1339 1340 if ($roleid) { 1341 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards 1342 if ($this->roles_protected()) { 1343 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id); 1344 } else { 1345 role_assign($roleid, $userid, $context->id); 1346 } 1347 } 1348 1349 // Recover old grades if present. 1350 if ($recovergrades) { 1351 require_once("$CFG->libdir/gradelib.php"); 1352 grade_recover_history_grades($userid, $courseid); 1353 } 1354 1355 // reset current user enrolment caching 1356 if ($userid == $USER->id) { 1357 if (isset($USER->enrol['enrolled'][$courseid])) { 1358 unset($USER->enrol['enrolled'][$courseid]); 1359 } 1360 if (isset($USER->enrol['tempguest'][$courseid])) { 1361 unset($USER->enrol['tempguest'][$courseid]); 1362 remove_temp_course_roles($context); 1363 } 1364 } 1365 } 1366 1367 /** 1368 * Store user_enrolments changes and trigger event. 1369 * 1370 * @param stdClass $instance 1371 * @param int $userid 1372 * @param int $status 1373 * @param int $timestart 1374 * @param int $timeend 1375 * @return void 1376 */ 1377 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) { 1378 global $DB, $USER, $CFG; 1379 1380 $name = $this->get_name(); 1381 1382 if ($instance->enrol !== $name) { 1383 throw new coding_exception('invalid enrol instance!'); 1384 } 1385 1386 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) { 1387 // weird, user not enrolled 1388 return; 1389 } 1390 1391 $modified = false; 1392 if (isset($status) and $ue->status != $status) { 1393 $ue->status = $status; 1394 $modified = true; 1395 } 1396 if (isset($timestart) and $ue->timestart != $timestart) { 1397 $ue->timestart = $timestart; 1398 $modified = true; 1399 } 1400 if (isset($timeend) and $ue->timeend != $timeend) { 1401 $ue->timeend = $timeend; 1402 $modified = true; 1403 } 1404 1405 if (!$modified) { 1406 // no change 1407 return; 1408 } 1409 1410 $ue->modifierid = $USER->id; 1411 $DB->update_record('user_enrolments', $ue); 1412 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches 1413 1414 // Invalidate core_access cache for get_suspended_userids. 1415 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid)); 1416 1417 // Trigger event. 1418 $event = \core\event\user_enrolment_updated::create( 1419 array( 1420 'objectid' => $ue->id, 1421 'courseid' => $instance->courseid, 1422 'context' => context_course::instance($instance->courseid), 1423 'relateduserid' => $ue->userid, 1424 'other' => array('enrol' => $name) 1425 ) 1426 ); 1427 $event->trigger(); 1428 1429 require_once($CFG->libdir . '/coursecatlib.php'); 1430 coursecat::user_enrolment_changed($instance->courseid, $ue->userid, 1431 $ue->status, $ue->timestart, $ue->timeend); 1432 } 1433 1434 /** 1435 * Unenrol user from course, 1436 * the last unenrolment removes all remaining roles. 1437 * 1438 * @param stdClass $instance 1439 * @param int $userid 1440 * @return void 1441 */ 1442 public function unenrol_user(stdClass $instance, $userid) { 1443 global $CFG, $USER, $DB; 1444 require_once("$CFG->dirroot/group/lib.php"); 1445 1446 $name = $this->get_name(); 1447 $courseid = $instance->courseid; 1448 1449 if ($instance->enrol !== $name) { 1450 throw new coding_exception('invalid enrol instance!'); 1451 } 1452 $context = context_course::instance($instance->courseid, MUST_EXIST); 1453 1454 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) { 1455 // weird, user not enrolled 1456 return; 1457 } 1458 1459 // Remove all users groups linked to this enrolment instance. 1460 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) { 1461 foreach ($gms as $gm) { 1462 groups_remove_member($gm->groupid, $gm->userid); 1463 } 1464 } 1465 1466 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id)); 1467 $DB->delete_records('user_enrolments', array('id'=>$ue->id)); 1468 1469 // add extra info and trigger event 1470 $ue->courseid = $courseid; 1471 $ue->enrol = $name; 1472 1473 $sql = "SELECT 'x' 1474 FROM {user_enrolments} ue 1475 JOIN {enrol} e ON (e.id = ue.enrolid) 1476 WHERE ue.userid = :userid AND e.courseid = :courseid"; 1477 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) { 1478 $ue->lastenrol = false; 1479 1480 } else { 1481 // the big cleanup IS necessary! 1482 require_once("$CFG->libdir/gradelib.php"); 1483 1484 // remove all remaining roles 1485 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false); 1486 1487 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc. 1488 groups_delete_group_members($courseid, $userid); 1489 1490 grade_user_unenrol($courseid, $userid); 1491 1492 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid)); 1493 1494 $ue->lastenrol = true; // means user not enrolled any more 1495 } 1496 // Trigger event. 1497 $event = \core\event\user_enrolment_deleted::create( 1498 array( 1499 'courseid' => $courseid, 1500 'context' => $context, 1501 'relateduserid' => $ue->userid, 1502 'objectid' => $ue->id, 1503 'other' => array( 1504 'userenrolment' => (array)$ue, 1505 'enrol' => $name 1506 ) 1507 ) 1508 ); 1509 $event->trigger(); 1510 // reset all enrol caches 1511 $context->mark_dirty(); 1512 1513 // Check if courrse contacts cache needs to be cleared. 1514 require_once($CFG->libdir . '/coursecatlib.php'); 1515 coursecat::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED); 1516 1517 // reset current user enrolment caching 1518 if ($userid == $USER->id) { 1519 if (isset($USER->enrol['enrolled'][$courseid])) { 1520 unset($USER->enrol['enrolled'][$courseid]); 1521 } 1522 if (isset($USER->enrol['tempguest'][$courseid])) { 1523 unset($USER->enrol['tempguest'][$courseid]); 1524 remove_temp_course_roles($context); 1525 } 1526 } 1527 } 1528 1529 /** 1530 * Forces synchronisation of user enrolments. 1531 * 1532 * This is important especially for external enrol plugins, 1533 * this function is called for all enabled enrol plugins 1534 * right after every user login. 1535 * 1536 * @param object $user user record 1537 * @return void 1538 */ 1539 public function sync_user_enrolments($user) { 1540 // override if necessary 1541 } 1542 1543 /** 1544 * This returns false for backwards compatibility, but it is really recommended. 1545 * 1546 * @since Moodle 3.1 1547 * @return boolean 1548 */ 1549 public function use_standard_editing_ui() { 1550 return false; 1551 } 1552 1553 /** 1554 * Return whether or not, given the current state, it is possible to add a new instance 1555 * of this enrolment plugin to the course. 1556 * 1557 * Default implementation is just for backwards compatibility. 1558 * 1559 * @param int $courseid 1560 * @return boolean 1561 */ 1562 public function can_add_instance($courseid) { 1563 $link = $this->get_newinstance_link($courseid); 1564 return !empty($link); 1565 } 1566 1567 /** 1568 * Return whether or not, given the current state, it is possible to edit an instance 1569 * of this enrolment plugin in the course. Used by the standard editing UI 1570 * to generate a link to the edit instance form if editing is allowed. 1571 * 1572 * @param stdClass $instance 1573 * @return boolean 1574 */ 1575 public function can_edit_instance($instance) { 1576 $context = context_course::instance($instance->courseid); 1577 1578 return has_capability('enrol/' . $instance->enrol . ':config', $context); 1579 } 1580 1581 /** 1582 * Returns link to page which may be used to add new instance of enrolment plugin in course. 1583 * @param int $courseid 1584 * @return moodle_url page url 1585 */ 1586 public function get_newinstance_link($courseid) { 1587 // override for most plugins, check if instance already exists in cases only one instance is supported 1588 return NULL; 1589 } 1590 1591 /** 1592 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead. 1593 */ 1594 public function instance_deleteable($instance) { 1595 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use 1596 enrol_plugin::can_delete_instance() instead'); 1597 } 1598 1599 /** 1600 * Is it possible to delete enrol instance via standard UI? 1601 * 1602 * @param stdClass $instance 1603 * @return bool 1604 */ 1605 public function can_delete_instance($instance) { 1606 return false; 1607 } 1608 1609 /** 1610 * Is it possible to hide/show enrol instance via standard UI? 1611 * 1612 * @param stdClass $instance 1613 * @return bool 1614 */ 1615 public function can_hide_show_instance($instance) { 1616 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER); 1617 return true; 1618 } 1619 1620 /** 1621 * Returns link to manual enrol UI if exists. 1622 * Does the access control tests automatically. 1623 * 1624 * @param object $instance 1625 * @return moodle_url 1626 */ 1627 public function get_manual_enrol_link($instance) { 1628 return NULL; 1629 } 1630 1631 /** 1632 * Returns list of unenrol links for all enrol instances in course. 1633 * 1634 * @param int $instance 1635 * @return moodle_url or NULL if self unenrolment not supported 1636 */ 1637 public function get_unenrolself_link($instance) { 1638 global $USER, $CFG, $DB; 1639 1640 $name = $this->get_name(); 1641 if ($instance->enrol !== $name) { 1642 throw new coding_exception('invalid enrol instance!'); 1643 } 1644 1645 if ($instance->courseid == SITEID) { 1646 return NULL; 1647 } 1648 1649 if (!enrol_is_enabled($name)) { 1650 return NULL; 1651 } 1652 1653 if ($instance->status != ENROL_INSTANCE_ENABLED) { 1654 return NULL; 1655 } 1656 1657 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) { 1658 return NULL; 1659 } 1660 1661 $context = context_course::instance($instance->courseid, MUST_EXIST); 1662 1663 if (!has_capability("enrol/$name:unenrolself", $context)) { 1664 return NULL; 1665 } 1666 1667 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) { 1668 return NULL; 1669 } 1670 1671 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id)); 1672 } 1673 1674 /** 1675 * Adds enrol instance UI to course edit form 1676 * 1677 * @param object $instance enrol instance or null if does not exist yet 1678 * @param MoodleQuickForm $mform 1679 * @param object $data 1680 * @param object $context context of existing course or parent category if course does not exist 1681 * @return void 1682 */ 1683 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) { 1684 // override - usually at least enable/disable switch, has to add own form header 1685 } 1686 1687 /** 1688 * Adds form elements to add/edit instance form. 1689 * 1690 * @since Moodle 3.1 1691 * @param object $instance enrol instance or null if does not exist yet 1692 * @param MoodleQuickForm $mform 1693 * @param context $context 1694 * @return void 1695 */ 1696 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) { 1697 // Do nothing by default. 1698 } 1699 1700 /** 1701 * Perform custom validation of the data used to edit the instance. 1702 * 1703 * @since Moodle 3.1 1704 * @param array $data array of ("fieldname"=>value) of submitted data 1705 * @param array $files array of uploaded files "element_name"=>tmp_file_path 1706 * @param object $instance The instance data loaded from the DB. 1707 * @param context $context The context of the instance we are editing 1708 * @return array of "element_name"=>"error_description" if there are errors, 1709 * or an empty array if everything is OK. 1710 */ 1711 public function edit_instance_validation($data, $files, $instance, $context) { 1712 // No errors by default. 1713 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER); 1714 return array(); 1715 } 1716 1717 /** 1718 * Validates course edit form data 1719 * 1720 * @param object $instance enrol instance or null if does not exist yet 1721 * @param array $data 1722 * @param object $context context of existing course or parent category if course does not exist 1723 * @return array errors array 1724 */ 1725 public function course_edit_validation($instance, array $data, $context) { 1726 return array(); 1727 } 1728 1729 /** 1730 * Called after updating/inserting course. 1731 * 1732 * @param bool $inserted true if course just inserted 1733 * @param object $course 1734 * @param object $data form data 1735 * @return void 1736 */ 1737 public function course_updated($inserted, $course, $data) { 1738 if ($inserted) { 1739 if ($this->get_config('defaultenrol')) { 1740 $this->add_default_instance($course); 1741 } 1742 } 1743 } 1744 1745 /** 1746 * Add new instance of enrol plugin. 1747 * @param object $course 1748 * @param array instance fields 1749 * @return int id of new instance, null if can not be created 1750 */ 1751 public function add_instance($course, array $fields = NULL) { 1752 global $DB; 1753 1754 if ($course->id == SITEID) { 1755 throw new coding_exception('Invalid request to add enrol instance to frontpage.'); 1756 } 1757 1758 $instance = new stdClass(); 1759 $instance->enrol = $this->get_name(); 1760 $instance->status = ENROL_INSTANCE_ENABLED; 1761 $instance->courseid = $course->id; 1762 $instance->enrolstartdate = 0; 1763 $instance->enrolenddate = 0; 1764 $instance->timemodified = time(); 1765 $instance->timecreated = $instance->timemodified; 1766 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id)); 1767 1768 $fields = (array)$fields; 1769 unset($fields['enrol']); 1770 unset($fields['courseid']); 1771 unset($fields['sortorder']); 1772 foreach($fields as $field=>$value) { 1773 $instance->$field = $value; 1774 } 1775 1776 $instance->id = $DB->insert_record('enrol', $instance); 1777 1778 \core\event\enrol_instance_created::create_from_record($instance)->trigger(); 1779 1780 return $instance->id; 1781 } 1782 1783 /** 1784 * Update instance of enrol plugin. 1785 * 1786 * @since Moodle 3.1 1787 * @param stdClass $instance 1788 * @param stdClass $data modified instance fields 1789 * @return boolean 1790 */ 1791 public function update_instance($instance, $data) { 1792 global $DB; 1793 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3', 1794 'customint4', 'customint5', 'customint6', 'customint7', 'customint8', 1795 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2', 1796 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid', 1797 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold', 1798 'enrolstartdate', 'enrolenddate', 'cost', 'currency'); 1799 1800 foreach ($properties as $key) { 1801 if (isset($data->$key)) { 1802 $instance->$key = $data->$key; 1803 } 1804 } 1805 $instance->timemodified = time(); 1806 1807 $update = $DB->update_record('enrol', $instance); 1808 if ($update) { 1809 \core\event\enrol_instance_updated::create_from_record($instance)->trigger(); 1810 } 1811 return $update; 1812 } 1813 1814 /** 1815 * Add new instance of enrol plugin with default settings, 1816 * called when adding new instance manually or when adding new course. 1817 * 1818 * Not all plugins support this. 1819 * 1820 * @param object $course 1821 * @return int id of new instance or null if no default supported 1822 */ 1823 public function add_default_instance($course) { 1824 return null; 1825 } 1826 1827 /** 1828 * Update instance status 1829 * 1830 * Override when plugin needs to do some action when enabled or disabled. 1831 * 1832 * @param stdClass $instance 1833 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED 1834 * @return void 1835 */ 1836 public function update_status($instance, $newstatus) { 1837 global $DB; 1838 1839 $instance->status = $newstatus; 1840 $DB->update_record('enrol', $instance); 1841 1842 $context = context_course::instance($instance->courseid); 1843 \core\event\enrol_instance_updated::create_from_record($instance)->trigger(); 1844 1845 // Invalidate all enrol caches. 1846 $context->mark_dirty(); 1847 } 1848 1849 /** 1850 * Delete course enrol plugin instance, unenrol all users. 1851 * @param object $instance 1852 * @return void 1853 */ 1854 public function delete_instance($instance) { 1855 global $DB; 1856 1857 $name = $this->get_name(); 1858 if ($instance->enrol !== $name) { 1859 throw new coding_exception('invalid enrol instance!'); 1860 } 1861 1862 //first unenrol all users 1863 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id)); 1864 foreach ($participants as $participant) { 1865 $this->unenrol_user($instance, $participant->userid); 1866 } 1867 $participants->close(); 1868 1869 // now clean up all remainders that were not removed correctly 1870 $DB->delete_records('groups_members', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name)); 1871 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name)); 1872 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id)); 1873 1874 // finally drop the enrol row 1875 $DB->delete_records('enrol', array('id'=>$instance->id)); 1876 1877 $context = context_course::instance($instance->courseid); 1878 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger(); 1879 1880 // Invalidate all enrol caches. 1881 $context->mark_dirty(); 1882 } 1883 1884 /** 1885 * Creates course enrol form, checks if form submitted 1886 * and enrols user if necessary. It can also redirect. 1887 * 1888 * @param stdClass $instance 1889 * @return string html text, usually a form in a text box 1890 */ 1891 public function enrol_page_hook(stdClass $instance) { 1892 return null; 1893 } 1894 1895 /** 1896 * Checks if user can self enrol. 1897 * 1898 * @param stdClass $instance enrolment instance 1899 * @param bool $checkuserenrolment if true will check if user enrolment is inactive. 1900 * used by navigation to improve performance. 1901 * @return bool|string true if successful, else error message or false 1902 */ 1903 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) { 1904 return false; 1905 } 1906 1907 /** 1908 * Return information for enrolment instance containing list of parameters required 1909 * for enrolment, name of enrolment plugin etc. 1910 * 1911 * @param stdClass $instance enrolment instance 1912 * @return array instance info. 1913 */ 1914 public function get_enrol_info(stdClass $instance) { 1915 return null; 1916 } 1917 1918 /** 1919 * Adds navigation links into course admin block. 1920 * 1921 * By defaults looks for manage links only. 1922 * 1923 * @param navigation_node $instancesnode 1924 * @param stdClass $instance 1925 * @return void 1926 */ 1927 public function add_course_navigation($instancesnode, stdClass $instance) { 1928 if ($this->use_standard_editing_ui()) { 1929 $context = context_course::instance($instance->courseid); 1930 $cap = 'enrol/' . $instance->enrol . ':config'; 1931 if (has_capability($cap, $context)) { 1932 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol); 1933 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams); 1934 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING); 1935 } 1936 } 1937 } 1938 1939 /** 1940 * Returns edit icons for the page with list of instances 1941 * @param stdClass $instance 1942 * @return array 1943 */ 1944 public function get_action_icons(stdClass $instance) { 1945 global $OUTPUT; 1946 1947 $icons = array(); 1948 if ($this->use_standard_editing_ui()) { 1949 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol); 1950 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams); 1951 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core', 1952 array('class' => 'iconsmall'))); 1953 } 1954 return $icons; 1955 } 1956 1957 /** 1958 * Reads version.php and determines if it is necessary 1959 * to execute the cron job now. 1960 * @return bool 1961 */ 1962 public function is_cron_required() { 1963 global $CFG; 1964 1965 $name = $this->get_name(); 1966 $versionfile = "$CFG->dirroot/enrol/$name/version.php"; 1967 $plugin = new stdClass(); 1968 include($versionfile); 1969 if (empty($plugin->cron)) { 1970 return false; 1971 } 1972 $lastexecuted = $this->get_config('lastcron', 0); 1973 if ($lastexecuted + $plugin->cron < time()) { 1974 return true; 1975 } else { 1976 return false; 1977 } 1978 } 1979 1980 /** 1981 * Called for all enabled enrol plugins that returned true from is_cron_required(). 1982 * @return void 1983 */ 1984 public function cron() { 1985 } 1986 1987 /** 1988 * Called when user is about to be deleted 1989 * @param object $user 1990 * @return void 1991 */ 1992 public function user_delete($user) { 1993 global $DB; 1994 1995 $sql = "SELECT e.* 1996 FROM {enrol} e 1997 JOIN {user_enrolments} ue ON (ue.enrolid = e.id) 1998 WHERE e.enrol = :name AND ue.userid = :userid"; 1999 $params = array('name'=>$this->get_name(), 'userid'=>$user->id); 2000 2001 $rs = $DB->get_recordset_sql($sql, $params); 2002 foreach($rs as $instance) { 2003 $this->unenrol_user($instance, $user->id); 2004 } 2005 $rs->close(); 2006 } 2007 2008 /** 2009 * Returns an enrol_user_button that takes the user to a page where they are able to 2010 * enrol users into the managers course through this plugin. 2011 * 2012 * Optional: If the plugin supports manual enrolments it can choose to override this 2013 * otherwise it shouldn't 2014 * 2015 * @param course_enrolment_manager $manager 2016 * @return enrol_user_button|false 2017 */ 2018 public function get_manual_enrol_button(course_enrolment_manager $manager) { 2019 return false; 2020 } 2021 2022 /** 2023 * Gets an array of the user enrolment actions 2024 * 2025 * @param course_enrolment_manager $manager 2026 * @param stdClass $ue 2027 * @return array An array of user_enrolment_actions 2028 */ 2029 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) { 2030 return array(); 2031 } 2032 2033 /** 2034 * Returns true if the plugin has one or more bulk operations that can be performed on 2035 * user enrolments. 2036 * 2037 * @param course_enrolment_manager $manager 2038 * @return bool 2039 */ 2040 public function has_bulk_operations(course_enrolment_manager $manager) { 2041 return false; 2042 } 2043 2044 /** 2045 * Return an array of enrol_bulk_enrolment_operation objects that define 2046 * the bulk actions that can be performed on user enrolments by the plugin. 2047 * 2048 * @param course_enrolment_manager $manager 2049 * @return array 2050 */ 2051 public function get_bulk_operations(course_enrolment_manager $manager) { 2052 return array(); 2053 } 2054 2055 /** 2056 * Do any enrolments need expiration processing. 2057 * 2058 * Plugins that want to call this functionality must implement 'expiredaction' config setting. 2059 * 2060 * @param progress_trace $trace 2061 * @param int $courseid one course, empty mean all 2062 * @return bool true if any data processed, false if not 2063 */ 2064 public function process_expirations(progress_trace $trace, $courseid = null) { 2065 global $DB; 2066 2067 $name = $this->get_name(); 2068 if (!enrol_is_enabled($name)) { 2069 $trace->finished(); 2070 return false; 2071 } 2072 2073 $processed = false; 2074 $params = array(); 2075 $coursesql = ""; 2076 if ($courseid) { 2077 $coursesql = "AND e.courseid = :courseid"; 2078 } 2079 2080 // Deal with expired accounts. 2081 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP); 2082 2083 if ($action == ENROL_EXT_REMOVED_UNENROL) { 2084 $instances = array(); 2085 $sql = "SELECT ue.*, e.courseid, c.id AS contextid 2086 FROM {user_enrolments} ue 2087 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol) 2088 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel) 2089 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql"; 2090 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid); 2091 2092 $rs = $DB->get_recordset_sql($sql, $params); 2093 foreach ($rs as $ue) { 2094 if (!$processed) { 2095 $trace->output("Starting processing of enrol_$name expirations..."); 2096 $processed = true; 2097 } 2098 if (empty($instances[$ue->enrolid])) { 2099 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid)); 2100 } 2101 $instance = $instances[$ue->enrolid]; 2102 if (!$this->roles_protected()) { 2103 // Let's just guess what extra roles are supposed to be removed. 2104 if ($instance->roleid) { 2105 role_unassign($instance->roleid, $ue->userid, $ue->contextid); 2106 } 2107 } 2108 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user. 2109 $this->unenrol_user($instance, $ue->userid); 2110 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1); 2111 } 2112 $rs->close(); 2113 unset($instances); 2114 2115 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) { 2116 $instances = array(); 2117 $sql = "SELECT ue.*, e.courseid, c.id AS contextid 2118 FROM {user_enrolments} ue 2119 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol) 2120 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel) 2121 WHERE ue.timeend > 0 AND ue.timeend < :now 2122 AND ue.status = :useractive $coursesql"; 2123 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid); 2124 $rs = $DB->get_recordset_sql($sql, $params); 2125 foreach ($rs as $ue) { 2126 if (!$processed) { 2127 $trace->output("Starting processing of enrol_$name expirations..."); 2128 $processed = true; 2129 } 2130 if (empty($instances[$ue->enrolid])) { 2131 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid)); 2132 } 2133 $instance = $instances[$ue->enrolid]; 2134 2135 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) { 2136 if (!$this->roles_protected()) { 2137 // Let's just guess what roles should be removed. 2138 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid)); 2139 if ($count == 1) { 2140 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0)); 2141 2142 } else if ($count > 1 and $instance->roleid) { 2143 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0); 2144 } 2145 } 2146 // In any case remove all roles that belong to this instance and user. 2147 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true); 2148 // Final cleanup of subcontexts if there are no more course roles. 2149 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) { 2150 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true); 2151 } 2152 } 2153 2154 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED); 2155 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1); 2156 } 2157 $rs->close(); 2158 unset($instances); 2159 2160 } else { 2161 // ENROL_EXT_REMOVED_KEEP means no changes. 2162 } 2163 2164 if ($processed) { 2165 $trace->output("...finished processing of enrol_$name expirations"); 2166 } else { 2167 $trace->output("No expired enrol_$name enrolments detected"); 2168 } 2169 $trace->finished(); 2170 2171 return $processed; 2172 } 2173 2174 /** 2175 * Send expiry notifications. 2176 * 2177 * Plugin that wants to have expiry notification MUST implement following: 2178 * - expirynotifyhour plugin setting, 2179 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold), 2180 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody, 2181 * expirymessageenrolledsubject and expirymessageenrolledbody), 2182 * - expiry_notification provider in db/messages.php, 2183 * - upgrade code that sets default thresholds for existing courses (should be 1 day), 2184 * - something that calls this method, such as cron. 2185 * 2186 * @param progress_trace $trace (accepts bool for backwards compatibility only) 2187 */ 2188 public function send_expiry_notifications($trace) { 2189 global $DB, $CFG; 2190 2191 $name = $this->get_name(); 2192 if (!enrol_is_enabled($name)) { 2193 $trace->finished(); 2194 return; 2195 } 2196 2197 // Unfortunately this may take a long time, it should not be interrupted, 2198 // otherwise users get duplicate notification. 2199 2200 core_php_time_limit::raise(); 2201 raise_memory_limit(MEMORY_HUGE); 2202 2203 2204 $expirynotifylast = $this->get_config('expirynotifylast', 0); 2205 $expirynotifyhour = $this->get_config('expirynotifyhour'); 2206 if (is_null($expirynotifyhour)) { 2207 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting"); 2208 $trace->finished(); 2209 return; 2210 } 2211 2212 if (!($trace instanceof progress_trace)) { 2213 $trace = $trace ? new text_progress_trace() : new null_progress_trace(); 2214 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER); 2215 } 2216 2217 $timenow = time(); 2218 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600); 2219 2220 if ($expirynotifylast > $notifytime) { 2221 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.'); 2222 $trace->finished(); 2223 return; 2224 2225 } else if ($timenow < $notifytime) { 2226 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.'); 2227 $trace->finished(); 2228 return; 2229 } 2230 2231 $trace->output('Processing '.$name.' enrolment expiration notifications...'); 2232 2233 // Notify users responsible for enrolment once every day. 2234 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname 2235 FROM {user_enrolments} ue 2236 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled) 2237 JOIN {course} c ON (c.id = e.courseid) 2238 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0) 2239 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2) 2240 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC"; 2241 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name); 2242 2243 $rs = $DB->get_recordset_sql($sql, $params); 2244 2245 $lastenrollid = 0; 2246 $users = array(); 2247 2248 foreach($rs as $ue) { 2249 if ($lastenrollid and $lastenrollid != $ue->enrolid) { 2250 $this->notify_expiry_enroller($lastenrollid, $users, $trace); 2251 $users = array(); 2252 } 2253 $lastenrollid = $ue->enrolid; 2254 2255 $enroller = $this->get_enroller($ue->enrolid); 2256 $context = context_course::instance($ue->courseid); 2257 2258 $user = $DB->get_record('user', array('id'=>$ue->userid)); 2259 2260 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend); 2261 2262 if (!$ue->notifyall) { 2263 continue; 2264 } 2265 2266 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) { 2267 // Notify enrolled users only once at the start of the threshold. 2268 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1); 2269 continue; 2270 } 2271 2272 $this->notify_expiry_enrolled($user, $ue, $trace); 2273 } 2274 $rs->close(); 2275 2276 if ($lastenrollid and $users) { 2277 $this->notify_expiry_enroller($lastenrollid, $users, $trace); 2278 } 2279 2280 $trace->output('...notification processing finished.'); 2281 $trace->finished(); 2282 2283 $this->set_config('expirynotifylast', $timenow); 2284 } 2285 2286 /** 2287 * Returns the user who is responsible for enrolments for given instance. 2288 * 2289 * Override if plugin knows anybody better than admin. 2290 * 2291 * @param int $instanceid enrolment instance id 2292 * @return stdClass user record 2293 */ 2294 protected function get_enroller($instanceid) { 2295 return get_admin(); 2296 } 2297 2298 /** 2299 * Notify user about incoming expiration of their enrolment, 2300 * it is called only if notification of enrolled users (aka students) is enabled in course. 2301 * 2302 * This is executed only once for each expiring enrolment right 2303 * at the start of the expiration threshold. 2304 * 2305 * @param stdClass $user 2306 * @param stdClass $ue 2307 * @param progress_trace $trace 2308 */ 2309 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) { 2310 global $CFG; 2311 2312 $name = $this->get_name(); 2313 2314 $oldforcelang = force_current_language($user->lang); 2315 2316 $enroller = $this->get_enroller($ue->enrolid); 2317 $context = context_course::instance($ue->courseid); 2318 2319 $a = new stdClass(); 2320 $a->course = format_string($ue->fullname, true, array('context'=>$context)); 2321 $a->user = fullname($user, true); 2322 $a->timeend = userdate($ue->timeend, '', $user->timezone); 2323 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user)); 2324 2325 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a); 2326 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a); 2327 2328 $message = new stdClass(); 2329 $message->notification = 1; 2330 $message->component = 'enrol_'.$name; 2331 $message->name = 'expiry_notification'; 2332 $message->userfrom = $enroller; 2333 $message->userto = $user; 2334 $message->subject = $subject; 2335 $message->fullmessage = $body; 2336 $message->fullmessageformat = FORMAT_MARKDOWN; 2337 $message->fullmessagehtml = markdown_to_html($body); 2338 $message->smallmessage = $subject; 2339 $message->contexturlname = $a->course; 2340 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid)); 2341 2342 if (message_send($message)) { 2343 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1); 2344 } else { 2345 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1); 2346 } 2347 2348 force_current_language($oldforcelang); 2349 } 2350 2351 /** 2352 * Notify person responsible for enrolments that some user enrolments will be expired soon, 2353 * it is called only if notification of enrollers (aka teachers) is enabled in course. 2354 * 2355 * This is called repeatedly every day for each course if there are any pending expiration 2356 * in the expiration threshold. 2357 * 2358 * @param int $eid 2359 * @param array $users 2360 * @param progress_trace $trace 2361 */ 2362 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) { 2363 global $DB; 2364 2365 $name = $this->get_name(); 2366 2367 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name)); 2368 $context = context_course::instance($instance->courseid); 2369 $course = $DB->get_record('course', array('id'=>$instance->courseid)); 2370 2371 $enroller = $this->get_enroller($instance->id); 2372 $admin = get_admin(); 2373 2374 $oldforcelang = force_current_language($enroller->lang); 2375 2376 foreach($users as $key=>$info) { 2377 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone); 2378 } 2379 2380 $a = new stdClass(); 2381 $a->course = format_string($course->fullname, true, array('context'=>$context)); 2382 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24)); 2383 $a->users = implode("\n", $users); 2384 $a->extendurl = (string)new moodle_url('/enrol/users.php', array('id'=>$instance->courseid)); 2385 2386 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a); 2387 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a); 2388 2389 $message = new stdClass(); 2390 $message->notification = 1; 2391 $message->component = 'enrol_'.$name; 2392 $message->name = 'expiry_notification'; 2393 $message->userfrom = $admin; 2394 $message->userto = $enroller; 2395 $message->subject = $subject; 2396 $message->fullmessage = $body; 2397 $message->fullmessageformat = FORMAT_MARKDOWN; 2398 $message->fullmessagehtml = markdown_to_html($body); 2399 $message->smallmessage = $subject; 2400 $message->contexturlname = $a->course; 2401 $message->contexturl = $a->extendurl; 2402 2403 if (message_send($message)) { 2404 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1); 2405 } else { 2406 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1); 2407 } 2408 2409 force_current_language($oldforcelang); 2410 } 2411 2412 /** 2413 * Backup execution step hook to annotate custom fields. 2414 * 2415 * @param backup_enrolments_execution_step $step 2416 * @param stdClass $enrol 2417 */ 2418 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) { 2419 // Override as necessary to annotate custom fields in the enrol table. 2420 } 2421 2422 /** 2423 * Automatic enrol sync executed during restore. 2424 * Useful for automatic sync by course->idnumber or course category. 2425 * @param stdClass $course course record 2426 */ 2427 public function restore_sync_course($course) { 2428 // Override if necessary. 2429 } 2430 2431 /** 2432 * Restore instance and map settings. 2433 * 2434 * @param restore_enrolments_structure_step $step 2435 * @param stdClass $data 2436 * @param stdClass $course 2437 * @param int $oldid 2438 */ 2439 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) { 2440 // Do not call this from overridden methods, restore and set new id there. 2441 $step->set_mapping('enrol', $oldid, 0); 2442 } 2443 2444 /** 2445 * Restore user enrolment. 2446 * 2447 * @param restore_enrolments_structure_step $step 2448 * @param stdClass $data 2449 * @param stdClass $instance 2450 * @param int $oldinstancestatus 2451 * @param int $userid 2452 */ 2453 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) { 2454 // Override as necessary if plugin supports restore of enrolments. 2455 } 2456 2457 /** 2458 * Restore role assignment. 2459 * 2460 * @param stdClass $instance 2461 * @param int $roleid 2462 * @param int $userid 2463 * @param int $contextid 2464 */ 2465 public function restore_role_assignment($instance, $roleid, $userid, $contextid) { 2466 // No role assignment by default, override if necessary. 2467 } 2468 2469 /** 2470 * Restore user group membership. 2471 * @param stdClass $instance 2472 * @param int $groupid 2473 * @param int $userid 2474 */ 2475 public function restore_group_member($instance, $groupid, $userid) { 2476 // Implement if you want to restore protected group memberships, 2477 // usually this is not necessary because plugins should be able to recreate the memberships automatically. 2478 } 2479 2480 /** 2481 * Returns defaults for new instances. 2482 * @since Moodle 3.1 2483 * @return array 2484 */ 2485 public function get_instance_defaults() { 2486 return array(); 2487 } 2488 2489 /** 2490 * Validate a list of parameter names and types. 2491 * @since Moodle 3.1 2492 * 2493 * @param array $data array of ("fieldname"=>value) of submitted data 2494 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options ) 2495 * @return array of "element_name"=>"error_description" if there are errors, 2496 * or an empty array if everything is OK. 2497 */ 2498 public function validate_param_types($data, $rules) { 2499 $errors = array(); 2500 $invalidstr = get_string('invaliddata', 'error'); 2501 foreach ($rules as $fieldname => $rule) { 2502 if (is_array($rule)) { 2503 if (!in_array($data[$fieldname], $rule)) { 2504 $errors[$fieldname] = $invalidstr; 2505 } 2506 } else { 2507 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) { 2508 $errors[$fieldname] = $invalidstr; 2509 } 2510 } 2511 } 2512 return $errors; 2513 } 2514 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Thu Aug 11 10:00:09 2016 | Cross-referenced by PHPXref 0.7.1 |