3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
10 // Copyright (C) 1999 onwards Martin Dougiamas, Moodle http://moodle.com//
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. //
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: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
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
34 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
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) {
51 if (!empty($CFG->disableglobalshack
)) {
52 error( 'The require_variable() function is deprecated.' );
55 error('A required parameter was missing');
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) {
69 if (!empty($CFG->disableglobalshack
)) {
70 error( "The optional_variable() function is deprecated ($var, $default)." );
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
87 function nvl(&$var, $default='') {
90 if (!empty($CFG->disableglobalshack
)) {
91 error( "The nvl() function is deprecated ($var, $default)." );
93 return isset($var) ?
$var : $default;
97 * Determines if a user an admin
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
105 function isadmin($userid=0) {
108 if (empty($CFG->rolesactive
)) { // Then the user is likely to be upgrading NOW
110 if (empty($USER->id
)) {
113 if (!empty($USER->admin
)) {
119 return record_exists('user_admins', 'userid', $userid);
122 $context = get_context_instance(CONTEXT_SYSTEM
);
124 return has_capability('moodle/legacy:admin', $context, $userid, false);
128 * Determines if a user is a teacher (or better)
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
137 function isteacher($courseid=0, $userid=0, $obsolete_includeadmin=true) {
138 /// Is the user able to access this course as a teacher?
141 if (empty($CFG->rolesactive
)) { // Teachers are locked out during an upgrade to 1.7
146 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
148 $context = get_context_instance(CONTEXT_SYSTEM
);
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
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
164 function isteacherinanycourse($userid=0, $includeadmin=true) {
167 if (empty($CFG->rolesactive
)) { // Teachers are locked out during an upgrade to 1.7
172 if (empty($USER->id
)) {
178 if (!record_exists('role_assignments', 'userid', $userid)) { // Has no roles anywhere
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)) {
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)) {
200 /// Include admins if required
202 $context = get_context_instance(CONTEXT_SYSTEM
);
203 if (has_capability('moodle/legacy:admin', $context, $userid, 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.
218 function isteacheredit($courseid, $userid=0, $obsolete_ignorestudentview=false) {
221 if (empty($CFG->rolesactive
)) {
225 if (empty($courseid)) {
226 $context = get_context_instance(CONTEXT_SYSTEM
);
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.
241 function iscreator ($userid=0) {
244 if (empty($CFG->rolesactive
)) {
248 $context = get_context_instance(CONTEXT_SYSTEM
);
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.
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.
266 function isstudent($courseid=0, $userid=0) {
269 if (empty($CFG->rolesactive
)) {
273 if ($courseid == 0) {
274 $context = get_context_instance(CONTEXT_SYSTEM
);
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.
288 function isguest($userid=0) {
291 if (empty($CFG->rolesactive
)) {
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.
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 ?
314 function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
318 if (!$user = get_record('user', 'id', $userid)) { // Check user
322 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
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)) {
332 $res = role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol);
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.
344 function unenrol_student($userid, $courseid=0) {
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
);
359 } else if (!$context = get_context_instance(CONTEXT_COURSE
, $courseid)) {
362 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
365 foreach($roles as $role) {
366 $status = role_unassign($role->id
, $userid, 0, $context->id
) and $status;
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;
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
392 function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
395 if (!$user = get_record('user', 'id', $userid)) { // Check user
399 $capability = $editall ?
'moodle/legacy:editingteacher' : 'moodle/legacy:teacher';
401 if (!$roles = get_roles_with_capability($capability, CAP_ALLOW
)) {
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)) {
411 $res = role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol);
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.
424 function remove_teacher($userid, $courseid=0) {
427 $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW
);
430 $roles +
= get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW
);
432 $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW
);
443 if (!$context = get_context_instance(CONTEXT_COURSE
, $courseid)) {
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)) {
464 delete_records('forum_subscriptions', 'userid', $userid);
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)) {
478 * Add an admin to a site
481 * @param int $userid The id of the user that is being tested against.
483 * @TODO: remove from cvs
485 function add_admin($userid) {
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
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) {
516 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
518 // Pass $view=true to filter hidden caps if the user cannot see them
519 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
520 '', '', '', '', false, true)) {
521 $users = sort_by_roleassignment_authority($users, $context);
522 return array_shift($users);
529 * Searches logs to find all enrolments since a certain date
531 * used to print recent activity
534 * @param int $courseid The course in question.
535 * @return object|false {@link $USER} records or false if error.
536 * @todo Finish documenting this function
538 function get_recent_enrolments($courseid, $timestart) {
542 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
544 return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, l.time
545 FROM {$CFG->prefix}user u,
546 {$CFG->prefix}role_assignments ra,
548 WHERE l.time > '$timestart'
549 AND l.course = '$courseid'
550 AND l.module = 'course'
551 AND l.action = 'enrol'
552 AND ".sql_cast_char2int('l.info')." = u.id
554 AND ra.contextid ".get_related_contexts_string($context)."
555 ORDER BY l.time ASC");
559 * Returns array of userinfo of all students in this course
560 * or on this site if courseid is id of site
564 * @param int $courseid The course in question.
565 * @param string $sort ?
566 * @param string $dir ?
568 * @param int $recordsperpage ?
569 * @param string $firstinitial ?
570 * @param string $lastinitial ?
572 * @param string $search ?
573 * @param string $fields A comma separated list of fields to be returned from the chosen table.
574 * @param string $exceptions ?
576 * @todo Finish documenting this function
578 function get_course_students($courseid, $sort='ul.timeaccess', $dir='', $page='', $recordsperpage='',
579 $firstinitial='', $lastinitial='', $group=NULL, $search='', $fields='', $exceptions='') {
583 // make sure it works on the site course
584 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
586 /// For the site course, old way was to check if $CFG->allusersaresitestudents was set to true.
587 /// The closest comparible method using roles is if the $CFG->defaultuserroleid is set to the legacy
588 /// student role. This function should be replaced where it is used with something more meaningful.
589 if (($courseid == SITEID
) && !empty($CFG->defaultuserroleid
) && empty($CFG->nodefaultuserrolelists
)) {
590 if ($roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
, $context)) {
592 foreach ($roles as $role) {
593 if ($role->id
== $CFG->defaultuserroleid
) {
599 if (empty($fields)) {
602 // return users with confirmed, undeleted accounts who are not site teachers
603 // the following is a mess because of different conventions in the different user functions
604 $sort = str_replace('s.timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
605 $sort = str_replace('timeaccess', 'lastaccess', $sort); // site users can't be sorted by timeaccess
606 $sort = str_replace('u.', '', $sort); // the get_user function doesn't use the u. prefix to fields
607 $sort = str_replace('ul.', '', $sort); // the get_user function doesn't use the ul. prefix to fields
608 // the following is a mess because of different conventions in the different user functions. MDL-17200
609 $fields = str_replace('u.', '', $fields);
610 $fields = str_replace('ul.', '', $fields);
611 $fields = str_replace('timeaccess', 'lastaccess', $fields);
613 $sort = $sort .' '. $dir;
615 // Now we have to make sure site teachers are excluded
617 if ($teachers = get_course_teachers(SITEID
)) {
618 foreach ($teachers as $teacher) {
619 $exceptions .= ','. $teacher->userid
;
621 $exceptions = ltrim($exceptions, ',');
625 return get_users(true, $search, true, $exceptions, $sort, $firstinitial, $lastinitial,
626 $page, $recordsperpage, $fields);
632 $fullname = sql_fullname('u.firstname','u.lastname');
636 $select = "c.contextlevel=".CONTEXT_COURSE
." AND "; // Must be on a course
637 if ($courseid != SITEID
) {
638 // If not site, require specific course
639 $select.= "c.instanceid=$courseid AND ";
641 $select.="rc.capability='moodle/legacy:student' AND rc.permission=".CAP_ALLOW
." AND ";
643 $select .= ' u.deleted = \'0\' ';
646 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
647 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
648 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
649 'u.emailstop, u.lang, u.timezone, ul.timeaccess as lastaccess';
653 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
657 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
661 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
664 if ($group === 0) { /// Need something here to get all students not in a group
667 } else if ($group !== NULL) {
668 $groupmembers = "INNER JOIN {$CFG->prefix}groups_members gm on u.id=gm.userid";
669 $select .= ' AND gm.groupid = \''. $group .'\'';
672 if (!empty($exceptions)) {
673 $select .= ' AND u.id NOT IN ('. $exceptions .')';
677 $sort = ' ORDER BY '. $sort .' ';
680 $students = get_records_sql("SELECT $fields
681 FROM {$CFG->prefix}user u INNER JOIN
682 {$CFG->prefix}role_assignments ra on u.id=ra.userid INNER JOIN
683 {$CFG->prefix}role_capabilities rc ON ra.roleid=rc.roleid INNER JOIN
684 {$CFG->prefix}context c ON c.id=ra.contextid LEFT OUTER JOIN
685 {$CFG->prefix}user_lastaccess ul on ul.userid=ra.userid AND ul.courseid = $courseid
687 WHERE $select $search $sort $dir", $page, $recordsperpage);
693 * Counts the students in a given course (or site), or a subset of them
695 * @param object $course The course in question as a course object.
696 * @param string $search ?
697 * @param string $firstinitial ?
698 * @param string $lastinitial ?
700 * @param string $exceptions ?
702 * @todo Finish documenting this function
704 function count_course_students($course, $search='', $firstinitial='', $lastinitial='', $group=NULL, $exceptions='') {
706 if ($students = get_course_students($course->id
, '', '', 0, 999999, $firstinitial, $lastinitial, $group, $search, '', $exceptions)) {
707 return count($students);
713 * Returns list of all teachers in this course
715 * If $courseid matches the site id then this function
716 * returns a list of all teachers for the site.
719 * @param int $courseid The course in question.
720 * @param string $sort ?
721 * @param string $exceptions ?
723 * @todo Finish documenting this function
725 function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
729 $sort = 'ul.timeaccess DESC';
731 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
733 /// For the site course, if the $CFG->defaultuserroleid is set to the legacy teacher role, then all
734 /// users are teachers. This function should be replaced where it is used with something more
736 if (($courseid == SITEID
) && !empty($CFG->defaultuserroleid
) && empty($CFG->nodefaultuserrolelists
)) {
737 if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW
, $context)) {
739 foreach ($roles as $role) {
740 if ($role->id
== $CFG->defaultuserroleid
) {
746 if (empty($fields)) {
749 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', '', '', $fields);
754 $users = get_users_by_capability($context, 'moodle/course:update',
755 'u.*, ul.timeaccess as lastaccess',
756 $sort, '','','',$exceptions, false);
757 return sort_by_roleassignment_authority($users, $context);
759 /// some fields will be missing, like authority, editall
761 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest,
762 u.email, u.city, u.country, u.lastlogin, u.picture, u.lang, u.timezone,
763 u.emailstop, t.authority,t.role,t.editall,t.timeaccess as lastaccess
764 FROM {$CFG->prefix}user u,
765 {$CFG->prefix}user_teachers t
766 WHERE t.course = '$courseid' AND t.userid = u.id
767 AND u.deleted = '0' AND u.confirmed = '1' $exceptions $sort");
772 * Returns all the users of a course: students and teachers
774 * @param int $courseid The course in question.
775 * @param string $sort ?
776 * @param string $exceptions A comma separated list of user->id to be skiped in the result returned by the function
777 * @param string $fields A comma separated list of fields to be returned from the chosen table.
778 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
779 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
780 * @todo Finish documenting this function
782 function get_course_users($courseid, $sort='ul.timeaccess DESC', $exceptions='', $fields='u.*, ul.timeaccess as lastaccess', $limitfrom='', $limitnum='') {
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)) {
793 foreach ($roles as $role) {
794 if ($role->id
== $CFG->defaultuserroleid
) {
800 if (empty($fields)) {
803 // the following is a mess because of different conventions in the different user functions. MDL-17200
804 $fields = str_replace('u.', '', $fields);
805 $fields = str_replace('ul.', '', $fields);
806 $fields = str_replace('timeaccess', 'lastaccess', $fields);
807 return get_users(true, '', true, $exceptions, 'lastname ASC', '', '', $limitfrom, $limitnum, $fields);
811 return get_users_by_capability($context, 'moodle/course:view', $fields, $sort, $limitfrom, $limitnum,'',$exceptions, false);
816 * Returns an array of user objects
819 * @param int $groupid The group(s) in question.
820 * @param string $sort How to sort the results
821 * @return object (changed to groupids)
823 function get_group_students($groupids, $sort='ul.timeaccess DESC') {
825 if (is_array($groupids)){
827 // all groups must be from one course anyway...
828 $group = groups_get_group(array_shift($groups));
830 $group = groups_get_group($groupids);
836 $context = get_context_instance(CONTEXT_COURSE
, $group->courseid
);
837 return get_users_by_capability($context, 'moodle/legacy:student', 'u.*, ul.timeaccess as lastaccess', $sort, '','',$groupids, '', false);
841 * Returns list of all the teachers who can access a group
844 * @param int $courseid The course in question.
845 * @param int $groupid The group in question.
848 function get_group_teachers($courseid, $groupid) {
849 /// Returns a list of all the teachers who can access a group
850 if ($teachers = get_course_teachers($courseid)) {
851 foreach ($teachers as $key => $teacher) {
852 if ($teacher->editall
) { // These can access anything
855 if (($teacher->authority
> 0) and groups_is_member($groupid, $teacher->id
)) { // Specific group teachers
858 unset($teachers[$key]);
866 ########### FROM weblib.php ##########################################################################
869 * Creates a nicely formatted table and returns it.
871 * @param array $table is an object with several properties.
872 * <ul<li>$table->head - An array of heading names.
873 * <li>$table->align - An array of column alignments
874 * <li>$table->size - An array of column sizes
875 * <li>$table->wrap - An array of "nowrap"s or nothing
876 * <li>$table->data[] - An array of arrays containing the data.
877 * <li>$table->class - A css class name
878 * <li>$table->fontsize - Is the size of all the text
879 * <li>$table->tablealign - Align the whole table
880 * <li>$table->width - A percentage of the page
881 * <li>$table->cellpadding - Padding on each cell
882 * <li>$table->cellspacing - Spacing between cells
885 * @todo Finish documenting this function
887 function make_table($table) {
888 return print_table($table, true);
893 * Print a message in a standard themed box.
894 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
895 * parameters remain. If possible, $align, $width and $color should not be defined at all.
896 * Preferably just use print_box() in weblib.php
898 * @param string $align, alignment of the box, not the text (default center, left, right).
899 * @param string $width, width of the box, including units %, for example '100%'.
900 * @param string $color, background colour of the box, for example '#eee'.
901 * @param int $padding, padding in pixels, specified without units.
902 * @param string $class, space-separated class names.
903 * @param string $id, space-separated id names.
904 * @param boolean $return, return as string or just print it
906 function print_simple_box($message, $align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
908 $output .= print_simple_box_start($align, $width, $color, $padding, $class, $id, true);
909 $output .= stripslashes_safe($message);
910 $output .= print_simple_box_end(true);
922 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
923 * parameters remain. If possible, $align, $width and $color should not be defined at all.
924 * Even better, please use print_box_start() in weblib.php
926 * @param string $align, alignment of the box, not the text (default center, left, right). DEPRECATED
927 * @param string $width, width of the box, including % units, for example '100%'. DEPRECATED
928 * @param string $color, background colour of the box, for example '#eee'. DEPRECATED
929 * @param int $padding, padding in pixels, specified without units. OBSOLETE
930 * @param string $class, space-separated class names.
931 * @param string $id, space-separated id names.
932 * @param boolean $return, return as string or just print it
934 function print_simple_box_start($align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
938 $divclasses = 'box '.$class.' '.$class.'content';
942 $divclasses .= ' boxalign'.$align; // Implement alignment using a class
944 if ($width) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
945 if (substr($width, -1, 1) == '%') { // Width is a % value
946 $width = (int) substr($width, 0, -1); // Extract just the number
948 $divclasses .= ' boxwidthnarrow'; // Approx 30% depending on theme
949 } else if ($width > 60) {
950 $divclasses .= ' boxwidthwide'; // Approx 80% depending on theme
952 $divclasses .= ' boxwidthnormal'; // Approx 50% depending on theme
955 $divstyles .= ' width:'.$width.';'; // Last resort
958 if ($color) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
959 $divstyles .= ' background:'.$color.';';
962 $divstyles = ' style="'.$divstyles.'"';
966 $id = ' id="'.$id.'"';
969 $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
980 * Print the end portion of a standard themed box.
981 * Preferably just use print_box_end() in weblib.php
983 function print_simple_box_end($return=false) {
993 * deprecated - use clean_param($string, PARAM_FILE); instead
994 * Check for bad characters ?
996 * @param string $string ?
997 * @param int $allowdots ?
998 * @todo Finish documenting this function - more detail needed in description as well as details on arguments
1000 function detect_munged_arguments($string, $allowdots=1) {
1001 if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references
1004 if (ereg('[\|\`]', $string)) { // check for other bad characters
1007 if (empty($string) or $string == '/') {
1014 /** Deprecated function - returns the code of the current charset - originally depended on the selected language pack.
1016 * @param $ignorecache not used anymore
1017 * @return string always returns 'UTF-8'
1019 function current_charset($ignorecache = false) {
1024 /////////////////////////////////////////////////////////////
1025 /// Old functions not used anymore - candidates for removal
1026 /////////////////////////////////////////////////////////////
1029 * Load a template from file - this function dates back to Moodle 1 :-) not used anymore
1031 * Returns a (big) string containing the contents of a template file with all
1032 * the variables interpolated. all the variables must be in the $var[] array or
1033 * object (whatever you decide to use).
1035 * <b>WARNING: do not use this on big files!!</b>
1037 * @param string $filename Location on the server's filesystem where template can be found.
1038 * @param mixed $var Passed in by reference. An array or object which will be loaded with data from the template file.
1041 function read_template($filename, &$var) {
1043 $temp = str_replace("\\", "\\\\", implode(file($filename), ''));
1044 $temp = str_replace('"', '\"', $temp);
1045 eval("\$template = \"$temp\";");
1051 * deprecated - relies on register globals; use new formslib instead
1053 * Set a variable's value depending on whether or not it already has a value.
1055 * If variable is set, set it to the set_value otherwise set it to the
1056 * unset_value. used to handle checkboxes when you are expecting them from
1059 * @param mixed $var Passed in by reference. The variable to check.
1060 * @param mixed $set_value The value to set $var to if $var already has a value.
1061 * @param mixed $unset_value The value to set $var to if $var does not already have a value.
1063 function checked(&$var, $set_value = 1, $unset_value = 0) {
1066 $var = $unset_value;
1073 * deprecated - use new formslib instead
1075 * Prints the word "checked" if a variable is true, otherwise prints nothing,
1076 * used for printing the word "checked" in a checkbox form element.
1078 * @param boolean $var Variable to be checked for true value
1079 * @param string $true_value Value to be printed if $var is true
1080 * @param string $false_value Value to be printed if $var is false
1082 function frmchecked(&$var, $true_value = 'checked', $false_value = '') {
1092 * Legacy function, provided for backward compatability.
1093 * This method now simply calls {@link use_html_editor()}
1095 * @deprecated Use {@link use_html_editor()} instead.
1096 * @param string $name Form element to replace with HTMl editor by name
1097 * @todo Finish documenting this function
1099 function print_richedit_javascript($form, $name, $source='no') {
1100 use_html_editor($name);
1103 /** various deprecated groups function **/
1107 * Returns the table in which group members are stored, with a prefix 'gm'.
1108 * @return SQL string.
1110 function groups_members_from_sql() {
1112 return " {$CFG->prefix}groups_members gm ";
1116 * Returns a join testing user.id against member's user ID.
1117 * Relies on 'user' table being included as 'user u'.
1118 * Used in Quiz module reports.
1119 * @param group ID, optional to include a test for this in the SQL.
1120 * @return SQL string.
1122 function groups_members_join_sql($groupid=false) {
1123 $sql = ' JOIN '.groups_members_from_sql().' ON u.id = gm.userid ';
1125 $sql = "AND gm.groupid = '$groupid' ";
1131 * Returns SQL for a WHERE clause testing the group ID.
1132 * Optionally test the member's ID against another table's user ID column.
1134 * @param userid_sql Optional user ID column selector, example "mdl_user.id", or false.
1135 * @return SQL string.
1137 function groups_members_where_sql($groupid, $userid_sql=false) {
1138 $sql = " gm.groupid = '$groupid' ";
1140 $sql .= "AND $userid_sql = gm.userid ";
1147 * Returns an array of group objects that the user is a member of
1148 * in the given course. If userid isn't specified, then return a
1149 * list of all groups in the course.
1152 * @param int $courseid The id of the course in question.
1153 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
1156 function get_groups($courseid, $userid=0) {
1157 return groups_get_all_groups($courseid, $userid);
1161 * Returns the user's groups in a particular course
1162 * note: this function originally returned only one group
1165 * @param int $courseid The course in question.
1166 * @param int $userid The id of the user as found in the 'user' table.
1167 * @param int $groupid The id of the group the user is in.
1168 * @return aray of groups
1170 function user_group($courseid, $userid) {
1171 return groups_get_all_groups($courseid, $userid);
1176 * Determines if the user is a member of the given group.
1178 * @param int $groupid The group to check for membership.
1179 * @param int $userid The user to check against the group.
1180 * @return boolean True if the user is a member, false otherwise.
1182 function ismember($groupid, $userid = null) {
1183 return groups_is_member($groupid, $userid);
1187 * Get the IDs for the user's groups in the given course.
1190 * @param int $courseid The course being examined - the 'course' table id field.
1191 * @return array An _array_ of groupids.
1192 * (Was return $groupids[0] - consequences!)
1194 function mygroupid($courseid) {
1196 if ($groups = groups_get_all_groups($courseid, $USER->id
)) {
1197 return array_keys($groups);
1204 * Add a user to a group, return true upon success or if user already a group
1207 * @param int $groupid The group id to add user to
1208 * @param int $userid The user id to add to the group
1211 function add_user_to_group($groupid, $userid) {
1213 require_once($CFG->dirroot
.'/group/lib.php');
1215 return groups_add_member($groupid, $userid);
1220 * Returns an array of user objects
1223 * @param int $groupid The group in question.
1224 * @param string $sort ?
1225 * @param string $exceptions A comma separated list of user->id to be skiped in the result returned by the function
1226 * @param string $fields A comma separated list of fields to be returned from the chosen table.
1227 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1228 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1229 * @return array array of user objects
1230 * @todo Finish documenting this function
1232 function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='', $fields='u.*', $limitfrom='', $limitnum='') {
1234 if (!empty($exceptions)) {
1235 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1239 // in postgres, you can't have things in sort that aren't in the select, so...
1240 $extrafield = str_replace('ASC','',$sort);
1241 $extrafield = str_replace('DESC','',$extrafield);
1242 $extrafield = trim($extrafield);
1243 if (!empty($extrafield)) {
1244 $extrafield = ','.$extrafield;
1246 return get_records_sql("SELECT DISTINCT $fields $extrafield
1247 FROM {$CFG->prefix}user u,
1248 {$CFG->prefix}groups_members m
1249 WHERE m.groupid = '$groupid'
1250 AND m.userid = u.id $except
1252 $limitfrom, $limitnum);
1256 * Returns the current group mode for a given course or activity module
1258 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
1260 function groupmode($course, $cm=null) {
1262 if (isset($cm->groupmode
) && empty($course->groupmodeforce
)) {
1263 return $cm->groupmode
;
1265 return $course->groupmode
;
1270 * Sets the current group in the session variable
1271 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
1272 * Sets currentgroup[$courseid] in the session variable appropriately.
1273 * Does not do any permission checking.
1275 * @param int $courseid The course being examined - relates to id field in
1277 * @param int $groupid The group being examined.
1278 * @return int Current group id which was set by this function
1280 function set_current_group($courseid, $groupid) {
1282 return $SESSION->currentgroup
[$courseid] = $groupid;
1287 * Gets the current group - either from the session variable or from the database.
1291 * @param int $courseid The course being examined - relates to id field in
1293 * @param bool $full If true, the return value is a full record object.
1294 * If false, just the id of the record.
1296 function get_current_group($courseid, $full = false) {
1299 if (isset($SESSION->currentgroup
[$courseid])) {
1301 return groups_get_group($SESSION->currentgroup
[$courseid]);
1303 return $SESSION->currentgroup
[$courseid];
1307 $mygroupid = mygroupid($courseid);
1308 if (is_array($mygroupid)) {
1309 $mygroupid = array_shift($mygroupid);
1310 set_current_group($courseid, $mygroupid);
1312 return groups_get_group($mygroupid);
1327 * A combination function to make it easier for modules
1330 * It will use a given "groupid" parameter and try to use
1331 * that to reset the current group for the user.
1333 * @uses VISIBLEGROUPS
1334 * @param course $course A {@link $COURSE} object
1335 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1336 * @param int $groupid Will try to use this optional parameter to
1337 * reset the current group for the user
1338 * @return int|false Returns the current group id or false if error.
1340 function get_and_set_current_group($course, $groupmode, $groupid=-1) {
1342 // Sets to the specified group, provided the current user has view permission
1343 if (!$groupmode) { // Groups don't even apply
1347 $currentgroupid = get_current_group($course->id
);
1349 if ($groupid < 0) { // No change was specified
1350 return $currentgroupid;
1353 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1354 if ($groupid and $group = get_record('groups', 'id', $groupid)) { // Try to change the current group to this groupid
1355 if ($group->courseid
== $course->id
) {
1356 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1357 $currentgroupid = set_current_group($course->id
, $groupid);
1359 } elseif ($groupmode == VISIBLEGROUPS
) {
1360 // All groups are visible
1361 //if (groups_is_member($group->id)){
1362 $currentgroupid = set_current_group($course->id
, $groupid); //set this since he might post
1364 $currentgroupid = $group->id;*/
1365 } elseif ($groupmode == SEPARATEGROUPS
) { // student in separate groups switching
1366 if (groups_is_member($groupid)) { //check if is a member
1367 $currentgroupid = set_current_group($course->id
, $groupid); //might need to set_current_group?
1370 notify('You do not belong to this group! ('.$groupid.')', 'error');
1374 } else { // When groupid = 0 it means show ALL groups
1375 // this is changed, non editting teacher needs access to group 0 as well,
1376 // for viewing work in visible groups (need to set current group for multiple pages)
1377 if (has_capability('moodle/site:accessallgroups', $context)) { // Sets current default group
1378 $currentgroupid = set_current_group($course->id
, 0);
1380 } else if ($groupmode == VISIBLEGROUPS
) { // All groups are visible
1381 $currentgroupid = set_current_group($course->id
, 0);
1385 return $currentgroupid;
1390 * A big combination function to make it easier for modules
1393 * Terminates if the current user shouldn't be looking at this group
1394 * Otherwise returns the current group if there is one
1395 * Otherwise returns false if groups aren't relevant
1397 * @uses SEPARATEGROUPS
1398 * @uses VISIBLEGROUPS
1399 * @param course $course A {@link $COURSE} object
1400 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
1401 * @param string $urlroot ?
1404 function setup_and_print_groups($course, $groupmode, $urlroot) {
1406 global $USER, $SESSION; //needs his id, need to hack his groups in session
1408 $changegroup = optional_param('group', -1, PARAM_INT
);
1410 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
1411 if ($currentgroup === false) {
1415 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1417 if ($groupmode == SEPARATEGROUPS
and !$currentgroup and !has_capability('moodle/site:accessallgroups', $context)) {
1418 //we are in separate groups and the current group is group 0, as last set.
1419 //this can mean that either, this guy has no group
1420 //or, this guy just came from a visible all forum, and he left when he set his current group to 0 (show all)
1422 if ($usergroups = groups_get_all_groups($course->id
, $USER->id
)){
1423 //for the second situation, we need to perform the trick and get him a group.
1424 $first = reset($usergroups);
1425 $currentgroup = get_and_set_current_group($course, $groupmode, $first->id
);
1428 //else he has no group in this course
1429 print_heading(get_string('notingroup'));
1430 print_footer($course);
1435 if ($groupmode == VISIBLEGROUPS
or ($groupmode and has_capability('moodle/site:accessallgroups', $context))) {
1437 if ($groups = groups_get_all_groups($course->id
)) {
1439 echo '<div class="groupselector">';
1440 print_group_menu($groups, $groupmode, $currentgroup, $urlroot, 1);
1444 } else if ($groupmode == SEPARATEGROUPS
and has_capability('moodle/course:view', $context)) {
1445 //get all the groups this guy is in in this course
1446 if ($usergroups = groups_get_all_groups($course->id
, $USER->id
)){
1447 echo '<div class="groupselector">';
1448 //print them in the menu
1449 print_group_menu($usergroups, $groupmode, $currentgroup, $urlroot, 0);
1454 return $currentgroup;
1458 * Prints an appropriate group selection menu
1460 * @uses VISIBLEGROUPS
1461 * @param array $groups ?
1462 * @param int $groupmode ?
1463 * @param string $currentgroup ?
1464 * @param string $urlroot ?
1465 * @param boolean $showall: if set to 0, it is a student in separate groups, do not display all participants
1466 * @todo Finish documenting this function
1468 function print_group_menu($groups, $groupmode, $currentgroup, $urlroot, $showall=1, $return=false) {
1471 $groupsmenu = array();
1473 /// Add an "All groups" to the start of the menu
1475 $groupsmenu[0] = get_string('allparticipants');
1477 foreach ($groups as $key => $group) {
1478 $groupsmenu[$key] = format_string($group->name
);
1481 if ($groupmode == VISIBLEGROUPS
) {
1482 $grouplabel = get_string('groupsvisible');
1484 $grouplabel = get_string('groupsseparate');
1487 if (count($groupsmenu) == 1) {
1488 $groupname = reset($groupsmenu);
1489 $output .= $grouplabel.': '.$groupname;
1491 $output .= popup_form($urlroot.'&group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
1503 * All users that we have not seen for a really long time (ie dead accounts)
1504 * TODO: Delete this for Moodle 2.0
1507 * @deprecated The query is executed directly within admin/cron.php (MDL-11571)
1508 * @param string $cutofftime ?
1509 * @return object {@link $USER} records
1511 function get_users_longtimenosee($cutofftime) {
1513 return get_records_sql("SELECT id, userid, courseid
1514 FROM {$CFG->prefix}user_lastaccess
1515 WHERE courseid != ".SITEID
."
1516 AND timeaccess < $cutofftime ");
1520 * Full list of users that have not yet confirmed their accounts.
1521 * TODO: Delete this for Moodle 2.0
1524 * @deprecated The query is executed directly within admin/cron.php (MDL-11487)
1525 * @param string $cutofftime ?
1526 * @return object {@link $USER} records
1528 function get_users_unconfirmed($cutofftime=2000000000) {
1530 return get_records_sql("SELECT *
1531 FROM {$CFG->prefix}user
1534 AND firstaccess < $cutofftime");
1538 * Full list of bogus accounts that are probably not ever going to be used
1539 * TODO: Delete this for Moodle 2.0
1542 * @deprecated The query is executed directly within admin/cron.php (MDL-11487)
1543 * @param string $cutofftime ?
1544 * @return object {@link $USER} records
1546 function get_users_not_fully_set_up($cutofftime=2000000000) {
1548 return get_records_sql("SELECT *
1549 FROM {$CFG->prefix}user
1552 AND lastaccess < $cutofftime
1554 AND (lastname = '' OR firstname = '' OR email = '')");
1558 * Returns SQL to be used as a subselect to find the primary role of users.
1559 * Geoff Cant <geoff@catalyst.net.nz> (the author) is very keen for this to
1560 * be implemented as a view in future versions.
1562 * eg if this function returns a string called $primaryroles, then you could:
1563 * $sql = 'SELECT COUNT(DISTINCT prs.userid) FROM ('.$primary_roles.') prs
1564 * WHERE prs.primary_roleid='.$role->id.' AND prs.courseid='.$course->id.
1565 * ' AND prs.contextlevel = '.CONTEXT_COURSE;
1567 * @return string the piece of SQL code to be used in your FROM( ) statement.
1569 function sql_primary_role_subselect() {
1571 return 'SELECT ra.userid,
1572 ra.roleid AS primary_roleid,
1578 c.instanceid AS courseid,
1580 FROM '.$CFG->prefix
.'role_assignments ra
1581 INNER JOIN '.$CFG->prefix
.'role r ON ra.roleid = r.id
1582 INNER JOIN '.$CFG->prefix
.'context c ON ra.contextid = c.id
1585 FROM '.$CFG->prefix
.'role_assignments i_ra
1586 INNER JOIN '.$CFG->prefix
.'role i_r ON i_ra.roleid = i_r.id
1587 WHERE ra.userid = i_ra.userid AND
1588 ra.contextid = i_ra.contextid AND
1589 i_r.sortorder < r.sortorder
1594 * Can include a given document file (depends on second
1595 * parameter) or just return info about it.
1598 * @param string $file ?
1599 * @param bool $include ?
1601 * @todo Finish documenting this function
1603 function document_file($file, $include=true) {
1606 debugging('The document_file() function is deprecated.', DEBUG_DEVELOPER
);
1608 $file = clean_filename($file);
1614 $langs = array(current_language(), get_string('parentlanguage'), 'en');
1616 foreach ($langs as $lang) {
1617 $info = new object();
1618 $info->filepath
= $CFG->dirroot
.'/lang/'. $lang .'/docs/'. $file;
1619 $info->urlpath
= $CFG->wwwroot
.'/lang/'. $lang .'/docs/'. $file;
1621 if (file_exists($info->filepath
)) {
1623 include($info->filepath
);
1633 * Print an error page displaying an error message.
1634 * Old method, don't call directly in new code - use print_error instead.
1639 * @param string $message The message to display to the user about the error.
1640 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
1642 function error ($message, $link='') {
1644 global $CFG, $SESSION, $THEME;
1645 $message = clean_text($message); // In case nasties are in here
1647 if (defined('FULLME') && FULLME
== 'cron') {
1648 // Errors in cron should be mtrace'd.
1653 if (! defined('HEADER_PRINTED')) {
1654 //header not yet printed
1655 @header
('HTTP/1.0 404 Not Found');
1656 print_header(get_string('error'));
1658 print_container_end_all(false, $THEME->open_header_containers
);
1662 print_simple_box($message, '', '', '', '', 'errorbox');
1664 debugging('Stack trace:', DEBUG_DEVELOPER
);
1666 // in case we are logging upgrade in admin/index.php stop it
1667 if (function_exists('upgrade_log_finish')) {
1668 upgrade_log_finish();
1671 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
1672 if ( !empty($SESSION->fromurl
) ) {
1673 $link = $SESSION->fromurl
;
1674 unset($SESSION->fromurl
);
1676 $link = $CFG->wwwroot
.'/';
1680 if (!empty($link)) {
1681 print_continue($link);
1686 for ($i=0;$i<512;$i++
) { // Padding to help IE work with 404