MDL-11082 Improved groups upgrade performance 1.8x -> 1.9; thanks Eloy for telling...
[moodle-pu.git] / lib / deprecatedlib.php
blobb2525140433717ac8eb7dfb2a60087014d79feb7
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999-2999 Martin Dougiamas, Moodle http://moodle.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * deprecatedlib.php - Old functions retained only for backward compatibility
29 * Old functions retained only for backward compatibility. New code should not
30 * use any of these functions.
32 * @author Martin Dougiamas
33 * @version $Id$
34 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
35 * @package moodlecore
41 /**
42 * Ensure that a variable is set
44 * If $var is undefined throw an error, otherwise return $var.
46 * @param mixed $var the variable which may be unset
47 * @param mixed $default the value to return if $var is unset
49 function require_variable($var) {
50 global $CFG;
51 if (!empty($CFG->disableglobalshack)) {
52 error( 'The require_variable() function is deprecated.' );
54 if (! isset($var)) {
55 error('A required parameter was missing');
59 /**
60 * Ensure that a variable is set
62 * If $var is undefined set it (by reference), otherwise return $var.
64 * @param mixed $var the variable which may be unset
65 * @param mixed $default the value to return if $var is unset
67 function optional_variable(&$var, $default=0) {
68 global $CFG;
69 if (!empty($CFG->disableglobalshack)) {
70 error( "The optional_variable() function is deprecated ($var, $default)." );
72 if (! isset($var)) {
73 $var = $default;
77 /**
78 * Ensure that a variable is set
80 * Return $var if it is defined, otherwise return $default,
81 * This function is very similar to {@link optional_variable()}
83 * @param mixed $var the variable which may be unset
84 * @param mixed $default the value to return if $var is unset
85 * @return mixed
87 function nvl(&$var, $default='') {
88 global $CFG;
90 if (!empty($CFG->disableglobalshack)) {
91 error( "The nvl() function is deprecated ($var, $default)." );
93 return isset($var) ? $var : $default;
96 /**
97 * Determines if a user an admin
99 * @uses $USER
100 * @param int $userid The id of the user as is found in the 'user' table
101 * @staticvar array $admins List of users who have been found to be admins by user id
102 * @staticvar array $nonadmins List of users who have been found not to be admins by user id
103 * @return bool
105 function isadmin($userid=0) {
106 global $USER, $CFG;
108 if (empty($CFG->rolesactive)) { // Then the user is likely to be upgrading NOW
109 if (!$userid) {
110 if (empty($USER->id)) {
111 return false;
113 if (!empty($USER->admin)) {
114 return true;
116 $userid = $USER->id;
119 return record_exists('user_admins', 'userid', $userid);
122 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
124 return has_capability('moodle/legacy:admin', $context, $userid, false);
128 * Determines if a user is a teacher (or better)
130 * @uses $CFG
131 * @param int $courseid The id of the course that is being viewed, if any
132 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
133 * @param bool $obsolete_includeadmin Not used any more
134 * @return bool
137 function isteacher($courseid=0, $userid=0, $obsolete_includeadmin=true) {
138 /// Is the user able to access this course as a teacher?
139 global $CFG;
141 if (empty($CFG->rolesactive)) { // Teachers are locked out during an upgrade to 1.7
142 return false;
145 if ($courseid) {
146 $context = get_context_instance(CONTEXT_COURSE, $courseid);
147 } else {
148 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
151 return (has_capability('moodle/legacy:teacher', $context, $userid, false)
152 or has_capability('moodle/legacy:editingteacher', $context, $userid, false)
153 or has_capability('moodle/legacy:admin', $context, $userid, false));
157 * Determines if a user is a teacher in any course, or an admin
159 * @uses $USER
160 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
161 * @param bool $includeadmin Include anyone wo is an admin as well
162 * @return bool
164 function isteacherinanycourse($userid=0, $includeadmin=true) {
165 global $USER, $CFG;
167 if (empty($CFG->rolesactive)) { // Teachers are locked out during an upgrade to 1.7
168 return false;
171 if (!$userid) {
172 if (empty($USER->id)) {
173 return false;
175 $userid = $USER->id;
178 if (!record_exists('role_assignments', 'userid', $userid)) { // Has no roles anywhere
179 return false;
182 /// If this user is assigned as an editing teacher anywhere then return true
183 if ($roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) {
184 foreach ($roles as $role) {
185 if (record_exists('role_assignments', 'roleid', $role->id, 'userid', $userid)) {
186 return true;
191 /// If this user is assigned as a non-editing teacher anywhere then return true
192 if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW)) {
193 foreach ($roles as $role) {
194 if (record_exists('role_assignments', 'roleid', $role->id, 'userid', $userid)) {
195 return true;
200 /// Include admins if required
201 if ($includeadmin) {
202 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
203 if (has_capability('moodle/legacy:admin', $context, $userid, false)) {
204 return true;
208 return false;
212 * Determines if a user is allowed to edit a given course
214 * @param int $courseid The id of the course that is being edited
215 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
216 * @return bool
218 function isteacheredit($courseid, $userid=0, $obsolete_ignorestudentview=false) {
219 global $CFG;
221 if (empty($CFG->rolesactive)) {
222 return false;
225 if (empty($courseid)) {
226 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
227 } else {
228 $context = get_context_instance(CONTEXT_COURSE, $courseid);
231 return (has_capability('moodle/legacy:editingteacher', $context, $userid, false)
232 or has_capability('moodle/legacy:admin', $context, $userid, false));
236 * Determines if a user can create new courses
238 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
239 * @return bool
241 function iscreator ($userid=0) {
242 global $CFG;
244 if (empty($CFG->rolesactive)) {
245 return false;
248 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
250 return (has_capability('moodle/legacy:coursecreator', $context, $userid, false)
251 or has_capability('moodle/legacy:admin', $context, $userid, false));
255 * Determines if a user is a student in the specified course
257 * If the course id specifies the site then this determines
258 * if the user is a confirmed and valid user of this site.
260 * @uses $CFG
261 * @uses SITEID
262 * @param int $courseid The id of the course being tested
263 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
264 * @return bool
266 function isstudent($courseid=0, $userid=0) {
267 global $CFG;
269 if (empty($CFG->rolesactive)) {
270 return false;
273 if ($courseid == 0) {
274 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
275 } else {
276 $context = get_context_instance(CONTEXT_COURSE, $courseid);
279 return has_capability('moodle/legacy:student', $context, $userid, false);
283 * Determines if the specified user is logged in as guest.
285 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
286 * @return bool
288 function isguest($userid=0) {
289 global $CFG;
291 if (empty($CFG->rolesactive)) {
292 return false;
295 $context = get_context_instance(CONTEXT_SYSTEM);
297 return has_capability('moodle/legacy:guest', $context, $userid, false);
301 * Enrols (or re-enrols) a student in a given course
303 * NOTE: Defaults to 'manual' enrolment - enrolment plugins
304 * must set it explicitly.
306 * @uses $CFG
307 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
308 * @param int $courseid The id of the course that is being viewed
309 * @param int $timestart ?
310 * @param int $timeend ?
311 * @param string $enrol ?
312 * @return bool
314 function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
316 global $CFG;
318 if (!$user = get_record('user', 'id', $userid)) { // Check user
319 return false;
322 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
323 return false;
326 $role = array_shift($roles); // We can only use one, let's use the first one
328 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
329 return false;
332 return role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
336 * Unenrols a student from a given course
338 * @param int $courseid The id of the course that is being viewed, if any
339 * @param int $userid The id of the user that is being tested against.
340 * @return bool
342 function unenrol_student($userid, $courseid=0) {
343 global $CFG;
345 $status = true;
347 if ($courseid) {
348 /// First delete any crucial stuff that might still send mail
349 if ($forums = get_records('forum', 'course', $courseid)) {
350 foreach ($forums as $forum) {
351 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
354 /// remove from all legacy student roles
355 if ($courseid == SITEID) {
356 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
357 } else if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
358 return false;
360 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
361 return false;
363 foreach($roles as $role) {
364 $status = role_unassign($role->id, $userid, 0, $context->id) and $status;
366 } else {
367 // recursivelly unenroll student from all courses
368 if ($courses = get_records('course')) {
369 foreach($courses as $course) {
370 $status = unenrol_student($userid, $course->id) and $status;
375 return $status;
379 * Add a teacher to a given course
381 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
382 * @param int $courseid The id of the course that is being viewed, if any
383 * @param int $editall Can edit the course
384 * @param string $role Obsolete
385 * @param int $timestart The time they start
386 * @param int $timeend The time they end in this role
387 * @param string $enrol The type of enrolment this is
388 * @return bool
390 function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
391 global $CFG;
393 if (!$user = get_record('user', 'id', $userid)) { // Check user
394 return false;
397 $capability = $editall ? 'moodle/legacy:editingteacher' : 'moodle/legacy:teacher';
399 if (!$roles = get_roles_with_capability($capability, CAP_ALLOW)) {
400 return false;
403 $role = array_shift($roles); // We can only use one, let's use the first one
405 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
406 return false;
409 return role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
413 * Removes a teacher from a given course (or ALL courses)
414 * Does not delete the user account
416 * @param int $courseid The id of the course that is being viewed, if any
417 * @param int $userid The id of the user that is being tested against.
418 * @return bool
420 function remove_teacher($userid, $courseid=0) {
421 global $CFG;
423 $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW);
425 if ($roles) {
426 $roles += get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
427 } else {
428 $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
431 if (empty($roles)) {
432 return true;
435 $return = true;
437 if ($courseid) {
439 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
440 return false;
443 /// First delete any crucial stuff that might still send mail
444 if ($forums = get_records('forum', 'course', $courseid)) {
445 foreach ($forums as $forum) {
446 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
450 /// No need to remove from groups now
452 foreach ($roles as $role) { // Unassign them from all the teacher roles
453 $newreturn = role_unassign($role->id, $userid, 0, $context->id);
454 if (empty($newreturn)) {
455 $return = false;
459 } else {
460 delete_records('forum_subscriptions', 'userid', $userid);
461 $return = true;
462 foreach ($roles as $role) { // Unassign them from all the teacher roles
463 $newreturn = role_unassign($role->id, $userid, 0, 0);
464 if (empty($newreturn)) {
465 $return = false;
470 return $return;
474 * Add an admin to a site
476 * @uses SITEID
477 * @param int $userid The id of the user that is being tested against.
478 * @return bool
479 * @TODO: remove from cvs
481 function add_admin($userid) {
482 return true;
485 function get_user_info_from_db($field, $value) { // For backward compatibility
486 return get_complete_user_data($field, $value);
491 * Get the guest user information from the database
493 * @return object(user) An associative array with the details of the guest user account.
494 * @todo Is object(user) a correct return type? Or is array the proper return type with a note that the contents include all details for a user.
496 function get_guest() {
497 return get_complete_user_data('username', 'guest');
501 * Returns $user object of the main teacher for a course
503 * @uses $CFG
504 * @param int $courseid The course in question.
505 * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
506 * @todo Finish documenting this function
508 function get_teacher($courseid) {
510 global $CFG;
512 $context = get_context_instance(CONTEXT_COURSE, $courseid);
514 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*,ra.hidden', 'r.sortorder ASC',
515 '', '', '', '', false)) {
516 foreach ($users as $user) {
517 if (!$user->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) {
518 return $user;
523 return false;
527 * Searches logs to find all enrolments since a certain date
529 * used to print recent activity
531 * @uses $CFG
532 * @param int $courseid The course in question.
533 * @return object|false {@link $USER} records or false if error.
534 * @todo Finish documenting this function
536 function get_recent_enrolments($courseid, $timestart) {
538 global $CFG;
540 $context = get_context_instance(CONTEXT_COURSE, $courseid);
542 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
543 FROM {$CFG->prefix}user u,
544 {$CFG->prefix}role_assignments ra,
545 {$CFG->prefix}log l
546 WHERE l.time > '$timestart'
547 AND l.course = '$courseid'
548 AND l.module = 'course'
549 AND l.action = 'enrol'
550 AND l.info = u.id
551 AND u.id = ra.userid
552 AND ra.contextid ".get_related_contexts_string($context)."
553 ORDER BY l.time ASC");
557 * Returns array of userinfo of all students in this course
558 * or on this site if courseid is id of site
560 * @uses $CFG
561 * @uses SITEID
562 * @param int $courseid The course in question.
563 * @param string $sort ?
564 * @param string $dir ?
565 * @param int $page ?
566 * @param int $recordsperpage ?
567 * @param string $firstinitial ?
568 * @param string $lastinitial ?
569 * @param ? $group ?
570 * @param string $search ?
571 * @param string $fields A comma separated list of fields to be returned from the chosen table.
572 * @param string $exceptions ?
573 * @return object
574 * @todo Finish documenting this function
576 function get_course_students($courseid, $sort='ul.timeaccess', $dir='', $page='', $recordsperpage='',
577 $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
579 global $CFG;
581 // make sure it works on the site course
582 $context = get_context_instance(CONTEXT_COURSE, $courseid);
584 /// For the site course, old way was to check if $CFG->allusersaresitestudents was set to true.
585 /// The closest comparible method using roles is if the $CFG->defaultuserroleid is set to the legacy
586 /// student role. This function should be replaced where it is used with something more meaningful.
587 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
588 if ($roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW, $context)) {
589 $hascap = false;
590 foreach ($roles as $role) {
591 if ($role->id == $CFG->defaultuserroleid) {
592 $hascap = true;
593 break;
596 if ($hascap) {
597 // return users with confirmed, undeleted accounts who are not site teachers
598 // the following is a mess because of different conventions in the different user functions
599 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
600 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
601 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
602 $fields = str_replace('u.', '', $fields);
603 if ($sort) {
604 $sort = $sort .' '. $dir;
606 // Now we have to make sure site teachers are excluded
608 if ($teachers = get_course_teachers(SITEID)) {
609 foreach ($teachers as $teacher) {
610 $exceptions .= ','. $teacher->userid;
612 $exceptions = ltrim($exceptions, ',');
616 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
617 $page, $recordsperpage, $fields ? $fields : '*');
622 $LIKE = sql_ilike();
623 $fullname = sql_fullname('u.firstname','u.lastname');
625 $groupmembers = '';
627 $select = "c.contextlevel=".CONTEXT_COURSE." AND "; // Must be on a course
628 if ($courseid != SITEID) {
629 // If not site, require specific course
630 $select.= "c.instanceid=$courseid AND ";
632 $select.="rc.capability='moodle/legacy:student' AND rc.permission=".CAP_ALLOW." AND ";
634 $select .= ' u.deleted = \'0\' ';
636 if (!$fields) {
637 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
638 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
639 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
640 'u.emailstop, u.lang, u.timezone, ul.timeaccess as lastaccess';
643 if ($search) {
644 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
647 if ($firstinitial) {
648 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
651 if ($lastinitial) {
652 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
655 if ($group === 0) { /// Need something here to get all students not in a group
656 return array();
658 } else if ($group !== NULL) {
659 $groupmembers = "INNER JOIN {$CFG->prefix}groups_members gm on u.id=gm.userid";
660 $select .= ' AND gm.groupid = \''. $group .'\'';
663 if (!empty($exceptions)) {
664 $select .= ' AND u.id NOT IN ('. $exceptions .')';
667 if ($sort) {
668 $sort = ' ORDER BY '. $sort .' ';
671 $students = get_records_sql("SELECT $fields
672 FROM {$CFG->prefix}user u INNER JOIN
673 {$CFG->prefix}role_assignments ra on u.id=ra.userid INNER JOIN
674 {$CFG->prefix}role_capabilities rc ON ra.roleid=rc.roleid INNER JOIN
675 {$CFG->prefix}context c ON c.id=ra.contextid LEFT OUTER JOIN
676 {$CFG->prefix}user_lastaccess ul on ul.userid=ra.userid
677 $groupmembers
678 WHERE $select $search $sort $dir", $page, $recordsperpage);
680 return $students;
684 * Counts the students in a given course (or site), or a subset of them
686 * @param object $course The course in question as a course object.
687 * @param string $search ?
688 * @param string $firstinitial ?
689 * @param string $lastinitial ?
690 * @param ? $group ?
691 * @param string $exceptions ?
692 * @return int
693 * @todo Finish documenting this function
695 function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
697 if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
698 return count($students);
700 return 0;
704 * Returns list of all teachers in this course
706 * If $courseid matches the site id then this function
707 * returns a list of all teachers for the site.
709 * @uses $CFG
710 * @param int $courseid The course in question.
711 * @param string $sort ?
712 * @param string $exceptions ?
713 * @return object
714 * @todo Finish documenting this function
716 function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
718 global $CFG;
720 $sort = 'ul.timeaccess DESC';
722 $context = get_context_instance(CONTEXT_COURSE, $courseid);
724 /// For the site course, if the $CFG->defaultuserroleid is set to the legacy teacher role, then all
725 /// users are teachers. This function should be replaced where it is used with something more
726 /// meaningful.
727 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
728 if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW, $context)) {
729 $hascap = false;
730 foreach ($roles as $role) {
731 if ($role->id == $CFG->defaultuserroleid) {
732 $hascap = true;
733 break;
736 if ($hascap) {
737 if (empty($fields)) {
738 $fields = '*';
740 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
745 return get_users_by_capability($context, 'moodle/course:update', 'u.*, ul.timeaccess as lastaccess, ra.hidden', $sort, '','','',$exceptions, false);
746 /// some fields will be missing, like authority, editall
748 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
749 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
750 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
751 FROM {$CFG->prefix}user u,
752 {$CFG->prefix}user_teachers t
753 WHERE t.course = '$courseid' AND t.userid = u.id
754 AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
759 * Returns all the users of a course: students and teachers
761 * @param int $courseid The course in question.
762 * @param string $sort ?
763 * @param string $exceptions ?
764 * @param string $fields A comma separated list of fields to be returned from the chosen table.
765 * @return object
766 * @todo Finish documenting this function
768 function get_course_users($courseid, $sort='ul.timeaccess DESC', $exceptions='', $fields='') {
769 global $CFG;
771 $context = get_context_instance(CONTEXT_COURSE, $courseid);
773 /// If the course id is the SITEID, we need to return all the users if the "defaultuserroleid"
774 /// has the capbility of accessing the site course. $CFG->nodefaultuserrolelists set to true can
775 /// over-rule using this.
776 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
777 if ($roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
778 $hascap = false;
779 foreach ($roles as $role) {
780 if ($role->id == $CFG->defaultuserroleid) {
781 $hascap = true;
782 break;
785 if ($hascap) {
786 if (empty($fields)) {
787 $fields = '*';
789 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
793 return get_users_by_capability($context, 'moodle/course:view', 'u.*, ul.timeaccess as lastaccess', $sort, '','','',$exceptions, false);
798 * Returns an array of user objects
800 * @uses $CFG
801 * @param int $groupid The group(s) in question.
802 * @param string $sort How to sort the results
803 * @return object (changed to groupids)
805 function get_group_students($groupids, $sort='ul.timeaccess DESC') {
807 if (is_array($groupids)){
808 $groups = $groupids;
809 // all groups must be from one course anyway...
810 $group = groups_get_group(array_shift($groups));
811 } else {
812 $group = groups_get_group($groupids);
814 if (!$group) {
815 return NULL;
818 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
819 return get_users_by_capability($context, 'moodle/legacy:student', 'u.*, ul.timeaccess as lastaccess', $sort, '','',$groupids, '', false);
823 * Returns list of all the teachers who can access a group
825 * @uses $CFG
826 * @param int $courseid The course in question.
827 * @param int $groupid The group in question.
828 * @return object
830 function get_group_teachers($courseid, $groupid) {
831 /// Returns a list of all the teachers who can access a group
832 if ($teachers = get_course_teachers($courseid)) {
833 foreach ($teachers as $key => $teacher) {
834 if ($teacher->editall) { // These can access anything
835 continue;
837 if (($teacher->authority > 0) and groups_is_member($groupid, $teacher->id)) { // Specific group teachers
838 continue;
840 unset($teachers[$key]);
843 return $teachers;
848 ########### FROM weblib.php ##########################################################################
852 * Print a message in a standard themed box.
853 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
854 * parameters remain. If possible, $align, $width and $color should not be defined at all.
855 * Preferably just use print_box() in weblib.php
857 * @param string $align, alignment of the box, not the text (default center, left, right).
858 * @param string $width, width of the box, including units %, for example '100%'.
859 * @param string $color, background colour of the box, for example '#eee'.
860 * @param int $padding, padding in pixels, specified without units.
861 * @param string $class, space-separated class names.
862 * @param string $id, space-separated id names.
863 * @param boolean $return, return as string or just print it
865 function print_simple_box($message, $align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
866 $output = '';
867 $output .= print_simple_box_start($align, $width, $color, $padding, $class, $id, true);
868 $output .= stripslashes_safe($message);
869 $output .= print_simple_box_end(true);
871 if ($return) {
872 return $output;
873 } else {
874 echo $output;
881 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
882 * parameters remain. If possible, $align, $width and $color should not be defined at all.
883 * Even better, please use print_box_start() in weblib.php
885 * @param string $align, alignment of the box, not the text (default center, left, right). DEPRECATED
886 * @param string $width, width of the box, including % units, for example '100%'. DEPRECATED
887 * @param string $color, background colour of the box, for example '#eee'. DEPRECATED
888 * @param int $padding, padding in pixels, specified without units. OBSOLETE
889 * @param string $class, space-separated class names.
890 * @param string $id, space-separated id names.
891 * @param boolean $return, return as string or just print it
893 function print_simple_box_start($align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
895 $output = '';
897 $divclasses = 'box '.$class.' '.$class.'content';
898 $divstyles = '';
900 if ($align) {
901 $divclasses .= ' boxalign'.$align; // Implement alignment using a class
903 if ($width) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
904 if (substr($width, -1, 1) == '%') { // Width is a % value
905 $width = (int) substr($width, 0, -1); // Extract just the number
906 if ($width < 40) {
907 $divclasses .= ' boxwidthnarrow'; // Approx 30% depending on theme
908 } else if ($width > 60) {
909 $divclasses .= ' boxwidthwide'; // Approx 80% depending on theme
910 } else {
911 $divclasses .= ' boxwidthnormal'; // Approx 50% depending on theme
913 } else {
914 $divstyles .= ' width:'.$width.';'; // Last resort
917 if ($color) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
918 $divstyles .= ' background:'.$color.';';
920 if ($divstyles) {
921 $divstyles = ' style="'.$divstyles.'"';
924 if ($id) {
925 $id = ' id="'.$id.'"';
928 $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
930 if ($return) {
931 return $output;
932 } else {
933 echo $output;
939 * Print the end portion of a standard themed box.
940 * Preferably just use print_box_end() in weblib.php
942 function print_simple_box_end($return=false) {
943 $output = '</div>';
944 if ($return) {
945 return $output;
946 } else {
947 echo $output;
952 * deprecated - use clean_param($string, PARAM_FILE); instead
953 * Check for bad characters ?
955 * @param string $string ?
956 * @param int $allowdots ?
957 * @todo Finish documenting this function - more detail needed in description as well as details on arguments
959 function detect_munged_arguments($string, $allowdots=1) {
960 if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references
961 return true;
963 if (ereg('[\|\`]', $string)) { // check for other bad characters
964 return true;
966 if (empty($string) or $string == '/') {
967 return true;
970 return false;
973 /** Deprecated function - returns the code of the current charset - originally depended on the selected language pack.
975 * @param $ignorecache not used anymore
976 * @return string always returns 'UTF-8'
978 function current_charset($ignorecache = false) {
979 return 'UTF-8';
983 /////////////////////////////////////////////////////////////
984 /// Old functions not used anymore - candidates for removal
985 /////////////////////////////////////////////////////////////
988 * Load a template from file - this function dates back to Moodle 1 :-) not used anymore
990 * Returns a (big) string containing the contents of a template file with all
991 * the variables interpolated. all the variables must be in the $var[] array or
992 * object (whatever you decide to use).
994 * <b>WARNING: do not use this on big files!!</b>
996 * @param string $filename Location on the server's filesystem where template can be found.
997 * @param mixed $var Passed in by reference. An array or object which will be loaded with data from the template file.
1000 function read_template($filename, &$var) {
1002 $temp = str_replace("\\", "\\\\", implode(file($filename), ''));
1003 $temp = str_replace('"', '\"', $temp);
1004 eval("\$template = \"$temp\";");
1005 return $template;
1010 * deprecated - relies on register globals; use new formslib instead
1012 * Set a variable's value depending on whether or not it already has a value.
1014 * If variable is set, set it to the set_value otherwise set it to the
1015 * unset_value. used to handle checkboxes when you are expecting them from
1016 * a form
1018 * @param mixed $var Passed in by reference. The variable to check.
1019 * @param mixed $set_value The value to set $var to if $var already has a value.
1020 * @param mixed $unset_value The value to set $var to if $var does not already have a value.
1022 function checked(&$var, $set_value = 1, $unset_value = 0) {
1024 if (empty($var)) {
1025 $var = $unset_value;
1026 } else {
1027 $var = $set_value;
1032 * deprecated - use new formslib instead
1034 * Prints the word "checked" if a variable is true, otherwise prints nothing,
1035 * used for printing the word "checked" in a checkbox form element.
1037 * @param boolean $var Variable to be checked for true value
1038 * @param string $true_value Value to be printed if $var is true
1039 * @param string $false_value Value to be printed if $var is false
1041 function frmchecked(&$var, $true_value = 'checked', $false_value = '') {
1043 if ($var) {
1044 echo $true_value;
1045 } else {
1046 echo $false_value;
1051 * Legacy function, provided for backward compatability.
1052 * This method now simply calls {@link use_html_editor()}
1054 * @deprecated Use {@link use_html_editor()} instead.
1055 * @param string $name Form element to replace with HTMl editor by name
1056 * @todo Finish documenting this function
1058 function print_richedit_javascript($form, $name, $source='no') {
1059 use_html_editor($name);
1062 /** various deprecated groups function **/
1066 * Returns the table in which group members are stored, with a prefix 'gm'.
1067 * @return SQL string.
1069 function groups_members_from_sql() {
1070 global $CFG;
1071 return " {$CFG->prefix}groups_members gm ";
1075 * Returns a join testing user.id against member's user ID.
1076 * Relies on 'user' table being included as 'user u'.
1077 * Used in Quiz module reports.
1078 * @param group ID, optional to include a test for this in the SQL.
1079 * @return SQL string.
1081 function groups_members_join_sql($groupid=false) {
1082 $sql = ' JOIN '.groups_members_from_sql().' ON u.id = gm.userid ';
1083 if ($groupid) {
1084 $sql = "AND gm.groupid = '$groupid' ";
1086 return $sql;
1087 //return ' INNER JOIN '.$CFG->prefix.'role_assignments ra ON u.id=ra.userid'.
1088 // ' INNER JOIN '.$CFG->prefix.'context c ON ra.contextid=c.id AND c.contextlevel='.CONTEXT_GROUP.' AND c.instanceid='.$groupid;
1092 * Returns SQL for a WHERE clause testing the group ID.
1093 * Optionally test the member's ID against another table's user ID column.
1094 * @param groupid
1095 * @param userid_sql Optional user ID column selector, example "mdl_user.id", or false.
1096 * @return SQL string.
1098 function groups_members_where_sql($groupid, $userid_sql=false) {
1099 $sql = " gm.groupid = '$groupid' ";
1100 if ($userid_sql) {
1101 $sql .= "AND $userid_sql = gm.userid ";
1103 return $sql;
1108 * Returns an array of group objects that the user is a member of
1109 * in the given course. If userid isn't specified, then return a
1110 * list of all groups in the course.
1112 * @uses $CFG
1113 * @param int $courseid The id of the course in question.
1114 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
1115 * @return object
1117 function get_groups($courseid, $userid=0) {
1118 return groups_get_all_groups($courseid, $userid);
1122 * Returns the user's groups in a particular course
1123 * note: this function originally returned only one group
1125 * @uses $CFG
1126 * @param int $courseid The course in question.
1127 * @param int $userid The id of the user as found in the 'user' table.
1128 * @param int $groupid The id of the group the user is in.
1129 * @return aray of groups
1131 function user_group($courseid, $userid) {
1132 return groups_get_all_groups($courseid, $userid);
1137 * Determines if the user is a member of the given group.
1139 * @param int $groupid The group to check for membership.
1140 * @param int $userid The user to check against the group.
1141 * @return boolean True if the user is a member, false otherwise.
1143 function ismember($groupid, $userid = null) {
1144 return groups_is_member($groupid, $userid);
1148 * Get the IDs for the user's groups in the given course.
1150 * @uses $USER
1151 * @param int $courseid The course being examined - the 'course' table id field.
1152 * @return array An _array_ of groupids.
1153 * (Was return $groupids[0] - consequences!)
1155 function mygroupid($courseid) {
1156 global $USER;
1157 if ($groups = groups_get_all_groups($courseid, $USER->id)) {
1158 return array_keys($groups);
1159 } else {
1160 return false;
1165 * Add a user to a group, return true upon success or if user already a group
1166 * member
1168 * @param int $groupid The group id to add user to
1169 * @param int $userid The user id to add to the group
1170 * @return bool
1172 function add_user_to_group($groupid, $userid) {
1173 global $CFG;
1174 require_once($CFG->dirroot.'/group/lib.php');
1176 return groups_add_member($groupid, $userid);
1181 * Returns an array of user objects
1183 * @uses $CFG
1184 * @param int $groupid The group in question.
1185 * @param string $sort ?
1186 * @param string $exceptions ?
1187 * @return object
1188 * @todo Finish documenting this function
1190 function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='',
1191 $fields='u.*') {
1192 global $CFG;
1193 if (!empty($exceptions)) {
1194 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1195 } else {
1196 $except = '';
1198 // in postgres, you can't have things in sort that aren't in the select, so...
1199 $extrafield = str_replace('ASC','',$sort);
1200 $extrafield = str_replace('DESC','',$extrafield);
1201 $extrafield = trim($extrafield);
1202 if (!empty($extrafield)) {
1203 $extrafield = ','.$extrafield;
1205 return get_records_sql("SELECT DISTINCT $fields $extrafield
1206 FROM {$CFG->prefix}user u,
1207 {$CFG->prefix}groups_members m
1208 WHERE m.groupid = '$groupid'
1209 AND m.userid = u.id $except
1210 ORDER BY $sort");
1214 * Returns the current group mode for a given course or activity module
1216 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
1218 function groupmode($course, $cm=null) {
1220 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
1221 return $cm->groupmode;
1223 return $course->groupmode;
1228 * Sets the current group in the session variable
1229 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
1230 * Sets currentgroup[$courseid] in the session variable appropriately.
1231 * Does not do any permission checking.
1232 * @uses $SESSION
1233 * @param int $courseid The course being examined - relates to id field in
1234 * 'course' table.
1235 * @param int $groupid The group being examined.
1236 * @return int Current group id which was set by this function
1238 function set_current_group($courseid, $groupid) {
1239 global $SESSION;
1240 return $SESSION->currentgroup[$courseid] = $groupid;
1245 * Gets the current group - either from the session variable or from the database.
1247 * @uses $USER
1248 * @uses $SESSION
1249 * @param int $courseid The course being examined - relates to id field in
1250 * 'course' table.
1251 * @param bool $full If true, the return value is a full record object.
1252 * If false, just the id of the record.
1254 function get_current_group($courseid, $full = false) {
1255 global $SESSION;
1257 if (isset($SESSION->currentgroup[$courseid])) {
1258 if ($full) {
1259 return groups_get_group($SESSION->currentgroup[$courseid]);
1260 } else {
1261 return $SESSION->currentgroup[$courseid];
1265 $mygroupid = mygroupid($courseid);
1266 if (is_array($mygroupid)) {
1267 $mygroupid = array_shift($mygroupid);
1268 set_current_group($courseid, $mygroupid);
1269 if ($full) {
1270 return groups_get_group($mygroupid);
1271 } else {
1272 return $mygroupid;
1276 if ($full) {
1277 return false;
1278 } else {
1279 return 0;
1285 * A combination function to make it easier for modules
1286 * to set up groups.
1288 * It will use a given "groupid" parameter and try to use
1289 * that to reset the current group for the user.
1291 * @uses VISIBLEGROUPS
1292 * @param course $course A {@link $COURSE} object
1293 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1294 * @param int $groupid Will try to use this optional parameter to
1295 * reset the current group for the user
1296 * @return int|false Returns the current group id or false if error.
1298 function get_and_set_current_group($course, $groupmode, $groupid=-1) {
1300 // Sets to the specified group, provided the current user has view permission
1301 if (!$groupmode) { // Groups don't even apply
1302 return false;
1305 $currentgroupid = get_current_group($course->id);
1307 if ($groupid < 0) { // No change was specified
1308 return $currentgroupid;
1311 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1312 if ($groupid and $group = get_record('groups', 'id', $groupid)) { // Try to change the current group to this groupid
1313 if ($group->courseid == $course->id) {
1314 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1315 $currentgroupid = set_current_group($course->id, $groupid);
1317 } elseif ($groupmode == VISIBLEGROUPS) {
1318 // All groups are visible
1319 //if (groups_is_member($group->id)){
1320 $currentgroupid = set_current_group($course->id, $groupid); //set this since he might post
1321 /*)}else {
1322 $currentgroupid = $group->id;*/
1323 } elseif ($groupmode == SEPARATEGROUPS) { // student in separate groups switching
1324 if (groups_is_member($groupid)) { //check if is a member
1325 $currentgroupid = set_current_group($course->id, $groupid); //might need to set_current_group?
1327 else {
1328 notify('You do not belong to this group! ('.$groupid.')', 'error');
1332 } else { // When groupid = 0 it means show ALL groups
1333 // this is changed, non editting teacher needs access to group 0 as well,
1334 // for viewing work in visible groups (need to set current group for multiple pages)
1335 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1336 $currentgroupid = set_current_group($course->id, 0);
1338 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1339 $currentgroupid = set_current_group($course->id, 0);
1343 return $currentgroupid;
1348 * A big combination function to make it easier for modules
1349 * to set up groups.
1351 * Terminates if the current user shouldn't be looking at this group
1352 * Otherwise returns the current group if there is one
1353 * Otherwise returns false if groups aren't relevant
1355 * @uses SEPARATEGROUPS
1356 * @uses VISIBLEGROUPS
1357 * @param course $course A {@link $COURSE} object
1358 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1359 * @param string $urlroot ?
1360 * @return int|false
1362 function setup_and_print_groups($course, $groupmode, $urlroot) {
1364 global $USER, $SESSION; //needs his id, need to hack his groups in session
1366 $changegroup = optional_param('group', -1, PARAM_INT);
1368 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
1369 if ($currentgroup === false) {
1370 return false;
1373 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1375 if ($groupmode == SEPARATEGROUPS and !$currentgroup and !has_capability('moodle/site:accessallgroups', $context)) {
1376 //we are in separate groups and the current group is group 0, as last set.
1377 //this can mean that either, this guy has no group
1378 //or, this guy just came from a visible all forum, and he left when he set his current group to 0 (show all)
1380 if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1381 //for the second situation, we need to perform the trick and get him a group.
1382 $first = reset($usergroups);
1383 $currentgroup = get_and_set_current_group($course, $groupmode, $first->id);
1385 } else {
1386 //else he has no group in this course
1387 print_heading(get_string('notingroup'));
1388 print_footer($course);
1389 exit;
1393 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/site:accessallgroups', $context))) {
1395 if ($groups = groups_get_all_groups($course->id)) {
1397 echo '<div class="groupselector">';
1398 print_group_menu($groups, $groupmode, $currentgroup, $urlroot, 1);
1399 echo '</div>';
1402 } else if ($groupmode == SEPARATEGROUPS and has_capability('moodle/course:view', $context)) {
1403 //get all the groups this guy is in in this course
1404 if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1405 echo '<div class="groupselector">';
1406 //print them in the menu
1407 print_group_menu($usergroups, $groupmode, $currentgroup, $urlroot, 0);
1408 echo '</div>';
1412 return $currentgroup;
1416 * Prints an appropriate group selection menu
1418 * @uses VISIBLEGROUPS
1419 * @param array $groups ?
1420 * @param int $groupmode ?
1421 * @param string $currentgroup ?
1422 * @param string $urlroot ?
1423 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
1424 * @todo Finish documenting this function
1426 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
1428 $output = '';
1429 $groupsmenu = array();
1431 /// Add an "All groups" to the start of the menu
1432 if ($showall){
1433 $groupsmenu[0] = get_string('allparticipants');
1435 foreach ($groups as $key => $group) {
1436 $groupsmenu[$key] = format_string($group->name);
1439 if ($groupmode == VISIBLEGROUPS) {
1440 $grouplabel = get_string('groupsvisible');
1441 } else {
1442 $grouplabel = get_string('groupsseparate');
1445 if (count($groupsmenu) == 1) {
1446 $groupname = reset($groupsmenu);
1447 $output .= $grouplabel.': '.$groupname;
1448 } else {
1449 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
1452 if ($return) {
1453 return $output;
1454 } else {
1455 echo $output;