MDL-11769:
[moodle-linuxchix.git] / lib / deprecatedlib.php
blob6b1652f73664e71ec993e9f0e7d237e0884ae427
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 onwards 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 $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
334 return $res;
338 * Unenrols a student from a given course
340 * @param int $courseid The id of the course that is being viewed, if any
341 * @param int $userid The id of the user that is being tested against.
342 * @return bool
344 function unenrol_student($userid, $courseid=0) {
345 global $CFG;
347 $status = true;
349 if ($courseid) {
350 /// First delete any crucial stuff that might still send mail
351 if ($forums = get_records('forum', 'course', $courseid)) {
352 foreach ($forums as $forum) {
353 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
356 /// remove from all legacy student roles
357 if ($courseid == SITEID) {
358 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
359 } else if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
360 return false;
362 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
363 return false;
365 foreach($roles as $role) {
366 $status = role_unassign($role->id, $userid, 0, $context->id) and $status;
368 } else {
369 // recursivelly unenroll student from all courses
370 if ($courses = get_records('course')) {
371 foreach($courses as $course) {
372 $status = unenrol_student($userid, $course->id) and $status;
377 return $status;
381 * Add a teacher to a given course
383 * @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.
384 * @param int $courseid The id of the course that is being viewed, if any
385 * @param int $editall Can edit the course
386 * @param string $role Obsolete
387 * @param int $timestart The time they start
388 * @param int $timeend The time they end in this role
389 * @param string $enrol The type of enrolment this is
390 * @return bool
392 function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
393 global $CFG;
395 if (!$user = get_record('user', 'id', $userid)) { // Check user
396 return false;
399 $capability = $editall ? 'moodle/legacy:editingteacher' : 'moodle/legacy:teacher';
401 if (!$roles = get_roles_with_capability($capability, CAP_ALLOW)) {
402 return false;
405 $role = array_shift($roles); // We can only use one, let's use the first one
407 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
408 return false;
411 $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
413 return $res;
417 * Removes a teacher from a given course (or ALL courses)
418 * Does not delete the user account
420 * @param int $courseid The id of the course that is being viewed, if any
421 * @param int $userid The id of the user that is being tested against.
422 * @return bool
424 function remove_teacher($userid, $courseid=0) {
425 global $CFG;
427 $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW);
429 if ($roles) {
430 $roles += get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
431 } else {
432 $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
435 if (empty($roles)) {
436 return true;
439 $return = true;
441 if ($courseid) {
443 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
444 return false;
447 /// First delete any crucial stuff that might still send mail
448 if ($forums = get_records('forum', 'course', $courseid)) {
449 foreach ($forums as $forum) {
450 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
454 /// No need to remove from groups now
456 foreach ($roles as $role) { // Unassign them from all the teacher roles
457 $newreturn = role_unassign($role->id, $userid, 0, $context->id);
458 if (empty($newreturn)) {
459 $return = false;
463 } else {
464 delete_records('forum_subscriptions', 'userid', $userid);
465 $return = true;
466 foreach ($roles as $role) { // Unassign them from all the teacher roles
467 $newreturn = role_unassign($role->id, $userid, 0, 0);
468 if (empty($newreturn)) {
469 $return = false;
474 return $return;
478 * Add an admin to a site
480 * @uses SITEID
481 * @param int $userid The id of the user that is being tested against.
482 * @return bool
483 * @TODO: remove from cvs
485 function add_admin($userid) {
486 return true;
489 function get_user_info_from_db($field, $value) { // For backward compatibility
490 return get_complete_user_data($field, $value);
495 * Get the guest user information from the database
497 * @return object(user) An associative array with the details of the guest user account.
498 * @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.
500 function get_guest() {
501 return get_complete_user_data('username', 'guest');
505 * Returns $user object of the main teacher for a course
507 * @uses $CFG
508 * @param int $courseid The course in question.
509 * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
510 * @todo Finish documenting this function
512 function get_teacher($courseid) {
514 global $CFG;
516 $context = get_context_instance(CONTEXT_COURSE, $courseid);
518 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*,ra.hidden', 'r.sortorder ASC',
519 '', '', '', '', false)) {
520 foreach ($users as $user) {
521 if (!$user->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) {
522 return $user;
527 return false;
531 * Searches logs to find all enrolments since a certain date
533 * used to print recent activity
535 * @uses $CFG
536 * @param int $courseid The course in question.
537 * @return object|false {@link $USER} records or false if error.
538 * @todo Finish documenting this function
540 function get_recent_enrolments($courseid, $timestart) {
542 global $CFG;
544 $context = get_context_instance(CONTEXT_COURSE, $courseid);
546 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
547 FROM {$CFG->prefix}user u,
548 {$CFG->prefix}role_assignments ra,
549 {$CFG->prefix}log l
550 WHERE l.time > '$timestart'
551 AND l.course = '$courseid'
552 AND l.module = 'course'
553 AND l.action = 'enrol'
554 AND l.info = u.id
555 AND u.id = ra.userid
556 AND ra.contextid ".get_related_contexts_string($context)."
557 ORDER BY l.time ASC");
561 * Returns array of userinfo of all students in this course
562 * or on this site if courseid is id of site
564 * @uses $CFG
565 * @uses SITEID
566 * @param int $courseid The course in question.
567 * @param string $sort ?
568 * @param string $dir ?
569 * @param int $page ?
570 * @param int $recordsperpage ?
571 * @param string $firstinitial ?
572 * @param string $lastinitial ?
573 * @param ? $group ?
574 * @param string $search ?
575 * @param string $fields A comma separated list of fields to be returned from the chosen table.
576 * @param string $exceptions ?
577 * @return object
578 * @todo Finish documenting this function
580 function get_course_students($courseid, $sort='ul.timeaccess', $dir='', $page='', $recordsperpage='',
581 $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
583 global $CFG;
585 // make sure it works on the site course
586 $context = get_context_instance(CONTEXT_COURSE, $courseid);
588 /// For the site course, old way was to check if $CFG->allusersaresitestudents was set to true.
589 /// The closest comparible method using roles is if the $CFG->defaultuserroleid is set to the legacy
590 /// student role. This function should be replaced where it is used with something more meaningful.
591 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
592 if ($roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW, $context)) {
593 $hascap = false;
594 foreach ($roles as $role) {
595 if ($role->id == $CFG->defaultuserroleid) {
596 $hascap = true;
597 break;
600 if ($hascap) {
601 // return users with confirmed, undeleted accounts who are not site teachers
602 // the following is a mess because of different conventions in the different user functions
603 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
604 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
605 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
606 $fields = str_replace('u.', '', $fields);
607 if ($sort) {
608 $sort = $sort .' '. $dir;
610 // Now we have to make sure site teachers are excluded
612 if ($teachers = get_course_teachers(SITEID)) {
613 foreach ($teachers as $teacher) {
614 $exceptions .= ','. $teacher->userid;
616 $exceptions = ltrim($exceptions, ',');
620 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
621 $page, $recordsperpage, $fields ? $fields : '*');
626 $LIKE = sql_ilike();
627 $fullname = sql_fullname('u.firstname','u.lastname');
629 $groupmembers = '';
631 $select = "c.contextlevel=".CONTEXT_COURSE." AND "; // Must be on a course
632 if ($courseid != SITEID) {
633 // If not site, require specific course
634 $select.= "c.instanceid=$courseid AND ";
636 $select.="rc.capability='moodle/legacy:student' AND rc.permission=".CAP_ALLOW." AND ";
638 $select .= ' u.deleted = \'0\' ';
640 if (!$fields) {
641 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
642 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
643 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
644 'u.emailstop, u.lang, u.timezone, ul.timeaccess as lastaccess';
647 if ($search) {
648 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
651 if ($firstinitial) {
652 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
655 if ($lastinitial) {
656 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
659 if ($group === 0) { /// Need something here to get all students not in a group
660 return array();
662 } else if ($group !== NULL) {
663 $groupmembers = "INNER JOIN {$CFG->prefix}groups_members gm on u.id=gm.userid";
664 $select .= ' AND gm.groupid = \''. $group .'\'';
667 if (!empty($exceptions)) {
668 $select .= ' AND u.id NOT IN ('. $exceptions .')';
671 if ($sort) {
672 $sort = ' ORDER BY '. $sort .' ';
675 $students = get_records_sql("SELECT $fields
676 FROM {$CFG->prefix}user u INNER JOIN
677 {$CFG->prefix}role_assignments ra on u.id=ra.userid INNER JOIN
678 {$CFG->prefix}role_capabilities rc ON ra.roleid=rc.roleid INNER JOIN
679 {$CFG->prefix}context c ON c.id=ra.contextid LEFT OUTER JOIN
680 {$CFG->prefix}user_lastaccess ul on ul.userid=ra.userid
681 $groupmembers
682 WHERE $select $search $sort $dir", $page, $recordsperpage);
684 return $students;
688 * Counts the students in a given course (or site), or a subset of them
690 * @param object $course The course in question as a course object.
691 * @param string $search ?
692 * @param string $firstinitial ?
693 * @param string $lastinitial ?
694 * @param ? $group ?
695 * @param string $exceptions ?
696 * @return int
697 * @todo Finish documenting this function
699 function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
701 if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
702 return count($students);
704 return 0;
708 * Returns list of all teachers in this course
710 * If $courseid matches the site id then this function
711 * returns a list of all teachers for the site.
713 * @uses $CFG
714 * @param int $courseid The course in question.
715 * @param string $sort ?
716 * @param string $exceptions ?
717 * @return object
718 * @todo Finish documenting this function
720 function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
722 global $CFG;
724 $sort = 'ul.timeaccess DESC';
726 $context = get_context_instance(CONTEXT_COURSE, $courseid);
728 /// For the site course, if the $CFG->defaultuserroleid is set to the legacy teacher role, then all
729 /// users are teachers. This function should be replaced where it is used with something more
730 /// meaningful.
731 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
732 if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW, $context)) {
733 $hascap = false;
734 foreach ($roles as $role) {
735 if ($role->id == $CFG->defaultuserroleid) {
736 $hascap = true;
737 break;
740 if ($hascap) {
741 if (empty($fields)) {
742 $fields = '*';
744 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
749 return get_users_by_capability($context, 'moodle/course:update', 'u.*, ul.timeaccess as lastaccess, ra.hidden', $sort, '','','',$exceptions, false);
750 /// some fields will be missing, like authority, editall
752 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
753 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
754 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
755 FROM {$CFG->prefix}user u,
756 {$CFG->prefix}user_teachers t
757 WHERE t.course = '$courseid' AND t.userid = u.id
758 AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
763 * Returns all the users of a course: students and teachers
765 * @param int $courseid The course in question.
766 * @param string $sort ?
767 * @param string $exceptions ?
768 * @param string $fields A comma separated list of fields to be returned from the chosen table.
769 * @return object
770 * @todo Finish documenting this function
772 function get_course_users($courseid, $sort='ul.timeaccess DESC', $exceptions='', $fields='u.*, ul.timeaccess as lastaccess') {
773 global $CFG;
775 $context = get_context_instance(CONTEXT_COURSE, $courseid);
777 /// If the course id is the SITEID, we need to return all the users if the "defaultuserroleid"
778 /// has the capbility of accessing the site course. $CFG->nodefaultuserrolelists set to true can
779 /// over-rule using this.
780 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
781 if ($roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
782 $hascap = false;
783 foreach ($roles as $role) {
784 if ($role->id == $CFG->defaultuserroleid) {
785 $hascap = true;
786 break;
789 if ($hascap) {
790 if (empty($fields)) {
791 $fields = '*';
793 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
797 return get_users_by_capability($context, 'moodle/course:view', $fields, $sort, '','','',$exceptions, false);
802 * Returns an array of user objects
804 * @uses $CFG
805 * @param int $groupid The group(s) in question.
806 * @param string $sort How to sort the results
807 * @return object (changed to groupids)
809 function get_group_students($groupids, $sort='ul.timeaccess DESC') {
811 if (is_array($groupids)){
812 $groups = $groupids;
813 // all groups must be from one course anyway...
814 $group = groups_get_group(array_shift($groups));
815 } else {
816 $group = groups_get_group($groupids);
818 if (!$group) {
819 return NULL;
822 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
823 return get_users_by_capability($context, 'moodle/legacy:student', 'u.*, ul.timeaccess as lastaccess', $sort, '','',$groupids, '', false);
827 * Returns list of all the teachers who can access a group
829 * @uses $CFG
830 * @param int $courseid The course in question.
831 * @param int $groupid The group in question.
832 * @return object
834 function get_group_teachers($courseid, $groupid) {
835 /// Returns a list of all the teachers who can access a group
836 if ($teachers = get_course_teachers($courseid)) {
837 foreach ($teachers as $key => $teacher) {
838 if ($teacher->editall) { // These can access anything
839 continue;
841 if (($teacher->authority > 0) and groups_is_member($groupid, $teacher->id)) { // Specific group teachers
842 continue;
844 unset($teachers[$key]);
847 return $teachers;
852 ########### FROM weblib.php ##########################################################################
856 * Print a message in a standard themed box.
857 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
858 * parameters remain. If possible, $align, $width and $color should not be defined at all.
859 * Preferably just use print_box() in weblib.php
861 * @param string $align, alignment of the box, not the text (default center, left, right).
862 * @param string $width, width of the box, including units %, for example '100%'.
863 * @param string $color, background colour of the box, for example '#eee'.
864 * @param int $padding, padding in pixels, specified without units.
865 * @param string $class, space-separated class names.
866 * @param string $id, space-separated id names.
867 * @param boolean $return, return as string or just print it
869 function print_simple_box($message, $align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
870 $output = '';
871 $output .= print_simple_box_start($align, $width, $color, $padding, $class, $id, true);
872 $output .= stripslashes_safe($message);
873 $output .= print_simple_box_end(true);
875 if ($return) {
876 return $output;
877 } else {
878 echo $output;
885 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
886 * parameters remain. If possible, $align, $width and $color should not be defined at all.
887 * Even better, please use print_box_start() in weblib.php
889 * @param string $align, alignment of the box, not the text (default center, left, right). DEPRECATED
890 * @param string $width, width of the box, including % units, for example '100%'. DEPRECATED
891 * @param string $color, background colour of the box, for example '#eee'. DEPRECATED
892 * @param int $padding, padding in pixels, specified without units. OBSOLETE
893 * @param string $class, space-separated class names.
894 * @param string $id, space-separated id names.
895 * @param boolean $return, return as string or just print it
897 function print_simple_box_start($align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
899 $output = '';
901 $divclasses = 'box '.$class.' '.$class.'content';
902 $divstyles = '';
904 if ($align) {
905 $divclasses .= ' boxalign'.$align; // Implement alignment using a class
907 if ($width) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
908 if (substr($width, -1, 1) == '%') { // Width is a % value
909 $width = (int) substr($width, 0, -1); // Extract just the number
910 if ($width < 40) {
911 $divclasses .= ' boxwidthnarrow'; // Approx 30% depending on theme
912 } else if ($width > 60) {
913 $divclasses .= ' boxwidthwide'; // Approx 80% depending on theme
914 } else {
915 $divclasses .= ' boxwidthnormal'; // Approx 50% depending on theme
917 } else {
918 $divstyles .= ' width:'.$width.';'; // Last resort
921 if ($color) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
922 $divstyles .= ' background:'.$color.';';
924 if ($divstyles) {
925 $divstyles = ' style="'.$divstyles.'"';
928 if ($id) {
929 $id = ' id="'.$id.'"';
932 $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
934 if ($return) {
935 return $output;
936 } else {
937 echo $output;
943 * Print the end portion of a standard themed box.
944 * Preferably just use print_box_end() in weblib.php
946 function print_simple_box_end($return=false) {
947 $output = '</div>';
948 if ($return) {
949 return $output;
950 } else {
951 echo $output;
956 * deprecated - use clean_param($string, PARAM_FILE); instead
957 * Check for bad characters ?
959 * @param string $string ?
960 * @param int $allowdots ?
961 * @todo Finish documenting this function - more detail needed in description as well as details on arguments
963 function detect_munged_arguments($string, $allowdots=1) {
964 if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references
965 return true;
967 if (ereg('[\|\`]', $string)) { // check for other bad characters
968 return true;
970 if (empty($string) or $string == '/') {
971 return true;
974 return false;
977 /** Deprecated function - returns the code of the current charset - originally depended on the selected language pack.
979 * @param $ignorecache not used anymore
980 * @return string always returns 'UTF-8'
982 function current_charset($ignorecache = false) {
983 return 'UTF-8';
987 /////////////////////////////////////////////////////////////
988 /// Old functions not used anymore - candidates for removal
989 /////////////////////////////////////////////////////////////
992 * Load a template from file - this function dates back to Moodle 1 :-) not used anymore
994 * Returns a (big) string containing the contents of a template file with all
995 * the variables interpolated. all the variables must be in the $var[] array or
996 * object (whatever you decide to use).
998 * <b>WARNING: do not use this on big files!!</b>
1000 * @param string $filename Location on the server's filesystem where template can be found.
1001 * @param mixed $var Passed in by reference. An array or object which will be loaded with data from the template file.
1004 function read_template($filename, &$var) {
1006 $temp = str_replace("\\", "\\\\", implode(file($filename), ''));
1007 $temp = str_replace('"', '\"', $temp);
1008 eval("\$template = \"$temp\";");
1009 return $template;
1014 * deprecated - relies on register globals; use new formslib instead
1016 * Set a variable's value depending on whether or not it already has a value.
1018 * If variable is set, set it to the set_value otherwise set it to the
1019 * unset_value. used to handle checkboxes when you are expecting them from
1020 * a form
1022 * @param mixed $var Passed in by reference. The variable to check.
1023 * @param mixed $set_value The value to set $var to if $var already has a value.
1024 * @param mixed $unset_value The value to set $var to if $var does not already have a value.
1026 function checked(&$var, $set_value = 1, $unset_value = 0) {
1028 if (empty($var)) {
1029 $var = $unset_value;
1030 } else {
1031 $var = $set_value;
1036 * deprecated - use new formslib instead
1038 * Prints the word "checked" if a variable is true, otherwise prints nothing,
1039 * used for printing the word "checked" in a checkbox form element.
1041 * @param boolean $var Variable to be checked for true value
1042 * @param string $true_value Value to be printed if $var is true
1043 * @param string $false_value Value to be printed if $var is false
1045 function frmchecked(&$var, $true_value = 'checked', $false_value = '') {
1047 if ($var) {
1048 echo $true_value;
1049 } else {
1050 echo $false_value;
1055 * Legacy function, provided for backward compatability.
1056 * This method now simply calls {@link use_html_editor()}
1058 * @deprecated Use {@link use_html_editor()} instead.
1059 * @param string $name Form element to replace with HTMl editor by name
1060 * @todo Finish documenting this function
1062 function print_richedit_javascript($form, $name, $source='no') {
1063 use_html_editor($name);
1066 /** various deprecated groups function **/
1070 * Returns the table in which group members are stored, with a prefix 'gm'.
1071 * @return SQL string.
1073 function groups_members_from_sql() {
1074 global $CFG;
1075 return " {$CFG->prefix}groups_members gm ";
1079 * Returns a join testing user.id against member's user ID.
1080 * Relies on 'user' table being included as 'user u'.
1081 * Used in Quiz module reports.
1082 * @param group ID, optional to include a test for this in the SQL.
1083 * @return SQL string.
1085 function groups_members_join_sql($groupid=false) {
1086 $sql = ' JOIN '.groups_members_from_sql().' ON u.id = gm.userid ';
1087 if ($groupid) {
1088 $sql = "AND gm.groupid = '$groupid' ";
1090 return $sql;
1091 //return ' INNER JOIN '.$CFG->prefix.'role_assignments ra ON u.id=ra.userid'.
1092 // ' INNER JOIN '.$CFG->prefix.'context c ON ra.contextid=c.id AND c.contextlevel='.CONTEXT_GROUP.' AND c.instanceid='.$groupid;
1096 * Returns SQL for a WHERE clause testing the group ID.
1097 * Optionally test the member's ID against another table's user ID column.
1098 * @param groupid
1099 * @param userid_sql Optional user ID column selector, example "mdl_user.id", or false.
1100 * @return SQL string.
1102 function groups_members_where_sql($groupid, $userid_sql=false) {
1103 $sql = " gm.groupid = '$groupid' ";
1104 if ($userid_sql) {
1105 $sql .= "AND $userid_sql = gm.userid ";
1107 return $sql;
1112 * Returns an array of group objects that the user is a member of
1113 * in the given course. If userid isn't specified, then return a
1114 * list of all groups in the course.
1116 * @uses $CFG
1117 * @param int $courseid The id of the course in question.
1118 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
1119 * @return object
1121 function get_groups($courseid, $userid=0) {
1122 return groups_get_all_groups($courseid, $userid);
1126 * Returns the user's groups in a particular course
1127 * note: this function originally returned only one group
1129 * @uses $CFG
1130 * @param int $courseid The course in question.
1131 * @param int $userid The id of the user as found in the 'user' table.
1132 * @param int $groupid The id of the group the user is in.
1133 * @return aray of groups
1135 function user_group($courseid, $userid) {
1136 return groups_get_all_groups($courseid, $userid);
1141 * Determines if the user is a member of the given group.
1143 * @param int $groupid The group to check for membership.
1144 * @param int $userid The user to check against the group.
1145 * @return boolean True if the user is a member, false otherwise.
1147 function ismember($groupid, $userid = null) {
1148 return groups_is_member($groupid, $userid);
1152 * Get the IDs for the user's groups in the given course.
1154 * @uses $USER
1155 * @param int $courseid The course being examined - the 'course' table id field.
1156 * @return array An _array_ of groupids.
1157 * (Was return $groupids[0] - consequences!)
1159 function mygroupid($courseid) {
1160 global $USER;
1161 if ($groups = groups_get_all_groups($courseid, $USER->id)) {
1162 return array_keys($groups);
1163 } else {
1164 return false;
1169 * Add a user to a group, return true upon success or if user already a group
1170 * member
1172 * @param int $groupid The group id to add user to
1173 * @param int $userid The user id to add to the group
1174 * @return bool
1176 function add_user_to_group($groupid, $userid) {
1177 global $CFG;
1178 require_once($CFG->dirroot.'/group/lib.php');
1180 return groups_add_member($groupid, $userid);
1185 * Returns an array of user objects
1187 * @uses $CFG
1188 * @param int $groupid The group in question.
1189 * @param string $sort ?
1190 * @param string $exceptions ?
1191 * @return object
1192 * @todo Finish documenting this function
1194 function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='',
1195 $fields='u.*') {
1196 global $CFG;
1197 if (!empty($exceptions)) {
1198 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1199 } else {
1200 $except = '';
1202 // in postgres, you can't have things in sort that aren't in the select, so...
1203 $extrafield = str_replace('ASC','',$sort);
1204 $extrafield = str_replace('DESC','',$extrafield);
1205 $extrafield = trim($extrafield);
1206 if (!empty($extrafield)) {
1207 $extrafield = ','.$extrafield;
1209 return get_records_sql("SELECT DISTINCT $fields $extrafield
1210 FROM {$CFG->prefix}user u,
1211 {$CFG->prefix}groups_members m
1212 WHERE m.groupid = '$groupid'
1213 AND m.userid = u.id $except
1214 ORDER BY $sort");
1218 * Returns the current group mode for a given course or activity module
1220 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
1222 function groupmode($course, $cm=null) {
1224 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
1225 return $cm->groupmode;
1227 return $course->groupmode;
1232 * Sets the current group in the session variable
1233 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
1234 * Sets currentgroup[$courseid] in the session variable appropriately.
1235 * Does not do any permission checking.
1236 * @uses $SESSION
1237 * @param int $courseid The course being examined - relates to id field in
1238 * 'course' table.
1239 * @param int $groupid The group being examined.
1240 * @return int Current group id which was set by this function
1242 function set_current_group($courseid, $groupid) {
1243 global $SESSION;
1244 return $SESSION->currentgroup[$courseid] = $groupid;
1249 * Gets the current group - either from the session variable or from the database.
1251 * @uses $USER
1252 * @uses $SESSION
1253 * @param int $courseid The course being examined - relates to id field in
1254 * 'course' table.
1255 * @param bool $full If true, the return value is a full record object.
1256 * If false, just the id of the record.
1258 function get_current_group($courseid, $full = false) {
1259 global $SESSION;
1261 if (isset($SESSION->currentgroup[$courseid])) {
1262 if ($full) {
1263 return groups_get_group($SESSION->currentgroup[$courseid]);
1264 } else {
1265 return $SESSION->currentgroup[$courseid];
1269 $mygroupid = mygroupid($courseid);
1270 if (is_array($mygroupid)) {
1271 $mygroupid = array_shift($mygroupid);
1272 set_current_group($courseid, $mygroupid);
1273 if ($full) {
1274 return groups_get_group($mygroupid);
1275 } else {
1276 return $mygroupid;
1280 if ($full) {
1281 return false;
1282 } else {
1283 return 0;
1289 * A combination function to make it easier for modules
1290 * to set up groups.
1292 * It will use a given "groupid" parameter and try to use
1293 * that to reset the current group for the user.
1295 * @uses VISIBLEGROUPS
1296 * @param course $course A {@link $COURSE} object
1297 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1298 * @param int $groupid Will try to use this optional parameter to
1299 * reset the current group for the user
1300 * @return int|false Returns the current group id or false if error.
1302 function get_and_set_current_group($course, $groupmode, $groupid=-1) {
1304 // Sets to the specified group, provided the current user has view permission
1305 if (!$groupmode) { // Groups don't even apply
1306 return false;
1309 $currentgroupid = get_current_group($course->id);
1311 if ($groupid < 0) { // No change was specified
1312 return $currentgroupid;
1315 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1316 if ($groupid and $group = get_record('groups', 'id', $groupid)) { // Try to change the current group to this groupid
1317 if ($group->courseid == $course->id) {
1318 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1319 $currentgroupid = set_current_group($course->id, $groupid);
1321 } elseif ($groupmode == VISIBLEGROUPS) {
1322 // All groups are visible
1323 //if (groups_is_member($group->id)){
1324 $currentgroupid = set_current_group($course->id, $groupid); //set this since he might post
1325 /*)}else {
1326 $currentgroupid = $group->id;*/
1327 } elseif ($groupmode == SEPARATEGROUPS) { // student in separate groups switching
1328 if (groups_is_member($groupid)) { //check if is a member
1329 $currentgroupid = set_current_group($course->id, $groupid); //might need to set_current_group?
1331 else {
1332 notify('You do not belong to this group! ('.$groupid.')', 'error');
1336 } else { // When groupid = 0 it means show ALL groups
1337 // this is changed, non editting teacher needs access to group 0 as well,
1338 // for viewing work in visible groups (need to set current group for multiple pages)
1339 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1340 $currentgroupid = set_current_group($course->id, 0);
1342 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1343 $currentgroupid = set_current_group($course->id, 0);
1347 return $currentgroupid;
1352 * A big combination function to make it easier for modules
1353 * to set up groups.
1355 * Terminates if the current user shouldn't be looking at this group
1356 * Otherwise returns the current group if there is one
1357 * Otherwise returns false if groups aren't relevant
1359 * @uses SEPARATEGROUPS
1360 * @uses VISIBLEGROUPS
1361 * @param course $course A {@link $COURSE} object
1362 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1363 * @param string $urlroot ?
1364 * @return int|false
1366 function setup_and_print_groups($course, $groupmode, $urlroot) {
1368 global $USER, $SESSION; //needs his id, need to hack his groups in session
1370 $changegroup = optional_param('group', -1, PARAM_INT);
1372 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
1373 if ($currentgroup === false) {
1374 return false;
1377 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1379 if ($groupmode == SEPARATEGROUPS and !$currentgroup and !has_capability('moodle/site:accessallgroups', $context)) {
1380 //we are in separate groups and the current group is group 0, as last set.
1381 //this can mean that either, this guy has no group
1382 //or, this guy just came from a visible all forum, and he left when he set his current group to 0 (show all)
1384 if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1385 //for the second situation, we need to perform the trick and get him a group.
1386 $first = reset($usergroups);
1387 $currentgroup = get_and_set_current_group($course, $groupmode, $first->id);
1389 } else {
1390 //else he has no group in this course
1391 print_heading(get_string('notingroup'));
1392 print_footer($course);
1393 exit;
1397 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/site:accessallgroups', $context))) {
1399 if ($groups = groups_get_all_groups($course->id)) {
1401 echo '<div class="groupselector">';
1402 print_group_menu($groups, $groupmode, $currentgroup, $urlroot, 1);
1403 echo '</div>';
1406 } else if ($groupmode == SEPARATEGROUPS and has_capability('moodle/course:view', $context)) {
1407 //get all the groups this guy is in in this course
1408 if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1409 echo '<div class="groupselector">';
1410 //print them in the menu
1411 print_group_menu($usergroups, $groupmode, $currentgroup, $urlroot, 0);
1412 echo '</div>';
1416 return $currentgroup;
1420 * Prints an appropriate group selection menu
1422 * @uses VISIBLEGROUPS
1423 * @param array $groups ?
1424 * @param int $groupmode ?
1425 * @param string $currentgroup ?
1426 * @param string $urlroot ?
1427 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
1428 * @todo Finish documenting this function
1430 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
1432 $output = '';
1433 $groupsmenu = array();
1435 /// Add an "All groups" to the start of the menu
1436 if ($showall){
1437 $groupsmenu[0] = get_string('allparticipants');
1439 foreach ($groups as $key => $group) {
1440 $groupsmenu[$key] = format_string($group->name);
1443 if ($groupmode == VISIBLEGROUPS) {
1444 $grouplabel = get_string('groupsvisible');
1445 } else {
1446 $grouplabel = get_string('groupsseparate');
1449 if (count($groupsmenu) == 1) {
1450 $groupname = reset($groupsmenu);
1451 $output .= $grouplabel.': '.$groupname;
1452 } else {
1453 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
1456 if ($return) {
1457 return $output;
1458 } else {
1459 echo $output;
1465 * All users that we have not seen for a really long time (ie dead accounts)
1466 * TODO: Delete this for Moodle 2.0
1468 * @uses $CFG
1469 * @deprecated The query is executed directly within admin/cron.php (MDL-11571)
1470 * @param string $cutofftime ?
1471 * @return object {@link $USER} records
1473 function get_users_longtimenosee($cutofftime) {
1474 global $CFG;
1475 return get_records_sql("SELECT id, userid, courseid
1476 FROM {$CFG->prefix}user_lastaccess
1477 WHERE courseid != ".SITEID."
1478 AND timeaccess < $cutofftime ");
1482 * Full list of users that have not yet confirmed their accounts.
1483 * TODO: Delete this for Moodle 2.0
1485 * @uses $CFG
1486 * @deprecated The query is executed directly within admin/cron.php (MDL-11487)
1487 * @param string $cutofftime ?
1488 * @return object {@link $USER} records
1490 function get_users_unconfirmed($cutofftime=2000000000) {
1491 global $CFG;
1492 return get_records_sql("SELECT *
1493 FROM {$CFG->prefix}user
1494 WHERE confirmed = 0
1495 AND firstaccess > 0
1496 AND firstaccess < $cutofftime");
1500 * Full list of bogus accounts that are probably not ever going to be used
1501 * TODO: Delete this for Moodle 2.0
1503 * @uses $CFG
1504 * @deprecated The query is executed directly within admin/cron.php (MDL-11487)
1505 * @param string $cutofftime ?
1506 * @return object {@link $USER} records
1508 function get_users_not_fully_set_up($cutofftime=2000000000) {
1509 global $CFG;
1510 return get_records_sql("SELECT *
1511 FROM {$CFG->prefix}user
1512 WHERE confirmed = 1
1513 AND lastaccess > 0
1514 AND lastaccess < $cutofftime
1515 AND deleted = 0
1516 AND (lastname = '' OR firstname = '' OR email = '')");