Further work on Moodle 1.9 integration.
[moodle/mihaisucan.git] / lib / deprecatedlib.php
blob59cc157581fa7be53d702de70de5cbb0f8e0fd53
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas, Moodle http://moodle.com//
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * deprecatedlib.php - Old functions retained only for backward compatibility
29 * Old functions retained only for backward compatibility. New code should not
30 * use any of these functions.
32 * @author Martin Dougiamas
33 * @version $Id$
34 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
35 * @package moodlecore
41 /**
42 * Ensure that a variable is set
44 * If $var is undefined throw an error, otherwise return $var.
46 * @param mixed $var the variable which may be unset
47 * @param mixed $default the value to return if $var is unset
49 function require_variable($var) {
50 global $CFG;
51 if (!empty($CFG->disableglobalshack)) {
52 error( 'The require_variable() function is deprecated.' );
54 if (! isset($var)) {
55 error('A required parameter was missing');
59 /**
60 * Ensure that a variable is set
62 * If $var is undefined set it (by reference), otherwise return $var.
64 * @param mixed $var the variable which may be unset
65 * @param mixed $default the value to return if $var is unset
67 function optional_variable(&$var, $default=0) {
68 global $CFG;
69 if (!empty($CFG->disableglobalshack)) {
70 error( "The optional_variable() function is deprecated ($var, $default)." );
72 if (! isset($var)) {
73 $var = $default;
77 /**
78 * Ensure that a variable is set
80 * Return $var if it is defined, otherwise return $default,
81 * This function is very similar to {@link optional_variable()}
83 * @param mixed $var the variable which may be unset
84 * @param mixed $default the value to return if $var is unset
85 * @return mixed
87 function nvl(&$var, $default='') {
88 global $CFG;
90 if (!empty($CFG->disableglobalshack)) {
91 error( "The nvl() function is deprecated ($var, $default)." );
93 return isset($var) ? $var : $default;
96 /**
97 * Determines if a user an admin
99 * @uses $USER
100 * @param int $userid The id of the user as is found in the 'user' table
101 * @staticvar array $admins List of users who have been found to be admins by user id
102 * @staticvar array $nonadmins List of users who have been found not to be admins by user id
103 * @return bool
105 function isadmin($userid=0) {
106 global $USER, $CFG;
108 if (empty($CFG->rolesactive)) { // Then the user is likely to be upgrading NOW
109 if (!$userid) {
110 if (empty($USER->id)) {
111 return false;
113 if (!empty($USER->admin)) {
114 return true;
116 $userid = $USER->id;
119 return record_exists('user_admins', 'userid', $userid);
122 $context = get_context_instance(CONTEXT_SYSTEM);
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);
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);
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);
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);
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);
275 } else {
276 $context = get_context_instance(CONTEXT_COURSE, $courseid);
279 return has_capability('moodle/legacy:student', $context, $userid, false);
283 * Determines if the specified user is logged in as guest.
285 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
286 * @return bool
288 function isguest($userid=0) {
289 global $CFG;
291 if (empty($CFG->rolesactive)) {
292 return false;
295 $context = get_context_instance(CONTEXT_SYSTEM);
297 return has_capability('moodle/legacy:guest', $context, $userid, false);
301 * Enrols (or re-enrols) a student in a given course
303 * NOTE: Defaults to 'manual' enrolment - enrolment plugins
304 * must set it explicitly.
306 * @uses $CFG
307 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
308 * @param int $courseid The id of the course that is being viewed
309 * @param int $timestart ?
310 * @param int $timeend ?
311 * @param string $enrol ?
312 * @return bool
314 function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
316 global $CFG;
318 if (!$user = get_record('user', 'id', $userid)) { // Check user
319 return false;
322 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
323 return false;
326 $role = array_shift($roles); // We can only use one, let's use the first one
328 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
329 return false;
332 $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
334 return $res;
338 * Unenrols a student from a given course
340 * @param int $courseid The id of the course that is being viewed, if any
341 * @param int $userid The id of the user that is being tested against.
342 * @return bool
344 function unenrol_student($userid, $courseid=0) {
345 global $CFG;
347 $status = true;
349 if ($courseid) {
350 /// First delete any crucial stuff that might still send mail
351 if ($forums = get_records('forum', 'course', $courseid)) {
352 foreach ($forums as $forum) {
353 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
356 /// remove from all legacy student roles
357 if ($courseid == SITEID) {
358 $context = get_context_instance(CONTEXT_SYSTEM);
359 } else if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
360 return false;
362 if (!$roles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
363 return false;
365 foreach($roles as $role) {
366 $status = role_unassign($role->id, $userid, 0, $context->id) and $status;
368 } else {
369 // recursivelly unenroll student from all courses
370 if ($courses = get_records('course')) {
371 foreach($courses as $course) {
372 $status = unenrol_student($userid, $course->id) and $status;
377 return $status;
381 * Add a teacher to a given course
383 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
384 * @param int $courseid The id of the course that is being viewed, if any
385 * @param int $editall Can edit the course
386 * @param string $role Obsolete
387 * @param int $timestart The time they start
388 * @param int $timeend The time they end in this role
389 * @param string $enrol The type of enrolment this is
390 * @return bool
392 function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
393 global $CFG;
395 if (!$user = get_record('user', 'id', $userid)) { // Check user
396 return false;
399 $capability = $editall ? 'moodle/legacy:editingteacher' : 'moodle/legacy:teacher';
401 if (!$roles = get_roles_with_capability($capability, CAP_ALLOW)) {
402 return false;
405 $role = array_shift($roles); // We can only use one, let's use the first one
407 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
408 return false;
411 $res = role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol);
413 return $res;
417 * Removes a teacher from a given course (or ALL courses)
418 * Does not delete the user account
420 * @param int $courseid The id of the course that is being viewed, if any
421 * @param int $userid The id of the user that is being tested against.
422 * @return bool
424 function remove_teacher($userid, $courseid=0) {
425 global $CFG;
427 $roles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW);
429 if ($roles) {
430 $roles += get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
431 } else {
432 $roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW);
435 if (empty($roles)) {
436 return true;
439 $return = true;
441 if ($courseid) {
443 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
444 return false;
447 /// First delete any crucial stuff that might still send mail
448 if ($forums = get_records('forum', 'course', $courseid)) {
449 foreach ($forums as $forum) {
450 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
454 /// No need to remove from groups now
456 foreach ($roles as $role) { // Unassign them from all the teacher roles
457 $newreturn = role_unassign($role->id, $userid, 0, $context->id);
458 if (empty($newreturn)) {
459 $return = false;
463 } else {
464 delete_records('forum_subscriptions', 'userid', $userid);
465 $return = true;
466 foreach ($roles as $role) { // Unassign them from all the teacher roles
467 $newreturn = role_unassign($role->id, $userid, 0, 0);
468 if (empty($newreturn)) {
469 $return = false;
474 return $return;
478 * Add an admin to a site
480 * @uses SITEID
481 * @param int $userid The id of the user that is being tested against.
482 * @return bool
483 * @TODO: remove from cvs
485 function add_admin($userid) {
486 return true;
489 function get_user_info_from_db($field, $value) { // For backward compatibility
490 return get_complete_user_data($field, $value);
495 * Get the guest user information from the database
497 * @return object(user) An associative array with the details of the guest user account.
498 * @todo Is object(user) a correct return type? Or is array the proper return type with a note that the contents include all details for a user.
500 function get_guest() {
501 return get_complete_user_data('username', 'guest');
505 * Returns $user object of the main teacher for a course
507 * @uses $CFG
508 * @param int $courseid The course in question.
509 * @return user|false A {@link $USER} record of the main teacher for the specified course or false if error.
510 * @todo Finish documenting this function
512 function get_teacher($courseid) {
514 global $CFG;
516 $context = get_context_instance(CONTEXT_COURSE, $courseid);
518 // 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);
525 return false;
529 * Searches logs to find all enrolments since a certain date
531 * used to print recent activity
533 * @uses $CFG
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) {
540 global $CFG;
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,
547 {$CFG->prefix}log l
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
553 AND u.id = ra.userid
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
562 * @uses $CFG
563 * @uses SITEID
564 * @param int $courseid The course in question.
565 * @param string $sort ?
566 * @param string $dir ?
567 * @param int $page ?
568 * @param int $recordsperpage ?
569 * @param string $firstinitial ?
570 * @param string $lastinitial ?
571 * @param ? $group ?
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 ?
575 * @return object
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='') {
581 global $CFG;
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)) {
591 $hascap = false;
592 foreach ($roles as $role) {
593 if ($role->id == $CFG->defaultuserroleid) {
594 $hascap = true;
595 break;
598 if ($hascap) {
599 if (empty($fields)) {
600 $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);
612 if ($sort) {
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);
631 $LIKE = sql_ilike();
632 $fullname = sql_fullname('u.firstname','u.lastname');
634 $groupmembers = '';
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\' ';
645 if (!$fields) {
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';
652 if ($search) {
653 $search = ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\') ';
656 if ($firstinitial) {
657 $select .= ' AND u.firstname '. $LIKE .'\''. $firstinitial .'%\' ';
660 if ($lastinitial) {
661 $select .= ' AND u.lastname '. $LIKE .'\''. $lastinitial .'%\' ';
664 if ($group === 0) { /// Need something here to get all students not in a group
665 return array();
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 .')';
676 if ($sort) {
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
686 $groupmembers
687 WHERE $select $search $sort $dir", $page, $recordsperpage);
689 return $students;
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 ?
699 * @param ? $group ?
700 * @param string $exceptions ?
701 * @return int
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);
709 return 0;
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.
718 * @uses $CFG
719 * @param int $courseid The course in question.
720 * @param string $sort ?
721 * @param string $exceptions ?
722 * @return object
723 * @todo Finish documenting this function
725 function get_course_teachers($courseid, $sort='t.authority ASC', $exceptions='') {
727 global $CFG;
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
735 /// meaningful.
736 if (($courseid == SITEID) && !empty($CFG->defaultuserroleid) && empty($CFG->nodefaultuserrolelists)) {
737 if ($roles = get_roles_with_capability('moodle/legacy:teacher', CAP_ALLOW, $context)) {
738 $hascap = false;
739 foreach ($roles as $role) {
740 if ($role->id == $CFG->defaultuserroleid) {
741 $hascap = true;
742 break;
745 if ($hascap) {
746 if (empty($fields)) {
747 $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='') {
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 // 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
818 * @uses $CFG
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)){
826 $groups = $groupids;
827 // all groups must be from one course anyway...
828 $group = groups_get_group(array_shift($groups));
829 } else {
830 $group = groups_get_group($groupids);
832 if (!$group) {
833 return NULL;
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
843 * @uses $CFG
844 * @param int $courseid The course in question.
845 * @param int $groupid The group in question.
846 * @return object
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
853 continue;
855 if (($teacher->authority > 0) and groups_is_member($groupid, $teacher->id)) { // Specific group teachers
856 continue;
858 unset($teachers[$key]);
861 return $teachers;
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
883 * </ul>
884 * @return string
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) {
907 $output = '';
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);
912 if ($return) {
913 return $output;
914 } else {
915 echo $output;
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) {
936 $output = '';
938 $divclasses = 'box '.$class.' '.$class.'content';
939 $divstyles = '';
941 if ($align) {
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
947 if ($width < 40) {
948 $divclasses .= ' boxwidthnarrow'; // Approx 30% depending on theme
949 } else if ($width > 60) {
950 $divclasses .= ' boxwidthwide'; // Approx 80% depending on theme
951 } else {
952 $divclasses .= ' boxwidthnormal'; // Approx 50% depending on theme
954 } else {
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.';';
961 if ($divstyles) {
962 $divstyles = ' style="'.$divstyles.'"';
965 if ($id) {
966 $id = ' id="'.$id.'"';
969 $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
971 if ($return) {
972 return $output;
973 } else {
974 echo $output;
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) {
984 $output = '</div>';
985 if ($return) {
986 return $output;
987 } else {
988 echo $output;
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
1002 return true;
1004 if (ereg('[\|\`]', $string)) { // check for other bad characters
1005 return true;
1007 if (empty($string) or $string == '/') {
1008 return true;
1011 return false;
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) {
1020 return 'UTF-8';
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\";");
1046 return $template;
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
1057 * a form
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) {
1065 if (empty($var)) {
1066 $var = $unset_value;
1067 } else {
1068 $var = $set_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 = '') {
1084 if ($var) {
1085 echo $true_value;
1086 } else {
1087 echo $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() {
1111 global $CFG;
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 ';
1124 if ($groupid) {
1125 $sql = "AND gm.groupid = '$groupid' ";
1127 return $sql;
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.
1133 * @param groupid
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' ";
1139 if ($userid_sql) {
1140 $sql .= "AND $userid_sql = gm.userid ";
1142 return $sql;
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.
1151 * @uses $CFG
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.
1154 * @return object
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
1164 * @uses $CFG
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.
1189 * @uses $USER
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) {
1195 global $USER;
1196 if ($groups = groups_get_all_groups($courseid, $USER->id)) {
1197 return array_keys($groups);
1198 } else {
1199 return false;
1204 * Add a user to a group, return true upon success or if user already a group
1205 * member
1207 * @param int $groupid The group id to add user to
1208 * @param int $userid The user id to add to the group
1209 * @return bool
1211 function add_user_to_group($groupid, $userid) {
1212 global $CFG;
1213 require_once($CFG->dirroot.'/group/lib.php');
1215 return groups_add_member($groupid, $userid);
1220 * Returns an array of user objects
1222 * @uses $CFG
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='') {
1233 global $CFG;
1234 if (!empty($exceptions)) {
1235 $except = ' AND u.id NOT IN ('. $exceptions .') ';
1236 } else {
1237 $except = '';
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
1251 ORDER BY $sort",
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.
1274 * @uses $SESSION
1275 * @param int $courseid The course being examined - relates to id field in
1276 * 'course' table.
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) {
1281 global $SESSION;
1282 return $SESSION->currentgroup[$courseid] = $groupid;
1287 * Gets the current group - either from the session variable or from the database.
1289 * @uses $USER
1290 * @uses $SESSION
1291 * @param int $courseid The course being examined - relates to id field in
1292 * 'course' table.
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) {
1297 global $SESSION;
1299 if (isset($SESSION->currentgroup[$courseid])) {
1300 if ($full) {
1301 return groups_get_group($SESSION->currentgroup[$courseid]);
1302 } else {
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);
1311 if ($full) {
1312 return groups_get_group($mygroupid);
1313 } else {
1314 return $mygroupid;
1318 if ($full) {
1319 return false;
1320 } else {
1321 return 0;
1327 * A combination function to make it easier for modules
1328 * to set up groups.
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
1344 return false;
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
1363 /*)}else {
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?
1369 else {
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
1391 * to set up groups.
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 ?
1402 * @return int|false
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) {
1412 return 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);
1427 } else {
1428 //else he has no group in this course
1429 print_heading(get_string('notingroup'));
1430 print_footer($course);
1431 exit;
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);
1441 echo '</div>';
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);
1450 echo '</div>';
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) {
1470 $output = '';
1471 $groupsmenu = array();
1473 /// Add an "All groups" to the start of the menu
1474 if ($showall){
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');
1483 } else {
1484 $grouplabel = get_string('groupsseparate');
1487 if (count($groupsmenu) == 1) {
1488 $groupname = reset($groupsmenu);
1489 $output .= $grouplabel.': '.$groupname;
1490 } else {
1491 $output .= popup_form($urlroot.'&amp;group=', $groupsmenu, 'selectgroup', $currentgroup, '', '', '', true, 'self', $grouplabel);
1494 if ($return) {
1495 return $output;
1496 } else {
1497 echo $output;
1503 * All users that we have not seen for a really long time (ie dead accounts)
1504 * TODO: Delete this for Moodle 2.0
1506 * @uses $CFG
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) {
1512 global $CFG;
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
1523 * @uses $CFG
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) {
1529 global $CFG;
1530 return get_records_sql("SELECT *
1531 FROM {$CFG->prefix}user
1532 WHERE confirmed = 0
1533 AND firstaccess > 0
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
1541 * @uses $CFG
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) {
1547 global $CFG;
1548 return get_records_sql("SELECT *
1549 FROM {$CFG->prefix}user
1550 WHERE confirmed = 1
1551 AND lastaccess > 0
1552 AND lastaccess < $cutofftime
1553 AND deleted = 0
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() {
1570 global $CFG;
1571 return 'SELECT ra.userid,
1572 ra.roleid AS primary_roleid,
1573 ra.contextid,
1574 r.sortorder,
1575 r.name,
1576 r.description,
1577 r.shortname,
1578 c.instanceid AS courseid,
1579 c.contextlevel
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
1583 WHERE NOT EXISTS (
1584 SELECT 1
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
1590 ) ';
1594 * Can include a given document file (depends on second
1595 * parameter) or just return info about it.
1597 * @uses $CFG
1598 * @param string $file ?
1599 * @param bool $include ?
1600 * @return ?
1601 * @todo Finish documenting this function
1603 function document_file($file, $include=true) {
1604 global $CFG;
1606 debugging('The document_file() function is deprecated.', DEBUG_DEVELOPER);
1608 $file = clean_filename($file);
1610 if (empty($file)) {
1611 return false;
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)) {
1622 if ($include) {
1623 include($info->filepath);
1625 return $info;
1629 return false;
1633 * Print an error page displaying an error message.
1634 * Old method, don't call directly in new code - use print_error instead.
1637 * @uses $SESSION
1638 * @uses $CFG
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.
1649 mtrace($message);
1650 die;
1653 if (! defined('HEADER_PRINTED')) {
1654 //header not yet printed
1655 @header('HTTP/1.0 404 Not Found');
1656 print_header(get_string('error'));
1657 } else {
1658 print_container_end_all(false, $THEME->open_header_containers);
1661 echo '<br />';
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);
1675 } else {
1676 $link = $CFG->wwwroot .'/';
1680 if (!empty($link)) {
1681 print_continue($link);
1684 print_footer();
1686 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
1687 echo ' ';
1690 die;
1693 function use_html_editor($name='', $editorhidebuttons='', $id='') {
1694 // error('use_html_editor() not available anymore');