MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / lib / deprecatedlib.php
blob8ce1ac2fff3af4496c85d0ec4b2dcab4f6933bb9
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 $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
334 // force accessinfo refresh for users visiting this context...
335 mark_context_dirty($context->path);
337 return $res;
341 * Unenrols a student from a given course
343 * @param int $courseid The id of the course that is being viewed, if any
344 * @param int $userid The id of the user that is being tested against.
345 * @return bool
347 function unenrol_student($userid, $courseid=0) {
348 global $CFG;
350 $status = true;
352 if ($courseid) {
353 /// First delete any crucial stuff that might still send mail
354 if ($forums = get_records('forum', 'course', $courseid)) {
355 foreach ($forums as $forum) {
356 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
359 /// remove from all legacy student roles
360 if ($courseid == SITEID) {
361 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
362 } else if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
363 return false;
365 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
366 return false;
368 foreach($roles as $role) {
369 $status = role_unassign($role->id, $userid, 0, $context->id) and $status;
371 // force accessinfo refresh for users visiting this context...
372 mark_context_dirty($context->path);
373 } else {
374 // recursivelly unenroll student from all courses
375 if ($courses = get_records('course')) {
376 foreach($courses as $course) {
377 $status = unenrol_student($userid, $course->id) and $status;
382 return $status;
386 * Add a teacher to a given course
388 * @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.
389 * @param int $courseid The id of the course that is being viewed, if any
390 * @param int $editall Can edit the course
391 * @param string $role Obsolete
392 * @param int $timestart The time they start
393 * @param int $timeend The time they end in this role
394 * @param string $enrol The type of enrolment this is
395 * @return bool
397 function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
398 global $CFG;
400 if (!$user = get_record('user', 'id', $userid)) { // Check user
401 return false;
404 $capability = $editall ? 'moodle/legacy:editingteacher' : 'moodle/legacy:teacher';
406 if (!$roles = get_roles_with_capability($capability, CAP_ALLOW)) {
407 return false;
410 $role = array_shift($roles); // We can only use one, let's use the first one
412 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
413 return false;
416 $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
418 // force accessinfo refresh for users visiting this context...
419 mark_context_dirty($context->path);
421 return $res;
425 * Removes a teacher from a given course (or ALL courses)
426 * Does not delete the user account
428 * @param int $courseid The id of the course that is being viewed, if any
429 * @param int $userid The id of the user that is being tested against.
430 * @return bool
432 function remove_teacher($userid, $courseid=0) {
433 global $CFG;
435 $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW);
437 if ($roles) {
438 $roles += get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
439 } else {
440 $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
443 if (empty($roles)) {
444 return true;
447 $return = true;
449 if ($courseid) {
451 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
452 return false;
455 /// First delete any crucial stuff that might still send mail
456 if ($forums = get_records('forum', 'course', $courseid)) {
457 foreach ($forums as $forum) {
458 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
462 /// No need to remove from groups now
464 foreach ($roles as $role) { // Unassign them from all the teacher roles
465 $newreturn = role_unassign($role->id, $userid, 0, $context->id);
466 if (empty($newreturn)) {
467 $return = false;
470 // force accessinfo refresh for users visiting this context...
471 mark_context_dirty($context->path);
473 } else {
474 delete_records('forum_subscriptions', 'userid', $userid);
475 $return = true;
476 foreach ($roles as $role) { // Unassign them from all the teacher roles
477 $newreturn = role_unassign($role->id, $userid, 0, 0);
478 if (empty($newreturn)) {
479 $return = false;
484 return $return;
488 * Add an admin to a site
490 * @uses SITEID
491 * @param int $userid The id of the user that is being tested against.
492 * @return bool
493 * @TODO: remove from cvs
495 function add_admin($userid) {
496 return true;
499 function get_user_info_from_db($field, $value) { // For backward compatibility
500 return get_complete_user_data($field, $value);
505 * Get the guest user information from the database
507 * @return object(user) An associative array with the details of the guest user account.
508 * @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.
510 function get_guest() {
511 return get_complete_user_data('username', 'guest');
515 * Returns $user object of the main teacher for a course
517 * @uses $CFG
518 * @param int $courseid The course in question.
519 * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
520 * @todo Finish documenting this function
522 function get_teacher($courseid) {
524 global $CFG;
526 $context = get_context_instance(CONTEXT_COURSE, $courseid);
528 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*,ra.hidden', 'r.sortorder ASC',
529 '', '', '', '', false)) {
530 foreach ($users as $user) {
531 if (!$user->hidden || has_capability('moodle/role:viewhiddenassigns', $context)) {
532 return $user;
537 return false;
541 * Searches logs to find all enrolments since a certain date
543 * used to print recent activity
545 * @uses $CFG
546 * @param int $courseid The course in question.
547 * @return object|false {@link $USER} records or false if error.
548 * @todo Finish documenting this function
550 function get_recent_enrolments($courseid, $timestart) {
552 global $CFG;
554 $context = get_context_instance(CONTEXT_COURSE, $courseid);
556 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
557 FROM {$CFG->prefix}user u,
558 {$CFG->prefix}role_assignments ra,
559 {$CFG->prefix}log l
560 WHERE l.time > '$timestart'
561 AND l.course = '$courseid'
562 AND l.module = 'course'
563 AND l.action = 'enrol'
564 AND l.info = u.id
565 AND u.id = ra.userid
566 AND ra.contextid ".get_related_contexts_string($context)."
567 ORDER BY l.time ASC");
571 * Returns array of userinfo of all students in this course
572 * or on this site if courseid is id of site
574 * @uses $CFG
575 * @uses SITEID
576 * @param int $courseid The course in question.
577 * @param string $sort ?
578 * @param string $dir ?
579 * @param int $page ?
580 * @param int $recordsperpage ?
581 * @param string $firstinitial ?
582 * @param string $lastinitial ?
583 * @param ? $group ?
584 * @param string $search ?
585 * @param string $fields A comma separated list of fields to be returned from the chosen table.
586 * @param string $exceptions ?
587 * @return object
588 * @todo Finish documenting this function
590 function get_course_students($courseid, $sort='ul.timeaccess', $dir='', $page='', $recordsperpage='',
591 $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
593 global $CFG;
595 // make sure it works on the site course
596 $context = get_context_instance(CONTEXT_COURSE, $courseid);
598 /// For the site course, old way was to check if $CFG->allusersaresitestudents was set to true.
599 /// The closest comparible method using roles is if the $CFG->defaultuserroleid is set to the legacy
600 /// student role. This function should be replaced where it is used with something more meaningful.
601 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
602 if ($roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW, $context)) {
603 $hascap = false;
604 foreach ($roles as $role) {
605 if ($role->id == $CFG->defaultuserroleid) {
606 $hascap = true;
607 break;
610 if ($hascap) {
611 // return users with confirmed, undeleted accounts who are not site teachers
612 // the following is a mess because of different conventions in the different user functions
613 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
614 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
615 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
616 $fields = str_replace('u.', '', $fields);
617 if ($sort) {
618 $sort = $sort .' '. $dir;
620 // Now we have to make sure site teachers are excluded
622 if ($teachers = get_course_teachers(SITEID)) {
623 foreach ($teachers as $teacher) {
624 $exceptions .= ','. $teacher->userid;
626 $exceptions = ltrim($exceptions, ',');
630 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
631 $page, $recordsperpage, $fields ? $fields : '*');
636 $LIKE = sql_ilike();
637 $fullname = sql_fullname('u.firstname','u.lastname');
639 $groupmembers = '';
641 $select = "c.contextlevel=".CONTEXT_COURSE." AND "; // Must be on a course
642 if ($courseid != SITEID) {
643 // If not site, require specific course
644 $select.= "c.instanceid=$courseid AND ";
646 $select.="rc.capability='moodle/legacy:student' AND rc.permission=".CAP_ALLOW." AND ";
648 $select .= ' u.deleted = \'0\' ';
650 if (!$fields) {
651 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
652 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
653 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
654 'u.emailstop, u.lang, u.timezone, ul.timeaccess as lastaccess';
657 if ($search) {
658 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
661 if ($firstinitial) {
662 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
665 if ($lastinitial) {
666 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
669 if ($group === 0) { /// Need something here to get all students not in a group
670 return array();
672 } else if ($group !== NULL) {
673 $groupmembers = "INNER JOIN {$CFG->prefix}groups_members gm on u.id=gm.userid";
674 $select .= ' AND gm.groupid = \''. $group .'\'';
677 if (!empty($exceptions)) {
678 $select .= ' AND u.id NOT IN ('. $exceptions .')';
681 if ($sort) {
682 $sort = ' ORDER BY '. $sort .' ';
685 $students = get_records_sql("SELECT $fields
686 FROM {$CFG->prefix}user u INNER JOIN
687 {$CFG->prefix}role_assignments ra on u.id=ra.userid INNER JOIN
688 {$CFG->prefix}role_capabilities rc ON ra.roleid=rc.roleid INNER JOIN
689 {$CFG->prefix}context c ON c.id=ra.contextid LEFT OUTER JOIN
690 {$CFG->prefix}user_lastaccess ul on ul.userid=ra.userid
691 $groupmembers
692 WHERE $select $search $sort $dir", $page, $recordsperpage);
694 return $students;
698 * Counts the students in a given course (or site), or a subset of them
700 * @param object $course The course in question as a course object.
701 * @param string $search ?
702 * @param string $firstinitial ?
703 * @param string $lastinitial ?
704 * @param ? $group ?
705 * @param string $exceptions ?
706 * @return int
707 * @todo Finish documenting this function
709 function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
711 if ($students = get_course_students($course->id, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
712 return count($students);
714 return 0;
718 * Returns list of all teachers in this course
720 * If $courseid matches the site id then this function
721 * returns a list of all teachers for the site.
723 * @uses $CFG
724 * @param int $courseid The course in question.
725 * @param string $sort ?
726 * @param string $exceptions ?
727 * @return object
728 * @todo Finish documenting this function
730 function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
732 global $CFG;
734 $sort = 'ul.timeaccess DESC';
736 $context = get_context_instance(CONTEXT_COURSE, $courseid);
738 /// For the site course, if the $CFG->defaultuserroleid is set to the legacy teacher role, then all
739 /// users are teachers. This function should be replaced where it is used with something more
740 /// meaningful.
741 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
742 if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW, $context)) {
743 $hascap = false;
744 foreach ($roles as $role) {
745 if ($role->id == $CFG->defaultuserroleid) {
746 $hascap = true;
747 break;
750 if ($hascap) {
751 if (empty($fields)) {
752 $fields = '*';
754 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
759 return get_users_by_capability($context, 'moodle/course:update', 'u.*, ul.timeaccess as lastaccess, ra.hidden', $sort, '','','',$exceptions, false);
760 /// some fields will be missing, like authority, editall
762 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
763 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
764 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
765 FROM {$CFG->prefix}user u,
766 {$CFG->prefix}user_teachers t
767 WHERE t.course = '$courseid' AND t.userid = u.id
768 AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
773 * Returns all the users of a course: students and teachers
775 * @param int $courseid The course in question.
776 * @param string $sort ?
777 * @param string $exceptions ?
778 * @param string $fields A comma separated list of fields to be returned from the chosen table.
779 * @return object
780 * @todo Finish documenting this function
782 function get_course_users($courseid, $sort='ul.timeaccess DESC', $exceptions='', $fields='u.*, ul.timeaccess as lastaccess') {
783 global $CFG;
785 $context = get_context_instance(CONTEXT_COURSE, $courseid);
787 /// If the course id is the SITEID, we need to return all the users if the "defaultuserroleid"
788 /// has the capbility of accessing the site course. $CFG->nodefaultuserrolelists set to true can
789 /// over-rule using this.
790 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
791 if ($roles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
792 $hascap = false;
793 foreach ($roles as $role) {
794 if ($role->id == $CFG->defaultuserroleid) {
795 $hascap = true;
796 break;
799 if ($hascap) {
800 if (empty($fields)) {
801 $fields = '*';
803 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
807 return get_users_by_capability($context, 'moodle/course:view', $fields, $sort, '','','',$exceptions, false);
812 * Returns an array of user objects
814 * @uses $CFG
815 * @param int $groupid The group(s) in question.
816 * @param string $sort How to sort the results
817 * @return object (changed to groupids)
819 function get_group_students($groupids, $sort='ul.timeaccess DESC') {
821 if (is_array($groupids)){
822 $groups = $groupids;
823 // all groups must be from one course anyway...
824 $group = groups_get_group(array_shift($groups));
825 } else {
826 $group = groups_get_group($groupids);
828 if (!$group) {
829 return NULL;
832 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
833 return get_users_by_capability($context, 'moodle/legacy:student', 'u.*, ul.timeaccess as lastaccess', $sort, '','',$groupids, '', false);
837 * Returns list of all the teachers who can access a group
839 * @uses $CFG
840 * @param int $courseid The course in question.
841 * @param int $groupid The group in question.
842 * @return object
844 function get_group_teachers($courseid, $groupid) {
845 /// Returns a list of all the teachers who can access a group
846 if ($teachers = get_course_teachers($courseid)) {
847 foreach ($teachers as $key => $teacher) {
848 if ($teacher->editall) { // These can access anything
849 continue;
851 if (($teacher->authority > 0) and groups_is_member($groupid, $teacher->id)) { // Specific group teachers
852 continue;
854 unset($teachers[$key]);
857 return $teachers;
862 ########### FROM weblib.php ##########################################################################
866 * Print a message in a standard themed box.
867 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
868 * parameters remain. If possible, $align, $width and $color should not be defined at all.
869 * Preferably just use print_box() in weblib.php
871 * @param string $align, alignment of the box, not the text (default center, left, right).
872 * @param string $width, width of the box, including units %, for example '100%'.
873 * @param string $color, background colour of the box, for example '#eee'.
874 * @param int $padding, padding in pixels, specified without units.
875 * @param string $class, space-separated class names.
876 * @param string $id, space-separated id names.
877 * @param boolean $return, return as string or just print it
879 function print_simple_box($message, $align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
880 $output = '';
881 $output .= print_simple_box_start($align, $width, $color, $padding, $class, $id, true);
882 $output .= stripslashes_safe($message);
883 $output .= print_simple_box_end(true);
885 if ($return) {
886 return $output;
887 } else {
888 echo $output;
895 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
896 * parameters remain. If possible, $align, $width and $color should not be defined at all.
897 * Even better, please use print_box_start() in weblib.php
899 * @param string $align, alignment of the box, not the text (default center, left, right). DEPRECATED
900 * @param string $width, width of the box, including % units, for example '100%'. DEPRECATED
901 * @param string $color, background colour of the box, for example '#eee'. DEPRECATED
902 * @param int $padding, padding in pixels, specified without units. OBSOLETE
903 * @param string $class, space-separated class names.
904 * @param string $id, space-separated id names.
905 * @param boolean $return, return as string or just print it
907 function print_simple_box_start($align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
909 $output = '';
911 $divclasses = 'box '.$class.' '.$class.'content';
912 $divstyles = '';
914 if ($align) {
915 $divclasses .= ' boxalign'.$align; // Implement alignment using a class
917 if ($width) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
918 if (substr($width, -1, 1) == '%') { // Width is a % value
919 $width = (int) substr($width, 0, -1); // Extract just the number
920 if ($width < 40) {
921 $divclasses .= ' boxwidthnarrow'; // Approx 30% depending on theme
922 } else if ($width > 60) {
923 $divclasses .= ' boxwidthwide'; // Approx 80% depending on theme
924 } else {
925 $divclasses .= ' boxwidthnormal'; // Approx 50% depending on theme
927 } else {
928 $divstyles .= ' width:'.$width.';'; // Last resort
931 if ($color) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
932 $divstyles .= ' background:'.$color.';';
934 if ($divstyles) {
935 $divstyles = ' style="'.$divstyles.'"';
938 if ($id) {
939 $id = ' id="'.$id.'"';
942 $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
944 if ($return) {
945 return $output;
946 } else {
947 echo $output;
953 * Print the end portion of a standard themed box.
954 * Preferably just use print_box_end() in weblib.php
956 function print_simple_box_end($return=false) {
957 $output = '</div>';
958 if ($return) {
959 return $output;
960 } else {
961 echo $output;
966 * deprecated - use clean_param($string, PARAM_FILE); instead
967 * Check for bad characters ?
969 * @param string $string ?
970 * @param int $allowdots ?
971 * @todo Finish documenting this function - more detail needed in description as well as details on arguments
973 function detect_munged_arguments($string, $allowdots=1) {
974 if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references
975 return true;
977 if (ereg('[\|\`]', $string)) { // check for other bad characters
978 return true;
980 if (empty($string) or $string == '/') {
981 return true;
984 return false;
987 /** Deprecated function - returns the code of the current charset - originally depended on the selected language pack.
989 * @param $ignorecache not used anymore
990 * @return string always returns 'UTF-8'
992 function current_charset($ignorecache = false) {
993 return 'UTF-8';
997 /////////////////////////////////////////////////////////////
998 /// Old functions not used anymore - candidates for removal
999 /////////////////////////////////////////////////////////////
1002 * Load a template from file - this function dates back to Moodle 1 :-) not used anymore
1004 * Returns a (big) string containing the contents of a template file with all
1005 * the variables interpolated. all the variables must be in the $var[] array or
1006 * object (whatever you decide to use).
1008 * <b>WARNING: do not use this on big files!!</b>
1010 * @param string $filename Location on the server's filesystem where template can be found.
1011 * @param mixed $var Passed in by reference. An array or object which will be loaded with data from the template file.
1014 function read_template($filename, &$var) {
1016 $temp = str_replace("\\", "\\\\", implode(file($filename), ''));
1017 $temp = str_replace('"', '\"', $temp);
1018 eval("\$template = \"$temp\";");
1019 return $template;
1024 * deprecated - relies on register globals; use new formslib instead
1026 * Set a variable's value depending on whether or not it already has a value.
1028 * If variable is set, set it to the set_value otherwise set it to the
1029 * unset_value. used to handle checkboxes when you are expecting them from
1030 * a form
1032 * @param mixed $var Passed in by reference. The variable to check.
1033 * @param mixed $set_value The value to set $var to if $var already has a value.
1034 * @param mixed $unset_value The value to set $var to if $var does not already have a value.
1036 function checked(&$var, $set_value = 1, $unset_value = 0) {
1038 if (empty($var)) {
1039 $var = $unset_value;
1040 } else {
1041 $var = $set_value;
1046 * deprecated - use new formslib instead
1048 * Prints the word "checked" if a variable is true, otherwise prints nothing,
1049 * used for printing the word "checked" in a checkbox form element.
1051 * @param boolean $var Variable to be checked for true value
1052 * @param string $true_value Value to be printed if $var is true
1053 * @param string $false_value Value to be printed if $var is false
1055 function frmchecked(&$var, $true_value = 'checked', $false_value = '') {
1057 if ($var) {
1058 echo $true_value;
1059 } else {
1060 echo $false_value;
1065 * Legacy function, provided for backward compatability.
1066 * This method now simply calls {@link use_html_editor()}
1068 * @deprecated Use {@link use_html_editor()} instead.
1069 * @param string $name Form element to replace with HTMl editor by name
1070 * @todo Finish documenting this function
1072 function print_richedit_javascript($form, $name, $source='no') {
1073 use_html_editor($name);
1076 /** various deprecated groups function **/
1080 * Returns the table in which group members are stored, with a prefix 'gm'.
1081 * @return SQL string.
1083 function groups_members_from_sql() {
1084 global $CFG;
1085 return " {$CFG->prefix}groups_members gm ";
1089 * Returns a join testing user.id against member's user ID.
1090 * Relies on 'user' table being included as 'user u'.
1091 * Used in Quiz module reports.
1092 * @param group ID, optional to include a test for this in the SQL.
1093 * @return SQL string.
1095 function groups_members_join_sql($groupid=false) {
1096 $sql = ' JOIN '.groups_members_from_sql().' ON u.id = gm.userid ';
1097 if ($groupid) {
1098 $sql = "AND gm.groupid = '$groupid' ";
1100 return $sql;
1101 //return ' INNER JOIN '.$CFG->prefix.'role_assignments ra ON u.id=ra.userid'.
1102 // ' INNER JOIN '.$CFG->prefix.'context c ON ra.contextid=c.id AND c.contextlevel='.CONTEXT_GROUP.' AND c.instanceid='.$groupid;
1106 * Returns SQL for a WHERE clause testing the group ID.
1107 * Optionally test the member's ID against another table's user ID column.
1108 * @param groupid
1109 * @param userid_sql Optional user ID column selector, example "mdl_user.id", or false.
1110 * @return SQL string.
1112 function groups_members_where_sql($groupid, $userid_sql=false) {
1113 $sql = " gm.groupid = '$groupid' ";
1114 if ($userid_sql) {
1115 $sql .= "AND $userid_sql = gm.userid ";
1117 return $sql;
1122 * Returns an array of group objects that the user is a member of
1123 * in the given course. If userid isn't specified, then return a
1124 * list of all groups in the course.
1126 * @uses $CFG
1127 * @param int $courseid The id of the course in question.
1128 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
1129 * @return object
1131 function get_groups($courseid, $userid=0) {
1132 return groups_get_all_groups($courseid, $userid);
1136 * Returns the user's groups in a particular course
1137 * note: this function originally returned only one group
1139 * @uses $CFG
1140 * @param int $courseid The course in question.
1141 * @param int $userid The id of the user as found in the 'user' table.
1142 * @param int $groupid The id of the group the user is in.
1143 * @return aray of groups
1145 function user_group($courseid, $userid) {
1146 return groups_get_all_groups($courseid, $userid);
1151 * Determines if the user is a member of the given group.
1153 * @param int $groupid The group to check for membership.
1154 * @param int $userid The user to check against the group.
1155 * @return boolean True if the user is a member, false otherwise.
1157 function ismember($groupid, $userid = null) {
1158 return groups_is_member($groupid, $userid);
1162 * Get the IDs for the user's groups in the given course.
1164 * @uses $USER
1165 * @param int $courseid The course being examined - the 'course' table id field.
1166 * @return array An _array_ of groupids.
1167 * (Was return $groupids[0] - consequences!)
1169 function mygroupid($courseid) {
1170 global $USER;
1171 if ($groups = groups_get_all_groups($courseid, $USER->id)) {
1172 return array_keys($groups);
1173 } else {
1174 return false;
1179 * Add a user to a group, return true upon success or if user already a group
1180 * member
1182 * @param int $groupid The group id to add user to
1183 * @param int $userid The user id to add to the group
1184 * @return bool
1186 function add_user_to_group($groupid, $userid) {
1187 global $CFG;
1188 require_once($CFG->dirroot.'/group/lib.php');
1190 return groups_add_member($groupid, $userid);
1195 * Returns an array of user objects
1197 * @uses $CFG
1198 * @param int $groupid The group in question.
1199 * @param string $sort ?
1200 * @param string $exceptions ?
1201 * @return object
1202 * @todo Finish documenting this function
1204 function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='',
1205 $fields='u.*') {
1206 global $CFG;
1207 if (!empty($exceptions)) {
1208 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1209 } else {
1210 $except = '';
1212 // in postgres, you can't have things in sort that aren't in the select, so...
1213 $extrafield = str_replace('ASC','',$sort);
1214 $extrafield = str_replace('DESC','',$extrafield);
1215 $extrafield = trim($extrafield);
1216 if (!empty($extrafield)) {
1217 $extrafield = ','.$extrafield;
1219 return get_records_sql("SELECT DISTINCT $fields $extrafield
1220 FROM {$CFG->prefix}user u,
1221 {$CFG->prefix}groups_members m
1222 WHERE m.groupid = '$groupid'
1223 AND m.userid = u.id $except
1224 ORDER BY $sort");
1228 * Returns the current group mode for a given course or activity module
1230 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
1232 function groupmode($course, $cm=null) {
1234 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
1235 return $cm->groupmode;
1237 return $course->groupmode;
1242 * Sets the current group in the session variable
1243 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
1244 * Sets currentgroup[$courseid] in the session variable appropriately.
1245 * Does not do any permission checking.
1246 * @uses $SESSION
1247 * @param int $courseid The course being examined - relates to id field in
1248 * 'course' table.
1249 * @param int $groupid The group being examined.
1250 * @return int Current group id which was set by this function
1252 function set_current_group($courseid, $groupid) {
1253 global $SESSION;
1254 return $SESSION->currentgroup[$courseid] = $groupid;
1259 * Gets the current group - either from the session variable or from the database.
1261 * @uses $USER
1262 * @uses $SESSION
1263 * @param int $courseid The course being examined - relates to id field in
1264 * 'course' table.
1265 * @param bool $full If true, the return value is a full record object.
1266 * If false, just the id of the record.
1268 function get_current_group($courseid, $full = false) {
1269 global $SESSION;
1271 if (isset($SESSION->currentgroup[$courseid])) {
1272 if ($full) {
1273 return groups_get_group($SESSION->currentgroup[$courseid]);
1274 } else {
1275 return $SESSION->currentgroup[$courseid];
1279 $mygroupid = mygroupid($courseid);
1280 if (is_array($mygroupid)) {
1281 $mygroupid = array_shift($mygroupid);
1282 set_current_group($courseid, $mygroupid);
1283 if ($full) {
1284 return groups_get_group($mygroupid);
1285 } else {
1286 return $mygroupid;
1290 if ($full) {
1291 return false;
1292 } else {
1293 return 0;
1299 * A combination function to make it easier for modules
1300 * to set up groups.
1302 * It will use a given "groupid" parameter and try to use
1303 * that to reset the current group for the user.
1305 * @uses VISIBLEGROUPS
1306 * @param course $course A {@link $COURSE} object
1307 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1308 * @param int $groupid Will try to use this optional parameter to
1309 * reset the current group for the user
1310 * @return int|false Returns the current group id or false if error.
1312 function get_and_set_current_group($course, $groupmode, $groupid=-1) {
1314 // Sets to the specified group, provided the current user has view permission
1315 if (!$groupmode) { // Groups don't even apply
1316 return false;
1319 $currentgroupid = get_current_group($course->id);
1321 if ($groupid < 0) { // No change was specified
1322 return $currentgroupid;
1325 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1326 if ($groupid and $group = get_record('groups', 'id', $groupid)) { // Try to change the current group to this groupid
1327 if ($group->courseid == $course->id) {
1328 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1329 $currentgroupid = set_current_group($course->id, $groupid);
1331 } elseif ($groupmode == VISIBLEGROUPS) {
1332 // All groups are visible
1333 //if (groups_is_member($group->id)){
1334 $currentgroupid = set_current_group($course->id, $groupid); //set this since he might post
1335 /*)}else {
1336 $currentgroupid = $group->id;*/
1337 } elseif ($groupmode == SEPARATEGROUPS) { // student in separate groups switching
1338 if (groups_is_member($groupid)) { //check if is a member
1339 $currentgroupid = set_current_group($course->id, $groupid); //might need to set_current_group?
1341 else {
1342 notify('You do not belong to this group! ('.$groupid.')', 'error');
1346 } else { // When groupid = 0 it means show ALL groups
1347 // this is changed, non editting teacher needs access to group 0 as well,
1348 // for viewing work in visible groups (need to set current group for multiple pages)
1349 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1350 $currentgroupid = set_current_group($course->id, 0);
1352 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1353 $currentgroupid = set_current_group($course->id, 0);
1357 return $currentgroupid;
1362 * A big combination function to make it easier for modules
1363 * to set up groups.
1365 * Terminates if the current user shouldn't be looking at this group
1366 * Otherwise returns the current group if there is one
1367 * Otherwise returns false if groups aren't relevant
1369 * @uses SEPARATEGROUPS
1370 * @uses VISIBLEGROUPS
1371 * @param course $course A {@link $COURSE} object
1372 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1373 * @param string $urlroot ?
1374 * @return int|false
1376 function setup_and_print_groups($course, $groupmode, $urlroot) {
1378 global $USER, $SESSION; //needs his id, need to hack his groups in session
1380 $changegroup = optional_param('group', -1, PARAM_INT);
1382 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
1383 if ($currentgroup === false) {
1384 return false;
1387 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1389 if ($groupmode == SEPARATEGROUPS and !$currentgroup and !has_capability('moodle/site:accessallgroups', $context)) {
1390 //we are in separate groups and the current group is group 0, as last set.
1391 //this can mean that either, this guy has no group
1392 //or, this guy just came from a visible all forum, and he left when he set his current group to 0 (show all)
1394 if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1395 //for the second situation, we need to perform the trick and get him a group.
1396 $first = reset($usergroups);
1397 $currentgroup = get_and_set_current_group($course, $groupmode, $first->id);
1399 } else {
1400 //else he has no group in this course
1401 print_heading(get_string('notingroup'));
1402 print_footer($course);
1403 exit;
1407 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/site:accessallgroups', $context))) {
1409 if ($groups = groups_get_all_groups($course->id)) {
1411 echo '<div class="groupselector">';
1412 print_group_menu($groups, $groupmode, $currentgroup, $urlroot, 1);
1413 echo '</div>';
1416 } else if ($groupmode == SEPARATEGROUPS and has_capability('moodle/course:view', $context)) {
1417 //get all the groups this guy is in in this course
1418 if ($usergroups = groups_get_all_groups($course->id, $USER->id)){
1419 echo '<div class="groupselector">';
1420 //print them in the menu
1421 print_group_menu($usergroups, $groupmode, $currentgroup, $urlroot, 0);
1422 echo '</div>';
1426 return $currentgroup;
1430 * Prints an appropriate group selection menu
1432 * @uses VISIBLEGROUPS
1433 * @param array $groups ?
1434 * @param int $groupmode ?
1435 * @param string $currentgroup ?
1436 * @param string $urlroot ?
1437 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
1438 * @todo Finish documenting this function
1440 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
1442 $output = '';
1443 $groupsmenu = array();
1445 /// Add an "All groups" to the start of the menu
1446 if ($showall){
1447 $groupsmenu[0] = get_string('allparticipants');
1449 foreach ($groups as $key => $group) {
1450 $groupsmenu[$key] = format_string($group->name);
1453 if ($groupmode == VISIBLEGROUPS) {
1454 $grouplabel = get_string('groupsvisible');
1455 } else {
1456 $grouplabel = get_string('groupsseparate');
1459 if (count($groupsmenu) == 1) {
1460 $groupname = reset($groupsmenu);
1461 $output .= $grouplabel.': '.$groupname;
1462 } else {
1463 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
1466 if ($return) {
1467 return $output;
1468 } else {
1469 echo $output;