MDL-25187 upgrade log debugging to use new DML style
[moodle.git] / lib / datalib.php
CommitLineData
3564771d 1<?php
2
117bd748
PS
3// This file is part of Moodle - http://moodle.org/
4//
3564771d 5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
117bd748 14//
3564771d 15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
341b5ed2 17
7cf1c7bd 18/**
19 * Library of functions for database manipulation.
5930cded 20 *
7cf1c7bd 21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - moodlelib.php - general-purpose Moodle functions
3564771d 24 *
78bfb562
PS
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7cf1c7bd 29 */
30
78bfb562
PS
31defined('MOODLE_INTERNAL') || die();
32
4f0c2d00
PS
33/**
34 * The maximum courses in a category
35 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
36 */
3564771d 37define('MAX_COURSES_IN_CATEGORY', 10000);
4f0c2d00 38
117bd748 39/**
3564771d 40 * The maximum number of course categories
117bd748 41 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
3564771d 42 */
0cbe8111 43define('MAX_COURSE_CATEGORIES', 10000);
44
4f0c2d00
PS
45/**
46 * Number of seconds to wait before updating lastaccess information in DB.
47 */
48define('LASTACCESS_UPDATE_SECS', 60);
df28d6c5 49
18a97fd8 50/**
fbc21ae8 51 * Returns $user object of the main admin user
20aeb4b8 52 * primary admin = admin with lowest role_assignment id among admins
3564771d 53 *
54 * @global object
55 * @static object $myadmin
56 * @return object An associative array representing the admin user.
fbc21ae8 57 */
4f0c2d00
PS
58function get_admin() {
59 static $mainadmin = null;
2965f8fd 60
4f0c2d00 61 if (!isset($mainadmin)) {
850262ee
AD
62 if (! $admins = get_admins()) {
63 return false;
df28d6c5 64 }
4f0c2d00
PS
65 //TODO: add some admin setting for specifying of THE main admin
66 // for now return the first assigned admin
67 $mainadmin = reset($admins);
df28d6c5 68 }
4f0c2d00 69 return $mainadmin;
df28d6c5 70}
71
18a97fd8 72/**
4f0c2d00 73 * Returns list of all admins, using 1 DB query
fbc21ae8 74 *
3564771d 75 * @return array
fbc21ae8 76 */
df28d6c5 77function get_admins() {
4f0c2d00 78 global $DB, $CFG;
5930cded 79
7928979b 80 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
adf176d7 81 return array();
7928979b
MD
82 }
83
4f0c2d00 84 $sql = "SELECT u.*
624a690b 85 FROM {user} u
4f0c2d00 86 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
5930cded 87
4f0c2d00 88 return $DB->get_records_sql($sql);
df28d6c5 89}
90
900df8b6 91/**
fbc21ae8 92 * Search through course users
93 *
5930cded 94 * If $coursid specifies the site course then this function searches
fbc21ae8 95 * through all undeleted and confirmed users
96 *
3564771d 97 * @global object
98 * @uses SITEID
99 * @uses SQL_PARAMS_NAMED
100 * @uses CONTEXT_COURSE
fbc21ae8 101 * @param int $courseid The course in question.
102 * @param int $groupid The group in question.
3564771d 103 * @param string $searchtext The string to search for
104 * @param string $sort A field to sort by
105 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
106 * @return array
fbc21ae8 107 */
624a690b 108function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
109 global $DB;
0720313b 110
245ac557 111 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
8f0cd6ef 112
900df8b6 113 if (!empty($exceptions)) {
624a690b 114 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
115 $except = "AND u.id $exceptions";
900df8b6 116 } else {
624a690b 117 $except = "";
118 $params = array();
900df8b6 119 }
2700d113 120
900df8b6 121 if (!empty($sort)) {
624a690b 122 $order = "ORDER BY $sort";
900df8b6 123 } else {
624a690b 124 $order = "";
900df8b6 125 }
8f0cd6ef 126
b0238f06 127 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
624a690b 128 $params['search1'] = "%$searchtext%";
129 $params['search2'] = "%$searchtext%";
2700d113 130
222ac91b 131 if (!$courseid or $courseid == SITEID) {
624a690b 132 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
133 FROM {user} u
134 WHERE $select
135 $except
136 $order";
137 return $DB->get_records_sql($sql, $params);
2700d113 138
624a690b 139 } else {
900df8b6 140 if ($groupid) {
624a690b 141 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
142 FROM {user} u
143 JOIN {groups_members} gm ON gm.userid = u.id
144 WHERE $select AND gm.groupid = :groupid
145 $except
146 $order";
147 $params['groupid'] = $groupid;
148 return $DB->get_records_sql($sql, $params);
149
900df8b6 150 } else {
ea8158c1 151 $context = get_context_instance(CONTEXT_COURSE, $courseid);
152 $contextlists = get_related_contexts_string($context);
624a690b 153
154 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
155 FROM {user} u
156 JOIN {role_assignments} ra ON ra.userid = u.id
157 WHERE $select AND ra.contextid $contextlists
158 $except
159 $order";
160 return $DB->get_records_sql($sql, $params);
900df8b6 161 }
162 }
df28d6c5 163}
164
18a97fd8 165/**
fbc21ae8 166 * Returns a subset of users
167 *
3564771d 168 * @global object
169 * @uses DEBUG_DEVELOPER
170 * @uses SQL_PARAMS_NAMED
7290c7fa 171 * @param bool $get If false then only a count of the records is returned
fbc21ae8 172 * @param string $search A simple string to search for
7290c7fa 173 * @param bool $confirmed A switch to allow/disallow unconfirmed users
3564771d 174 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
fbc21ae8 175 * @param string $sort A SQL snippet for the sorting criteria to use
3564771d 176 * @param string $firstinitial Users whose first name starts with $firstinitial
177 * @param string $lastinitial Users whose last name starts with $lastinitial
178 * @param string $page The page or records to return
179 * @param string $recordsperpage The number of records to return per page
fbc21ae8 180 * @param string $fields A comma separated list of fields to be returned from the chosen table.
117bd748 181 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
3564771d 182 * False is returned if an error is encountered.
fbc21ae8 183 */
624a690b 184function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
185 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
b3df1764 186 global $DB, $CFG;
5930cded 187
36075e09 188 if ($get && !$recordsperpage) {
189 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
190 'On large installations, this will probably cause an out of memory error. ' .
191 'Please think again and change your code so that it does not try to ' .
03517306 192 'load so much data into memory.', DEBUG_DEVELOPER);
36075e09 193 }
18a97fd8 194
245ac557 195 $fullname = $DB->sql_fullname();
e384fb7b 196
b3df1764
PS
197 $select = " id <> :guestid AND deleted = 0";
198 $params = array('guestid'=>$CFG->siteguest);
488acd1b 199
0044147e 200 if (!empty($search)){
201 $search = trim($search);
b0238f06 202 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
624a690b 203 $params['search1'] = "%$search%";
204 $params['search2'] = "%$search%";
205 $params['search3'] = "$search";
e384fb7b 206 }
207
5a741655 208 if ($confirmed) {
624a690b 209 $select .= " AND confirmed = 1";
5a741655 210 }
211
212 if ($exceptions) {
624a690b 213 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
214 $params = $params + $eparams;
215 $except = " AND id $exceptions";
5a741655 216 }
217
488acd1b 218 if ($firstinitial) {
b0238f06 219 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
624a690b 220 $params['fni'] = "$firstinitial%";
8f0cd6ef 221 }
488acd1b 222 if ($lastinitial) {
b0238f06 223 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
624a690b 224 $params['lni'] = "$lastinitial%";
8f0cd6ef 225 }
488acd1b 226
cd1edf9e 227 if ($extraselect) {
624a690b 228 $select .= " AND $extraselect";
229 $params = $params + (array)$extraparams;
cd1edf9e 230 }
231
5a741655 232 if ($get) {
624a690b 233 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
5a741655 234 } else {
624a690b 235 return $DB->count_records_select('user', $select, $params);
5a741655 236 }
9fa49e22 237}
238
5a741655 239
18a97fd8 240/**
fbc21ae8 241 * @todo Finish documenting this function
3564771d 242 *
243 * @param string $sort An SQL field to sort by
244 * @param string $dir The sort direction ASC|DESC
245 * @param int $page The page or records to return
246 * @param int $recordsperpage The number of records to return per page
247 * @param string $search A simple string to search for
248 * @param string $firstinitial Users whose first name starts with $firstinitial
249 * @param string $lastinitial Users whose last name starts with $lastinitial
250 * @param string $extraselect An additional SQL select statement to append to the query
251 * @param array $extraparams Additional parameters to use for the above $extraselect
252 * @return array Array of {@link $USER} records
fbc21ae8 253 */
254
36075e09 255function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
624a690b 256 $search='', $firstinitial='', $lastinitial='', $extraselect='', array $extraparams=null) {
257 global $DB;
31fefa63 258
245ac557 259 $fullname = $DB->sql_fullname();
c2a96d6b 260
624a690b 261 $select = "deleted <> 1";
262 $params = array();
488acd1b 263
0044147e 264 if (!empty($search)) {
265 $search = trim($search);
f63ac65a
PS
266 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
267 " OR ". $DB->sql_like('email', ':search2', false, false).
268 " OR username = :search3)";
624a690b 269 $params['search1'] = "%$search%";
270 $params['search2'] = "%$search%";
271 $params['search3'] = "$search";
488acd1b 272 }
273
274 if ($firstinitial) {
f63ac65a 275 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
624a690b 276 $params['fni'] = "$firstinitial%";
488acd1b 277 }
488acd1b 278 if ($lastinitial) {
f63ac65a 279 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
624a690b 280 $params['lni'] = "$lastinitial%";
c750592a 281 }
282
cd1edf9e 283 if ($extraselect) {
624a690b 284 $select .= " AND $extraselect";
285 $params = $params + (array)$extraparams;
cd1edf9e 286 }
03d820c7 287
488acd1b 288 if ($sort) {
624a690b 289 $sort = " ORDER BY $sort $dir";
488acd1b 290 }
291
292/// warning: will return UNCONFIRMED USERS
624a690b 293 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
294 FROM {user}
295 WHERE $select
296 $sort", $params, $page, $recordsperpage);
9fa49e22 297
298}
299
488acd1b 300
18a97fd8 301/**
7290c7fa 302 * Full list of users that have confirmed their accounts.
fbc21ae8 303 *
3564771d 304 * @global object
624a690b 305 * @return array of unconfirmed users
fbc21ae8 306 */
9fa49e22 307function get_users_confirmed() {
b3df1764 308 global $DB, $CFG;
624a690b 309 return $DB->get_records_sql("SELECT *
310 FROM {user}
b3df1764 311 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
9fa49e22 312}
313
314
02ebf404 315/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
316
317
18a97fd8 318/**
fbc21ae8 319 * Returns $course object of the top-level site.
320 *
3f77c158 321 * @return object A {@link $COURSE} object for the site, exception if not found
fbc21ae8 322 */
c44d5d42 323function get_site() {
624a690b 324 global $SITE, $DB;
c44d5d42 325
326 if (!empty($SITE->id)) { // We already have a global to use, so return that
327 return $SITE;
328 }
02ebf404 329
624a690b 330 if ($course = $DB->get_record('course', array('category'=>0))) {
02ebf404 331 return $course;
332 } else {
3f77c158
PS
333 // course table exists, but the site is not there,
334 // unfortunately there is no automatic way to recover
335 throw new moodle_exception('nosite', 'error');
02ebf404 336 }
337}
338
18a97fd8 339/**
613bbd7c 340 * Returns list of courses, for whole site, or category
341 *
342 * Returns list of courses, for whole site, or category
bfbfdb53 343 * Important: Using c.* for fields is extremely expensive because
613bbd7c 344 * we are using distinct. You almost _NEVER_ need all the fields
345 * in such a large SELECT
346 *
3564771d 347 * @global object
348 * @global object
349 * @global object
350 * @uses CONTEXT_COURSE
351 * @param string|int $categoryid Either a category id or 'all' for everything
352 * @param string $sort A field and direction to sort by
353 * @param string $fields The additional fields to return
354 * @return array Array of courses
613bbd7c 355 */
6315b1c8 356function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 357
3b8a284c 358 global $USER, $CFG, $DB;
5930cded 359
3b8a284c 360 $params = array();
361
362 if ($categoryid !== "all" && is_numeric($categoryid)) {
363 $categoryselect = "WHERE c.category = :catid";
364 $params['catid'] = $categoryid;
71dea306 365 } else {
5930cded 366 $categoryselect = "";
09575480 367 }
368
369 if (empty($sort)) {
370 $sortstatement = "";
371 } else {
372 $sortstatement = "ORDER BY $sort";
373 }
374
375 $visiblecourses = array();
5930cded 376
4f0c2d00
PS
377 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
378
379 $sql = "SELECT $fields $ccselect
3b8a284c 380 FROM {course} c
4f0c2d00 381 $ccjoin
3b8a284c 382 $categoryselect
383 $sortstatement";
384
71dea306 385 // pull out all course matching the cat
3b8a284c 386 if ($courses = $DB->get_records_sql($sql, $params)) {
09575480 387
388 // loop throught them
389 foreach ($courses as $course) {
4f0c2d00 390 context_instance_preload($course);
285f94f5 391 if (isset($course->visible) && $course->visible <= 0) {
09575480 392 // for hidden courses, require visibility check
4f0c2d00 393 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
3b8a284c 394 $visiblecourses [$course->id] = $course;
09575480 395 }
396 } else {
3b8a284c 397 $visiblecourses [$course->id] = $course;
5930cded 398 }
09575480 399 }
6315b1c8 400 }
71dea306 401 return $visiblecourses;
8130b77b 402}
403
8130b77b 404
6315b1c8 405/**
613bbd7c 406 * Returns list of courses, for whole site, or category
407 *
408 * Similar to get_courses, but allows paging
5930cded 409 * Important: Using c.* for fields is extremely expensive because
613bbd7c 410 * we are using distinct. You almost _NEVER_ need all the fields
411 * in such a large SELECT
412 *
3564771d 413 * @global object
414 * @global object
415 * @global object
416 * @uses CONTEXT_COURSE
417 * @param string|int $categoryid Either a category id or 'all' for everything
418 * @param string $sort A field and direction to sort by
419 * @param string $fields The additional fields to return
420 * @param int $totalcount Reference for the number of courses
421 * @param string $limitfrom The course to start from
422 * @param string $limitnum The number of courses to limit to
117bd748 423 * @return array Array of courses
613bbd7c 424 */
6315b1c8 425function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
426 &$totalcount, $limitfrom="", $limitnum="") {
3b8a284c 427 global $USER, $CFG, $DB;
c7fe5c6f 428
3b8a284c 429 $params = array();
5930cded 430
71dea306 431 $categoryselect = "";
432 if ($categoryid != "all" && is_numeric($categoryid)) {
3b8a284c 433 $categoryselect = "WHERE c.category = :catid";
434 $params['catid'] = $categoryid;
71dea306 435 } else {
5930cded 436 $categoryselect = "";
437 }
438
4f0c2d00
PS
439 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
440
441 $sql = "SELECT $fields $ccselect
3b8a284c 442 FROM {course} c
4f0c2d00 443 $ccjoin
3b8a284c 444 $categoryselect
445 ORDER BY $sort";
446
71dea306 447 // pull out all course matching the cat
3b8a284c 448 if (!$rs = $DB->get_recordset_sql($sql, $params)) {
449 return array();
12490fc2 450 }
71dea306 451 $totalcount = 0;
5930cded 452
285f94f5 453 if (!$limitfrom) {
5930cded 454 $limitfrom = 0;
71dea306 455 }
5930cded 456
71dea306 457 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
3b8a284c 458 $visiblecourses = array();
459 foreach($rs as $course) {
4f0c2d00 460 context_instance_preload($course);
03cedd62 461 if ($course->visible <= 0) {
462 // for hidden courses, require visibility check
4f0c2d00 463 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
71dea306 464 $totalcount++;
03cedd62 465 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
3b8a284c 466 $visiblecourses [$course->id] = $course;
71dea306 467 }
468 }
03cedd62 469 } else {
470 $totalcount++;
471 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
3b8a284c 472 $visiblecourses [$course->id] = $course;
03cedd62 473 }
5930cded 474 }
71dea306 475 }
3b8a284c 476 $rs->close();
71dea306 477 return $visiblecourses;
02ebf404 478}
479
624a690b 480/**
70f15878 481 * Retrieve course records with the course managers and other related records
482 * that we need for print_course(). This allows print_courses() to do its job
483 * in a constant number of DB queries, regardless of the number of courses,
484 * role assignments, etc.
bfbfdb53 485 *
70f15878 486 * The returned array is indexed on c.id, and each course will have
70f15878 487 * - $course->managers - array containing RA objects that include a $user obj
488 * with the minimal fields needed for fullname()
489 *
3564771d 490 * @global object
491 * @global object
492 * @global object
493 * @uses CONTEXT_COURSE
494 * @uses CONTEXT_SYSTEM
495 * @uses CONTEXT_COURSECAT
496 * @uses SITEID
497 * @param int|string $categoryid Either the categoryid for the courses or 'all'
498 * @param string $sort A SQL sort field and direction
499 * @param array $fields An array of additional fields to fetch
500 * @return array
70f15878 501 */
502function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
503 /*
bfbfdb53 504 * The plan is to
70f15878 505 *
506 * - Grab the courses JOINed w/context
507 *
508 * - Grab the interesting course-manager RAs
509 * JOINed with a base user obj and add them to each course
510 *
511 * So as to do all the work in 2 DB queries. The RA+user JOIN
512 * ends up being pretty expensive if it happens over _all_
513 * courses on a large site. (Are we surprised!?)
514 *
515 * So this should _never_ get called with 'all' on a large site.
516 *
517 */
3b8a284c 518 global $USER, $CFG, $DB;
70f15878 519
3b8a284c 520 $params = array();
70f15878 521 $allcats = false; // bool flag
522 if ($categoryid === 'all') {
523 $categoryclause = '';
524 $allcats = true;
525 } elseif (is_numeric($categoryid)) {
3b8a284c 526 $categoryclause = "c.category = :catid";
527 $params['catid'] = $categoryid;
70f15878 528 } else {
529 debugging("Could not recognise categoryid = $categoryid");
530 $categoryclause = '';
531 }
532
533 $basefields = array('id', 'category', 'sortorder',
534 'shortname', 'fullname', 'idnumber',
df997f84
PS
535 'startdate', 'visible',
536 'newsitems', 'groupmode', 'groupmodeforce');
70f15878 537
538 if (!is_null($fields) && is_string($fields)) {
539 if (empty($fields)) {
540 $fields = $basefields;
541 } else {
bfbfdb53 542 // turn the fields from a string to an array that
70f15878 543 // get_user_courses_bycap() will like...
544 $fields = explode(',',$fields);
545 $fields = array_map('trim', $fields);
546 $fields = array_unique(array_merge($basefields, $fields));
547 }
548 } elseif (is_array($fields)) {
549 $fields = array_merge($basefields,$fields);
550 }
551 $coursefields = 'c.' .join(',c.', $fields);
552
553 if (empty($sort)) {
554 $sortstatement = "";
555 } else {
556 $sortstatement = "ORDER BY $sort";
557 }
558
e89f157b 559 $where = 'WHERE c.id != ' . SITEID;
70f15878 560 if ($categoryclause !== ''){
e89f157b 561 $where = "$where AND $categoryclause";
70f15878 562 }
563
564 // pull out all courses matching the cat
4f0c2d00
PS
565 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
566 $sql = "SELECT $coursefields $ccselect
3b8a284c 567 FROM {course} c
4f0c2d00 568 $ccjoin
3b8a284c 569 $where
570 $sortstatement";
70f15878 571
572 $catpaths = array();
573 $catpath = NULL;
3b8a284c 574 if ($courses = $DB->get_records_sql($sql, $params)) {
70f15878 575 // loop on courses materialising
bfbfdb53 576 // the context, and prepping data to fetch the
70f15878 577 // managers efficiently later...
578 foreach ($courses as $k => $course) {
4f0c2d00
PS
579 context_instance_preload($course);
580 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
581 $courses[$k] = $course;
70f15878 582 $courses[$k]->managers = array();
583 if ($allcats === false) {
584 // single cat, so take just the first one...
585 if ($catpath === NULL) {
4f0c2d00 586 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
70f15878 587 }
588 } else {
589 // chop off the contextid of the course itself
590 // like dirname() does...
4f0c2d00 591 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
70f15878 592 }
593 }
594 } else {
595 return array(); // no courses!
596 }
597
df997f84
PS
598 $CFG->coursecontact = trim($CFG->coursecontact);
599 if (empty($CFG->coursecontact)) {
b1cff118 600 return $courses;
601 }
602
7785dc2e 603 $managerroles = explode(',', $CFG->coursecontact);
70f15878 604 $catctxids = '';
605 if (count($managerroles)) {
606 if ($allcats === true) {
607 $catpaths = array_unique($catpaths);
608 $ctxids = array();
609 foreach ($catpaths as $cpath) {
610 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
611 }
612 $ctxids = array_unique($ctxids);
613 $catctxids = implode( ',' , $ctxids);
c7a71127 614 unset($catpaths);
615 unset($cpath);
70f15878 616 } else {
617 // take the ctx path from the first course
618 // as all categories will be the same...
619 $catpath = substr($catpath,1);
620 $catpath = preg_replace(':/\d+$:','',$catpath);
621 $catctxids = str_replace('/',',',$catpath);
622 }
623 if ($categoryclause !== '') {
624 $categoryclause = "AND $categoryclause";
625 }
626 /*
bfbfdb53 627 * Note: Here we use a LEFT OUTER JOIN that can
70f15878 628 * "optionally" match to avoid passing a ton of context
629 * ids in an IN() clause. Perhaps a subselect is faster.
630 *
631 * In any case, this SQL is not-so-nice over large sets of
632 * courses with no $categoryclause.
633 *
634 */
635 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
70f15878 636 r.id AS roleid, r.name as rolename,
637 u.id AS userid, u.firstname, u.lastname
3b8a284c 638 FROM {role_assignments} ra
639 JOIN {context} ctx ON ra.contextid = ctx.id
640 JOIN {user} u ON ra.userid = u.id
641 JOIN {role} r ON ra.roleid = r.id
642 LEFT OUTER JOIN {course} c
643 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
c7a71127 644 WHERE ( c.id IS NOT NULL";
645 // under certain conditions, $catctxids is NULL
646 if($catctxids == NULL){
647 $sql .= ") ";
648 }else{
649 $sql .= " OR ra.contextid IN ($catctxids) )";
650 }
651
df997f84 652 $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
70f15878 653 $categoryclause
654 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
3b8a284c 655 $rs = $DB->get_recordset_sql($sql, $params);
bfbfdb53 656
70f15878 657 // This loop is fairly stupid as it stands - might get better
658 // results doing an initial pass clustering RAs by path.
3b8a284c 659 foreach($rs as $ra) {
4f0c2d00 660 $user = new stdClass;
03cedd62 661 $user->id = $ra->userid; unset($ra->userid);
662 $user->firstname = $ra->firstname; unset($ra->firstname);
663 $user->lastname = $ra->lastname; unset($ra->lastname);
664 $ra->user = $user;
665 if ($ra->contextlevel == CONTEXT_SYSTEM) {
666 foreach ($courses as $k => $course) {
667 $courses[$k]->managers[] = $ra;
668 }
4f0c2d00 669 } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
03cedd62 670 if ($allcats === false) {
671 // It always applies
70f15878 672 foreach ($courses as $k => $course) {
673 $courses[$k]->managers[] = $ra;
674 }
03cedd62 675 } else {
676 foreach ($courses as $k => $course) {
4f0c2d00 677 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
03cedd62 678 // Note that strpos() returns 0 as "matched at pos 0"
4f0c2d00 679 if (strpos($coursecontext->path, $ra->path.'/') === 0) {
03cedd62 680 // Only add it to subpaths
70f15878 681 $courses[$k]->managers[] = $ra;
682 }
70f15878 683 }
70f15878 684 }
03cedd62 685 } else { // course-level
4f0c2d00 686 if (!array_key_exists($ra->instanceid, $courses)) {
03cedd62 687 //this course is not in a list, probably a frontpage course
688 continue;
689 }
690 $courses[$ra->instanceid]->managers[] = $ra;
70f15878 691 }
692 }
3b8a284c 693 $rs->close();
70f15878 694 }
695
696 return $courses;
697}
02ebf404 698
18a97fd8 699/**
7290c7fa 700 * A list of courses that match a search
fbc21ae8 701 *
3564771d 702 * @global object
703 * @global object
704 * @param array $searchterms An array of search criteria
705 * @param string $sort A field and direction to sort by
706 * @param int $page The page number to get
707 * @param int $recordsperpage The number of records per page
708 * @param int $totalcount Passed in by reference.
7290c7fa 709 * @return object {@link $COURSE} records
fbc21ae8 710 */
d4419d55 711function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
3b8a284c 712 global $CFG, $DB;
02ebf404 713
06c1a1da 714 if ($DB->sql_regex_supported()) {
715 $REGEXP = $DB->sql_regex(true);
716 $NOTREGEXP = $DB->sql_regex(false);
02ebf404 717 }
718
06c1a1da 719 $searchcond = array();
720 $params = array();
721 $i = 0;
02ebf404 722
06c1a1da 723 $concat = $DB->sql_concat('c.summary', "' '", 'c.fullname');
3b8a284c 724
02ebf404 725 foreach ($searchterms as $searchterm) {
06c1a1da 726 $i++;
6bb0f67f 727
b0238f06 728 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
0f62a5b5 729 /// will use it to simulate the "-" operator with LIKE clause
730
6bb0f67f 731 /// Under Oracle and MSSQL, trim the + and - operators and perform
0f62a5b5 732 /// simpler LIKE (or NOT LIKE) queries
06c1a1da 733 if (!$DB->sql_regex_supported()) {
0f62a5b5 734 if (substr($searchterm, 0, 1) == '-') {
b0238f06 735 $NOT = true;
0f62a5b5 736 }
6bb0f67f 737 $searchterm = trim($searchterm, '+-');
738 }
739
06c1a1da 740 // TODO: +- may not work for non latin languages
3b8a284c 741
d4419d55 742 if (substr($searchterm,0,1) == '+') {
06c1a1da 743 $searchterm = trim($searchterm, '+-');
744 $searchterm = preg_quote($searchterm, '|');
745 $searchcond[] = "$concat $REGEXP :ss$i";
746 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
747
a8b56716 748 } else if (substr($searchterm,0,1) == "-") {
06c1a1da 749 $searchterm = trim($searchterm, '+-');
750 $searchterm = preg_quote($searchterm, '|');
751 $searchcond[] = "$concat $NOTREGEXP :ss$i";
752 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
753
a8b56716 754 } else {
47586394 755 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
06c1a1da 756 $params['ss'.$i] = "%$searchterm%";
a8b56716 757 }
02ebf404 758 }
759
06c1a1da 760 if (empty($searchcond)) {
761 $totalcount = 0;
762 return array();
763 }
764
765 $searchcond = implode(" AND ", $searchcond);
766
4f0c2d00
PS
767 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
768 $sql = "SELECT c.* $ccselect
3b8a284c 769 FROM {course} c
4f0c2d00 770 $ccjoin
06c1a1da 771 WHERE $searchcond AND c.id <> ".SITEID."
772 ORDER BY $sort";
2c64f65c 773 $courses = array();
3b8a284c 774 $c = 0; // counts how many visible courses we've seen
02ebf404 775
3b8a284c 776 if ($rs = $DB->get_recordset_sql($sql, $params)) {
2c64f65c 777 // Tiki pagination
778 $limitfrom = $page * $recordsperpage;
779 $limitto = $limitfrom + $recordsperpage;
2c64f65c 780
3b8a284c 781 foreach($rs as $course) {
4f0c2d00
PS
782 context_instance_preload($course);
783 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
784 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2c64f65c 785 // Don't exit this loop till the end
786 // we need to count all the visible courses
787 // to update $totalcount
788 if ($c >= $limitfrom && $c < $limitto) {
3b8a284c 789 $courses[$course->id] = $course;
02ebf404 790 }
2c64f65c 791 $c++;
02ebf404 792 }
793 }
3b8a284c 794 $rs->close();
02ebf404 795 }
796
2c64f65c 797 // our caller expects 2 bits of data - our return
798 // array, and an updated $totalcount
799 $totalcount = $c;
02ebf404 800 return $courses;
801}
802
803
18a97fd8 804/**
40fb8aa6 805 * Returns a sorted list of categories. Each category object has a context
806 * property that is a context object.
bfbfdb53 807 *
40fb8aa6 808 * When asking for $parent='none' it will return all the categories, regardless
809 * of depth. Wheen asking for a specific parent, the default is to return
810 * a "shallow" resultset. Pass false to $shallow and it will return all
bfbfdb53 811 * the child categories as well.
812 *
3564771d 813 * @global object
814 * @uses CONTEXT_COURSECAT
613bbd7c 815 * @param string $parent The parent category if any
816 * @param string $sort the sortorder
40fb8aa6 817 * @param bool $shallow - set to false to get the children too
613bbd7c 818 * @return array of categories
fbc21ae8 819 */
40fb8aa6 820function get_categories($parent='none', $sort=NULL, $shallow=true) {
3b8a284c 821 global $DB;
40fb8aa6 822
823 if ($sort === NULL) {
824 $sort = 'ORDER BY cc.sortorder ASC';
825 } elseif ($sort ==='') {
826 // leave it as empty
827 } else {
828 $sort = "ORDER BY $sort";
829 }
02ebf404 830
4f0c2d00
PS
831 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
832
814748c9 833 if ($parent === 'none') {
4f0c2d00 834 $sql = "SELECT cc.* $ccselect
3b8a284c 835 FROM {course_categories} cc
4f0c2d00 836 $ccjoin
40fb8aa6 837 $sort";
3b8a284c 838 $params = array();
839
40fb8aa6 840 } elseif ($shallow) {
4f0c2d00 841 $sql = "SELECT cc.* $ccselect
3b8a284c 842 FROM {course_categories} cc
4f0c2d00 843 $ccjoin
3b8a284c 844 WHERE cc.parent=?
40fb8aa6 845 $sort";
3b8a284c 846 $params = array($parent);
847
02ebf404 848 } else {
4f0c2d00 849 $sql = "SELECT cc.* $ccselect
3b8a284c 850 FROM {course_categories} cc
4f0c2d00 851 $ccjoin
3b8a284c 852 JOIN {course_categories} ccp
853 ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").")
854 WHERE ccp.id=?
40fb8aa6 855 $sort";
3b8a284c 856 $params = array($parent);
02ebf404 857 }
40fb8aa6 858 $categories = array();
859
3b8a284c 860 if( $rs = $DB->get_recordset_sql($sql, $params) ){
861 foreach($rs as $cat) {
4f0c2d00
PS
862 context_instance_preload($cat);
863 $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
864 if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
40fb8aa6 865 $categories[$cat->id] = $cat;
02ebf404 866 }
867 }
3b8a284c 868 $rs->close();
02ebf404 869 }
870 return $categories;
871}
872
873
2327b9df 874/**
875 * Returns an array of category ids of all the subcategories for a given
876 * category.
3564771d 877 *
878 * @global object
879 * @param int $catid - The id of the category whose subcategories we want to find.
2327b9df 880 * @return array of category ids.
881 */
882function get_all_subcategories($catid) {
3b8a284c 883 global $DB;
2327b9df 884
885 $subcats = array();
886
3b8a284c 887 if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
2327b9df 888 foreach ($categories as $cat) {
889 array_push($subcats, $cat->id);
890 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
891 }
892 }
893 return $subcats;
894}
895
18a97fd8 896/**
0cbe8111 897 * Return specified category, default if given does not exist
117bd748 898 *
3564771d 899 * @global object
900 * @uses MAX_COURSES_IN_CATEGORY
901 * @uses CONTEXT_COURSECAT
902 * @uses SYSCONTEXTID
0cbe8111 903 * @param int $catid course category id
904 * @return object caregory
905 */
906function get_course_category($catid=0) {
907 global $DB;
908
909 $category = false;
910
911 if (!empty($catid)) {
912 $category = $DB->get_record('course_categories', array('id'=>$catid));
913 }
8f0cd6ef 914
0cbe8111 915 if (!$category) {
916 // the first category is considered default for now
917 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
918 $category = reset($category);
919
920 } else {
365a5941 921 $cat = new stdClass();
0cbe8111 922 $cat->name = get_string('miscellaneous');
923 $cat->depth = 1;
924 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
925 $cat->timemodified = time();
a8d6ef8c 926 $catid = $DB->insert_record('course_categories', $cat);
0cbe8111 927 // make sure category context exists
928 get_context_instance(CONTEXT_COURSECAT, $catid);
929 mark_context_dirty('/'.SYSCONTEXTID);
7a9d505b 930 fix_course_sortorder(); // Required to build course_categories.depth and .path.
0cbe8111 931 $category = $DB->get_record('course_categories', array('id'=>$catid));
f41ef63e 932 }
0cbe8111 933 }
ba87a4da 934
0cbe8111 935 return $category;
936}
937
938/**
939 * Fixes course category and course sortorder, also verifies category and course parents and paths.
a1b892cc 940 * (circular references are not fixed)
3564771d 941 *
942 * @global object
943 * @global object
944 * @uses MAX_COURSES_IN_CATEGORY
945 * @uses MAX_COURSE_CATEGORIES
946 * @uses SITEID
947 * @uses CONTEXT_COURSE
948 * @return void
0cbe8111 949 */
950function fix_course_sortorder() {
951 global $DB, $SITE;
952
953 //WARNING: this is PHP5 only code!
954
955 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
956 //move all categories that are not sorted yet to the end
957 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
958 }
959
960 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
961 $topcats = array();
962 $brokencats = array();
963 foreach ($allcats as $cat) {
964 $sortorder = (int)$cat->sortorder;
965 if (!$cat->parent) {
966 while(isset($topcats[$sortorder])) {
967 $sortorder++;
968 }
969 $topcats[$sortorder] = $cat;
970 continue;
971 }
972 if (!isset($allcats[$cat->parent])) {
973 $brokencats[] = $cat;
974 continue;
c5d13b68 975 }
0cbe8111 976 if (!isset($allcats[$cat->parent]->children)) {
977 $allcats[$cat->parent]->children = array();
c5d13b68 978 }
0cbe8111 979 while(isset($allcats[$cat->parent]->children[$sortorder])) {
980 $sortorder++;
981 }
982 $allcats[$cat->parent]->children[$sortorder] = $cat;
f41ef63e 983 }
0cbe8111 984 unset($allcats);
39f65595 985
0cbe8111 986 // add broken cats to category tree
987 if ($brokencats) {
988 $defaultcat = reset($topcats);
989 foreach ($brokencats as $cat) {
990 $topcats[] = $cat;
a1b892cc 991 }
ba87a4da 992 }
993
0cbe8111 994 // now walk recursively the tree and fix any problems found
995 $sortorder = 0;
996 $fixcontexts = array();
997 _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
998
999 // detect if there are "multiple" frontpage courses and fix them if needed
1000 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
1001 if (count($frontcourses) > 1) {
1002 if (isset($frontcourses[SITEID])) {
1003 $frontcourse = $frontcourses[SITEID];
1004 unset($frontcourses[SITEID]);
1005 } else {
1006 $frontcourse = array_shift($frontcourses);
1007 }
1008 $defaultcat = reset($topcats);
1009 foreach ($frontcourses as $course) {
1010 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
1011 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1012 $fixcontexts[$context->id] = $context;
1013 }
1014 unset($frontcourses);
1015 } else {
1016 $frontcourse = reset($frontcourses);
814748c9 1017 }
1018
0cbe8111 1019 // now fix the paths and depths in context table if needed
1020 if ($fixcontexts) {
1021 rebuild_contexts($fixcontexts);
39f65595 1022 }
5930cded 1023
0cbe8111 1024 // release memory
1025 unset($topcats);
1026 unset($brokencats);
1027 unset($fixcontexts);
1028
1029 // fix frontpage course sortorder
1030 if ($frontcourse->sortorder != 1) {
1031 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
39f65595 1032 }
1033
0cbe8111 1034 // now fix the course counts in category records if needed
1035 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1036 FROM {course_categories} cc
1037 LEFT JOIN {course} c ON c.category = cc.id
1038 GROUP BY cc.id, cc.coursecount
1039 HAVING cc.coursecount <> COUNT(c.id)";
ba87a4da 1040
0cbe8111 1041 if ($updatecounts = $DB->get_records_sql($sql)) {
1042 foreach ($updatecounts as $cat) {
1043 $cat->coursecount = $cat->newcount;
1044 unset($cat->newcount);
1045 $DB->update_record_raw('course_categories', $cat, true);
a1b892cc 1046 }
02ebf404 1047 }
8f0cd6ef 1048
0cbe8111 1049 // now make sure that sortorders in course table are withing the category sortorder ranges
8ed5dd63 1050 $sql = "SELECT DISTINCT cc.id, cc.sortorder
0cbe8111 1051 FROM {course_categories} cc
1052 JOIN {course} c ON c.category = cc.id
1053 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1054
1055 if ($fixcategories = $DB->get_records_sql($sql)) {
1056 //fix the course sortorder ranges
1057 foreach ($fixcategories as $cat) {
1058 $sql = "UPDATE {course}
78a0635c 1059 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
0cbe8111 1060 WHERE category = ?";
1061 $DB->execute($sql, array($cat->sortorder, $cat->id));
1062 }
814748c9 1063 }
0cbe8111 1064 unset($fixcategories);
1065
1066 // categories having courses with sortorder duplicates or having gaps in sortorder
1067 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1068 FROM {course} c1
1069 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1070 JOIN {course_categories} cc ON (c1.category = cc.id)
1071 WHERE c1.id <> c2.id";
1072 $fixcategories = $DB->get_records_sql($sql);
1073
1074 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1075 FROM {course_categories} cc
1076 JOIN {course} c ON c.category = cc.id
1077 GROUP BY cc.id, cc.sortorder, cc.coursecount
1078 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1079 $gapcategories = $DB->get_records_sql($sql);
1080
1081 foreach ($gapcategories as $cat) {
1082 if (isset($fixcategories[$cat->id])) {
1083 // duplicates detected already
1084
1085 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1086 // easy - new course inserted with sortorder 0, the rest is ok
1087 $sql = "UPDATE {course}
1088 SET sortorder = sortorder + 1
1089 WHERE category = ?";
1090 $DB->execute($sql, array($cat->id));
758b9a4d 1091
0cbe8111 1092 } else {
1093 // it needs full resorting
1094 $fixcategories[$cat->id] = $cat;
6bc502cc 1095 }
1096 }
0cbe8111 1097 unset($gapcategories);
8f0cd6ef 1098
0cbe8111 1099 // fix course sortorders in problematic categories only
1100 foreach ($fixcategories as $cat) {
1101 $i = 1;
1102 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1103 foreach ($courses as $course) {
1104 if ($course->sortorder != $cat->sortorder + $i) {
1105 $course->sortorder = $cat->sortorder + $i;
a1b892cc 1106 $DB->update_record_raw('course', $course, true);
0cbe8111 1107 }
1108 $i++;
1109 }
1110 }
02ebf404 1111}
1112
d8634192 1113/**
0cbe8111 1114 * Internal recursive category verification function, do not use directly!
3564771d 1115 *
1116 * @todo Document the arguments of this function better
1117 *
1118 * @global object
1119 * @uses MAX_COURSES_IN_CATEGORY
1120 * @uses CONTEXT_COURSECAT
1121 * @param array $children
1122 * @param int $sortorder
1123 * @param string $parent
1124 * @param int $depth
1125 * @param string $path
1126 * @param array $fixcontexts
1127 * @return void
0cbe8111 1128 */
1129function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
c3df0901 1130 global $DB;
d8634192 1131
0cbe8111 1132 $depth++;
c3df0901 1133
0cbe8111 1134 foreach ($children as $cat) {
1135 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1136 $update = false;
1137 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1138 $cat->parent = $parent;
1139 $cat->depth = $depth;
1140 $cat->path = $path.'/'.$cat->id;
1141 $update = true;
c3df0901 1142
0cbe8111 1143 // make sure context caches are rebuild and dirty contexts marked
1144 $context = get_context_instance(CONTEXT_COURSECAT, $cat->id);
1145 $fixcontexts[$context->id] = $context;
1146 }
1147 if ($cat->sortorder != $sortorder) {
1148 $cat->sortorder = $sortorder;
1149 $update = true;
1150 }
1151 if ($update) {
1152 $DB->update_record('course_categories', $cat, true);
1153 }
1154 if (isset($cat->children)) {
1155 _fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts);
d8634192 1156 }
1157 }
1158}
1159
db4b12eb 1160/**
1161 * List of remote courses that a user has access to via MNET.
1162 * Works only on the IDP
1163 *
3564771d 1164 * @global object
1165 * @global object
1166 * @param int @userid The user id to get remote courses for
1167 * @return array Array of {@link $COURSE} of course objects
db4b12eb 1168 */
1169function get_my_remotecourses($userid=0) {
c3df0901 1170 global $DB, $USER;
db4b12eb 1171
1172 if (empty($userid)) {
1173 $userid = $USER->id;
1174 }
1175
c6575bef
DM
1176 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1177 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
152a2273 1178 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
86dd62a7 1179 h.name AS hostname
152a2273 1180 FROM {mnetservice_enrol_courses} c
c6575bef
DM
1181 JOIN (SELECT DISTINCT hostid, remotecourseid
1182 FROM {mnetservice_enrol_enrolments}
1183 WHERE userid = ?
1184 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1185 JOIN {mnet_host} h ON h.id = c.hostid";
db4b12eb 1186
c3df0901 1187 return $DB->get_records_sql($sql, array($userid));
db4b12eb 1188}
1189
1190/**
1191 * List of remote hosts that a user has access to via MNET.
1192 * Works on the SP
1193 *
3564771d 1194 * @global object
1195 * @global object
1196 * @return array|bool Array of host objects or false
db4b12eb 1197 */
1198function get_my_remotehosts() {
1199 global $CFG, $USER;
1200
1201 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1202 return false; // Return nothing on the IDP
1203 }
1204 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1205 return $USER->mnet_foreign_host_array;
1206 }
1207 return false;
1208}
fbc21ae8 1209
18a97fd8 1210/**
fbc21ae8 1211 * This function creates a default separated/connected scale
1212 *
1213 * This function creates a default separated/connected scale
1214 * so there's something in the database. The locations of
1215 * strings and files is a bit odd, but this is because we
1216 * need to maintain backward compatibility with many different
1217 * existing language translations and older sites.
3564771d 1218 *
1219 * @global object
3564771d 1220 * @return void
fbc21ae8 1221 */
02ebf404 1222function make_default_scale() {
2d0f7da8 1223 global $DB;
02ebf404 1224
1225 $defaultscale = NULL;
1226 $defaultscale->courseid = 0;
1227 $defaultscale->userid = 0;
d4419d55 1228 $defaultscale->name = get_string('separateandconnected');
2d0f7da8 1229 $defaultscale->description = get_string('separateandconnectedinfo');
d4419d55 1230 $defaultscale->scale = get_string('postrating1', 'forum').','.
1231 get_string('postrating2', 'forum').','.
1232 get_string('postrating3', 'forum');
02ebf404 1233 $defaultscale->timemodified = time();
1234
a9637e7d
PS
1235 $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1236 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
02ebf404 1237}
1238
fbc21ae8 1239
18a97fd8 1240/**
fbc21ae8 1241 * Returns a menu of all available scales from the site as well as the given course
1242 *
3564771d 1243 * @global object
fbc21ae8 1244 * @param int $courseid The id of the course as found in the 'course' table.
3564771d 1245 * @return array
fbc21ae8 1246 */
02ebf404 1247function get_scales_menu($courseid=0) {
c3df0901 1248 global $DB;
02ebf404 1249
c3df0901 1250 $sql = "SELECT id, name
1251 FROM {scale}
1252 WHERE courseid = 0 or courseid = ?
02ebf404 1253 ORDER BY courseid ASC, name ASC";
c3df0901 1254 $params = array($courseid);
02ebf404 1255
c3df0901 1256 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
02ebf404 1257 return $scales;
1258 }
1259
1260 make_default_scale();
1261
c3df0901 1262 return $DB->get_records_sql_menu($sql, $params);
02ebf404 1263}
1264
5baa0ad6 1265
1266
1267/**
1268 * Given a set of timezone records, put them in the database, replacing what is there
1269 *
3564771d 1270 * @global object
5baa0ad6 1271 * @param array $timezones An array of timezone records
3564771d 1272 * @return void
5baa0ad6 1273 */
1274function update_timezone_records($timezones) {
c3df0901 1275 global $DB;
5baa0ad6 1276
1277/// Clear out all the old stuff
b820eb8c 1278 $DB->delete_records('timezone');
5baa0ad6 1279
1280/// Insert all the new stuff
1281 foreach ($timezones as $timezone) {
a599aeeb 1282 if (is_array($timezone)) {
1283 $timezone = (object)$timezone;
1284 }
c3df0901 1285 $DB->insert_record('timezone', $timezone);
5baa0ad6 1286 }
1287}
1288
1289
df28d6c5 1290/// MODULE FUNCTIONS /////////////////////////////////////////////////
1291
18a97fd8 1292/**
fbc21ae8 1293 * Just gets a raw list of all modules in a course
1294 *
3564771d 1295 * @global object
fbc21ae8 1296 * @param int $courseid The id of the course as found in the 'course' table.
3564771d 1297 * @return array
fbc21ae8 1298 */
9fa49e22 1299function get_course_mods($courseid) {
c3df0901 1300 global $DB;
9fa49e22 1301
3a11c548 1302 if (empty($courseid)) {
1303 return false; // avoid warnings
1304 }
1305
c3df0901 1306 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1307 FROM {modules} m, {course_modules} cm
1308 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1309 array($courseid)); // no disabled mods
9fa49e22 1310}
1311
fbc21ae8 1312
18a97fd8 1313/**
f9d5371b 1314 * Given an id of a course module, finds the coursemodule description
fbc21ae8 1315 *
3564771d 1316 * @global object
a1b892cc 1317 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
f9d5371b 1318 * @param int $cmid course module id (id in course_modules table)
1319 * @param int $courseid optional course id for extra validation
a1b892cc 1320 * @param bool $sectionnum include relative section number (0,1,2 ...)
4fea29e4 1321 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1322 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1323 * MUST_EXIST means throw exception if no record or multiple records found
83be47e6 1324 * @return stdClass
f9d5371b 1325 */
4fea29e4 1326function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
c3df0901 1327 global $DB;
f9d5371b 1328
a1b892cc 1329 $params = array('cmid'=>$cmid);
1330
1331 if (!$modulename) {
1332 if (!$modulename = $DB->get_field_sql("SELECT md.name
1333 FROM {modules} md
1334 JOIN {course_modules} cm ON cm.module = md.id
4fea29e4 1335 WHERE cm.id = :cmid", $params, $strictness)) {
a1b892cc 1336 return false;
1337 }
1338 }
1339
1340 $params['modulename'] = $modulename;
1341
d251907c 1342 $courseselect = "";
a1b892cc 1343 $sectionfield = "";
1344 $sectionjoin = "";
f9d5371b 1345
c3df0901 1346 if ($courseid) {
a1b892cc 1347 $courseselect = "AND cm.course = :courseid";
c3df0901 1348 $params['courseid'] = $courseid;
d251907c 1349 }
c3df0901 1350
a1b892cc 1351 if ($sectionnum) {
1352 $sectionfield = ", cw.section AS sectionnum";
1353 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1354 }
1355
1356 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1357 FROM {course_modules} cm
1358 JOIN {modules} md ON md.id = cm.module
1359 JOIN {".$modulename."} m ON m.id = cm.instance
1360 $sectionjoin
1361 WHERE cm.id = :cmid AND md.name = :modulename
1362 $courseselect";
1363
4fea29e4 1364 return $DB->get_record_sql($sql, $params, $strictness);
f9d5371b 1365}
1366
1367/**
1368 * Given an instance number of a module, finds the coursemodule description
1369 *
3564771d 1370 * @global object
f9d5371b 1371 * @param string $modulename name of module type, eg. resource, assignment,...
1372 * @param int $instance module instance number (id in resource, assignment etc. table)
1373 * @param int $courseid optional course id for extra validation
a1b892cc 1374 * @param bool $sectionnum include relative section number (0,1,2 ...)
4fea29e4 1375 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1376 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1377 * MUST_EXIST means throw exception if no record or multiple records found
83be47e6 1378 * @return stdClass
fbc21ae8 1379 */
4fea29e4 1380function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
c3df0901 1381 global $DB;
df28d6c5 1382
a1b892cc 1383 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1384
d251907c 1385 $courseselect = "";
a1b892cc 1386 $sectionfield = "";
1387 $sectionjoin = "";
df28d6c5 1388
c3df0901 1389 if ($courseid) {
a1b892cc 1390 $courseselect = "AND cm.course = :courseid";
c3df0901 1391 $params['courseid'] = $courseid;
d251907c 1392 }
c3df0901 1393
a1b892cc 1394 if ($sectionnum) {
1395 $sectionfield = ", cw.section AS sectionnum";
1396 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1397 }
1398
1399 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1400 FROM {course_modules} cm
1401 JOIN {modules} md ON md.id = cm.module
1402 JOIN {".$modulename."} m ON m.id = cm.instance
1403 $sectionjoin
1404 WHERE m.id = :instance AND md.name = :modulename
1405 $courseselect";
df28d6c5 1406
4fea29e4 1407 return $DB->get_record_sql($sql, $params, $strictness);
df28d6c5 1408}
1409
dd97c328 1410/**
1411 * Returns all course modules of given activity in course
3564771d 1412 *
1413 * @param string $modulename The module name (forum, quiz, etc.)
1414 * @param int $courseid The course id to get modules for
dd97c328 1415 * @param string $extrafields extra fields starting with m.
3564771d 1416 * @return array Array of results
dd97c328 1417 */
1418function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
c3df0901 1419 global $DB;
dd97c328 1420
1421 if (!empty($extrafields)) {
1422 $extrafields = ", $extrafields";
1423 }
c3df0901 1424 $params = array();
1425 $params['courseid'] = $courseid;
1426 $params['modulename'] = $modulename;
1427
1428
1429 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1430 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1431 WHERE cm.course = :courseid AND
1432 cm.instance = m.id AND
1433 md.name = :modulename AND
e0985504 1434 md.id = cm.module", $params);
dd97c328 1435}
ac0b1a19 1436
185cfb09 1437/**
1438 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1439 *
1440 * Returns an array of all the active instances of a particular
1441 * module in given courses, sorted in the order they are defined
ac0b1a19 1442 * in the course. Returns an empty array on any errors.
185cfb09 1443 *
ac0b1a19 1444 * The returned objects includle the columns cw.section, cm.visible,
1445 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1446 *
3564771d 1447 * @global object
1448 * @global object
ac0b1a19 1449 * @param string $modulename The name of the module to get instances for
1450 * @param array $courses an array of course objects.
3564771d 1451 * @param int $userid
1452 * @param int $includeinvisible
ac0b1a19 1453 * @return array of module instance objects, including some extra fields from the course_modules
1454 * and course_sections tables, or an empty array if an error occurred.
185cfb09 1455 */
00e12c73 1456function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
c3df0901 1457 global $CFG, $DB;
ac0b1a19 1458
1459 $outputarray = array();
1460
185cfb09 1461 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
ac0b1a19 1462 return $outputarray;
185cfb09 1463 }
ac0b1a19 1464
c3df0901 1465 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1466 $params['modulename'] = $modulename;
1467
1468 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1469 cm.groupmode, cm.groupingid, cm.groupmembersonly
1470 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1471 {".$modulename."} m
1472 WHERE cm.course $coursessql AND
1473 cm.instance = m.id AND
1474 cm.section = cw.id AND
1475 md.name = :modulename AND
1476 md.id = cm.module", $params)) {
ac0b1a19 1477 return $outputarray;
185cfb09 1478 }
1479
185cfb09 1480 foreach ($courses as $course) {
ac0b1a19 1481 $modinfo = get_fast_modinfo($course, $userid);
fea43a7f 1482
ac0b1a19 1483 if (empty($modinfo->instances[$modulename])) {
185cfb09 1484 continue;
1485 }
ac0b1a19 1486
1487 foreach ($modinfo->instances[$modulename] as $cm) {
1488 if (!$includeinvisible and !$cm->uservisible) {
1489 continue;
1490 }
1491 if (!isset($rawmods[$cm->id])) {
1492 continue;
185cfb09 1493 }
ac0b1a19 1494 $instance = $rawmods[$cm->id];
1495 if (!empty($cm->extra)) {
9a9012dc 1496 $instance->extra = $cm->extra;
ac0b1a19 1497 }
1498 $outputarray[] = $instance;
185cfb09 1499 }
1500 }
1501
1502 return $outputarray;
185cfb09 1503}
fbc21ae8 1504
18a97fd8 1505/**
3d96cba7 1506 * Returns an array of all the active instances of a particular module in a given course,
1507 * sorted in the order they are defined.
fbc21ae8 1508 *
1509 * Returns an array of all the active instances of a particular
1510 * module in a given course, sorted in the order they are defined
3d96cba7 1511 * in the course. Returns an empty array on any errors.
1512 *
1513 * The returned objects includle the columns cw.section, cm.visible,
ac0b1a19 1514 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
fbc21ae8 1515 *
3564771d 1516 * Simply calls {@link all_instances_in_courses()} with a single provided course
1517 *
3d96cba7 1518 * @param string $modulename The name of the module to get instances for
ac0b1a19 1519 * @param object $course The course obect.
3d96cba7 1520 * @return array of module instance objects, including some extra fields from the course_modules
1521 * and course_sections tables, or an empty array if an error occurred.
3564771d 1522 * @param int $userid
1523 * @param int $includeinvisible
fbc21ae8 1524 */
00e12c73 1525function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
ac0b1a19 1526 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
df28d6c5 1527}
1528
9fa49e22 1529
18a97fd8 1530/**
fbc21ae8 1531 * Determine whether a module instance is visible within a course
1532 *
1533 * Given a valid module object with info about the id and course,
1534 * and the module's type (eg "forum") returns whether the object
dd97c328 1535 * is visible or not, groupmembersonly visibility not tested
fbc21ae8 1536 *
3564771d 1537 * @global object
117bd748 1538
613bbd7c 1539 * @param $moduletype Name of the module eg 'forum'
1540 * @param $module Object which is the instance of the module
3564771d 1541 * @return bool Success
fbc21ae8 1542 */
580f2fbc 1543function instance_is_visible($moduletype, $module) {
c3df0901 1544 global $DB;
580f2fbc 1545
2b49ae96 1546 if (!empty($module->id)) {
d251907c 1547 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
c3df0901 1548 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1549 FROM {course_modules} cm, {modules} m
1550 WHERE cm.course = :courseid AND
1551 cm.module = m.id AND
1552 m.name = :moduletype AND
f93ea222 1553 cm.instance = :moduleid", $params)) {
5930cded 1554
2b49ae96 1555 foreach ($records as $record) { // there should only be one - use the first one
dd97c328 1556 return $record->visible;
2b49ae96 1557 }
580f2fbc 1558 }
1559 }
580f2fbc 1560 return true; // visible by default!
1561}
1562
dd97c328 1563/**
1564 * Determine whether a course module is visible within a course,
1565 * this is different from instance_is_visible() - faster and visibility for user
1566 *
3564771d 1567 * @global object
1568 * @global object
1569 * @uses DEBUG_DEVELOPER
1570 * @uses CONTEXT_MODULE
1571 * @uses CONDITION_MISSING_EXTRATABLE
dd97c328 1572 * @param object $cm object
1573 * @param int $userid empty means current user
3564771d 1574 * @return bool Success
dd97c328 1575 */
1576function coursemodule_visible_for_user($cm, $userid=0) {
82bd6a5e 1577 global $USER,$CFG;
dd97c328 1578
1579 if (empty($cm->id)) {
1580 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1581 return false;
1582 }
1583 if (empty($userid)) {
1584 $userid = $USER->id;
1585 }
1586 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1587 return false;
1588 }
82bd6a5e 1589 if ($CFG->enableavailability) {
1590 require_once($CFG->libdir.'/conditionlib.php');
1591 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
117bd748
PS
1592 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1593 !has_capability('moodle/course:viewhiddenactivities',
82bd6a5e 1594 get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1595 return false;
1596 }
1597 }
dd97c328 1598 return groups_course_module_visible($cm, $userid);
1599}
1600
a3fb1c45 1601
1602
1603
9fa49e22 1604/// LOG FUNCTIONS /////////////////////////////////////////////////////
1605
1606
18a97fd8 1607/**
fbc21ae8 1608 * Add an entry to the log table.
1609 *
1610 * Add an entry to the log table. These are "action" focussed rather
1611 * than web server hits, and provide a way to easily reconstruct what
1612 * any particular student has been doing.
1613 *
3564771d 1614 * @global object
1615 * @global object
1616 * @global object
fbc21ae8 1617 * @uses SITEID
3564771d 1618 * @uses DEBUG_DEVELOPER
1619 * @uses DEBUG_ALL
89dcb99d 1620 * @param int $courseid The course id
fbc21ae8 1621 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
f7664880 1622 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
fbc21ae8 1623 * @param string $url The file and parameters used to see the results of the action
1624 * @param string $info Additional description information
1625 * @param string $cm The course_module->id if there is one
1626 * @param string $user If log regards $user other than $USER
3564771d 1627 * @return void
fbc21ae8 1628 */
d4419d55 1629function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
e8395a09 1630 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1631 // This is for a good reason: it is the most frequently used DB update function,
1632 // so it has been optimised for speed.
f33e1ed4 1633 global $DB, $CFG, $USER;
9fa49e22 1634
7a5b1fc5 1635 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 1636 $cm = 0;
1637 }
1638
3d94772d 1639 if ($user) {
1640 $userid = $user;
1641 } else {
b7b64ff2 1642 if (session_is_loggedinas()) { // Don't log
3d94772d 1643 return;
1644 }
d4419d55 1645 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 1646 }
1647
f11f7b41
PS
1648 if (isset($CFG->logguests) and !$CFG->logguests) {
1649 if (!$userid or isguestuser($userid)) {
1650 return;
1651 }
1652 }
1653
fcaff7ff 1654 $REMOTE_ADDR = getremoteaddr();
1655
9fa49e22 1656 $timenow = time();
ac1ba33e 1657 $info = $info;
10a760b9 1658 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
8082d3ab 1659 $url = html_entity_decode($url);
10a760b9 1660 }
853df85e 1661
6c5a2108 1662 // Restrict length of log lines to the space actually available in the
1663 // database so that it doesn't cause a DB error. Log a warning so that
1664 // developers can avoid doing things which are likely to cause this on a
1665 // routine basis.
ac1ba33e 1666 $tl = textlib_get_instance();
6c5a2108 1667 if(!empty($info) && $tl->strlen($info)>255) {
ac1ba33e 1668 $info = $tl->substr($info,0,252).'...';
6c5a2108 1669 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1670 }
ac1ba33e 1671
6c5a2108 1672 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1673 if(!empty($url) && $tl->strlen($url)>100) {
1674 $url=$tl->substr($url,0,97).'...';
1675 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1676 }
8a445484 1677
f33e1ed4 1678 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
853df85e 1679
f33e1ed4 1680 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1681 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
9f064546 1682
8082d3ab
PS
1683 try {
1684 $DB->insert_record_raw('log', $log, false);
1685 } catch (dml_write_exception $e) {
252720c4 1686 debugging('Error: Could not insert a new entry to the Moodle log', DEBUG_ALL);
8082d3ab
PS
1687 // MDL-11893, alert $CFG->supportemail if insert into log failed
1688 if ($CFG->supportemail and empty($CFG->noemailever)) {
1689 // email_to_user is not usable because email_to_user tries to write to the logs table,
1690 // and this will get caught in an infinite loop, if disk is full
1691 $site = get_site();
1692 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1693 $message = "Insert into log table failed at ". date('l dS \of F Y h:i:s A') .".\n It is possible that your disk is full.\n\n";
1694 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1695
1696 $lasttime = get_config('admin', 'lastloginserterrormail');
1697 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1698 mail($CFG->supportemail, $subject, $message);
1699 set_config('lastloginserterrormail', time(), 'admin');
1700 }
1701 }
8f0cd6ef 1702 }
341b5ed2 1703}
1704
1705/**
1706 * Store user last access times - called when use enters a course or site
1707 *
3564771d 1708 * @global object
1709 * @global object
1710 * @global object
1711 * @uses LASTACCESS_UPDATE_SECS
1712 * @uses SITEID
341b5ed2 1713 * @param int $courseid, empty means site
1714 * @return void
1715 */
1716function user_accesstime_log($courseid=0) {
f33e1ed4 1717 global $USER, $CFG, $DB;
341b5ed2 1718
b7b64ff2 1719 if (!isloggedin() or session_is_loggedinas()) {
341b5ed2 1720 // no access tracking
1721 return;
1722 }
1723
1724 if (empty($courseid)) {
1725 $courseid = SITEID;
1726 }
1727
1728 $timenow = time();
1729
1730/// Store site lastaccess time for the current user
1731 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1732 /// Update $USER->lastaccess for next checks
1733 $USER->lastaccess = $timenow;
341b5ed2 1734
365a5941 1735 $last = new stdClass();
f33e1ed4 1736 $last->id = $USER->id;
1737 $last->lastip = getremoteaddr();
1738 $last->lastaccess = $timenow;
1739
68fbad44 1740 $DB->update_record_raw('user', $last);
341b5ed2 1741 }
1742
1743 if ($courseid == SITEID) {
1744 /// no user_lastaccess for frontpage
1745 return;
1746 }
cb8aaedf 1747
341b5ed2 1748/// Store course lastaccess times for the current user
1749 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
341b5ed2 1750
f33e1ed4 1751 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
341b5ed2 1752
f33e1ed4 1753 if ($lastaccess === false) {
1754 // Update course lastaccess for next checks
1755 $USER->currentcourseaccess[$courseid] = $timenow;
1756
365a5941 1757 $last = new stdClass();
f33e1ed4 1758 $last->userid = $USER->id;
1759 $last->courseid = $courseid;
1760 $last->timeaccess = $timenow;
68fbad44 1761 $DB->insert_record_raw('user_lastaccess', $last, false);
d251907c 1762
f33e1ed4 1763 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1764 // no need to update now, it was updated recently in concurrent login ;-)
341b5ed2 1765
f33e1ed4 1766 } else {
1767 // Update course lastaccess for next checks
1768 $USER->currentcourseaccess[$courseid] = $timenow;
1769
68fbad44 1770 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
3d94772d 1771 }
8f0cd6ef 1772 }
9fa49e22 1773}
1774
18a97fd8 1775/**
fbc21ae8 1776 * Select all log records based on SQL criteria
1777 *
3564771d 1778 * @todo Finish documenting this function
1779 *
1780 * @global object
fbc21ae8 1781 * @param string $select SQL select criteria
c3df0901 1782 * @param array $params named sql type params
fbc21ae8 1783 * @param string $order SQL order by clause to sort the records returned
1784 * @param string $limitfrom ?
1785 * @param int $limitnum ?
1786 * @param int $totalcount Passed in by reference.
7290c7fa 1787 * @return object
fbc21ae8 1788 */
c3df0901 1789function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1790 global $DB;
9fa49e22 1791
519d369f 1792 if ($order) {
c3df0901 1793 $order = "ORDER BY $order";
1794 }
1795
1796 $selectsql = "";
1797 $countsql = "";
1798
1799 if ($select) {
1800 $select = "WHERE $select";
519d369f 1801 }
1802
c3df0901 1803 $sql = "SELECT COUNT(*)
1804 FROM {log} l
1805 $select";
1806
1807 $totalcount = $DB->count_records_sql($sql, $params);
a2ddd957 1808
c3df0901 1809 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
d251907c 1810 FROM {log} l
c3df0901 1811 LEFT JOIN {user} u ON l.userid = u.id
d251907c 1812 $select
c3df0901 1813 $order";
519d369f 1814
c3df0901 1815 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
9fa49e22 1816}
1817
519d369f 1818
18a97fd8 1819/**
fbc21ae8 1820 * Select all log records for a given course and user
1821 *
3564771d 1822 * @todo Finish documenting this function
1823 *
1824 * @global object
2f87145b 1825 * @uses DAYSECS
fbc21ae8 1826 * @param int $userid The id of the user as found in the 'user' table.
1827 * @param int $courseid The id of the course as found in the 'course' table.
1828 * @param string $coursestart ?
fbc21ae8 1829 */
9fa49e22 1830function get_logs_usercourse($userid, $courseid, $coursestart) {
c3df0901 1831 global $DB;
9fa49e22 1832
c3df0901 1833 $params = array();
1834
1835 $courseselect = '';
da0c90c3 1836 if ($courseid) {
c3df0901 1837 $courseselect = "AND course = :courseid";
d251907c 1838 $params['courseid'] = $courseid;
da0c90c3 1839 }
c3df0901 1840 $params['userid'] = $userid;
d251907c 1841 $params['coursestart'] = $coursestart;
da0c90c3 1842
c3df0901 1843 return $DB->get_records_sql("SELECT FLOOR((time - :coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
1844 FROM {log}
1845 WHERE userid = :userid
1846 AND time > :coursestart $courseselect
1847 GROUP BY FLOOR((time - :coursestart)/". DAYSECS .")", $params);
9fa49e22 1848}
1849
18a97fd8 1850/**
fbc21ae8 1851 * Select all log records for a given course, user, and day
1852 *
3564771d 1853 * @global object
2f87145b 1854 * @uses HOURSECS
fbc21ae8 1855 * @param int $userid The id of the user as found in the 'user' table.
1856 * @param int $courseid The id of the course as found in the 'course' table.
1857 * @param string $daystart ?
7290c7fa 1858 * @return object
fbc21ae8 1859 */
9fa49e22 1860function get_logs_userday($userid, $courseid, $daystart) {
c3df0901 1861 global $DB;
1862
66a0612a 1863 $params = array($daystart, $userid, $daystart);
9fa49e22 1864
c3df0901 1865 $courseselect = '';
7e4a6488 1866 if ($courseid) {
66a0612a
SH
1867 $courseselect = "AND course = ?";
1868 $params[] = $courseid;
7e4a6488 1869 }
66a0612a 1870 $params[] = $daystart;
7e4a6488 1871
66a0612a 1872 return $DB->get_records_sql("SELECT FLOOR((time - ?)/". HOURSECS .") AS hour, COUNT(*) AS num
c3df0901 1873 FROM {log}
66a0612a
SH
1874 WHERE userid = ?
1875 AND time > ? $courseselect
1876 GROUP BY FLOOR((time - ?)/". HOURSECS .") ", $params);
9fa49e22 1877}
1878
b4bac9b6 1879/**
1880 * Returns an object with counts of failed login attempts
1881 *
8f0cd6ef 1882 * Returns information about failed login attempts. If the current user is
1883 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 1884 * number of accounts. For non-admins, only the attempts on the given user
1885 * are shown.
1886 *
3564771d 1887 * @global object
1888 * @uses CONTEXT_SYSTEM
4f0c2d00 1889 * @param string $mode Either 'admin' or 'everybody'
fbc21ae8 1890 * @param string $username The username we are searching for
1891 * @param string $lastlogin The date from which we are searching
1892 * @return int
b4bac9b6 1893 */
b4bac9b6 1894function count_login_failures($mode, $username, $lastlogin) {
c3df0901 1895 global $DB;
b4bac9b6 1896
c3df0901 1897 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1898 $select = "module='login' AND action='error' AND time > :lastlogin";
1899
365a5941 1900 $count = new stdClass();
b4bac9b6 1901
4f0c2d00 1902 if (is_siteadmin()) {
c3df0901 1903 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
1904 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
b4bac9b6 1905 return $count;
1906 }
4f0c2d00 1907 } else if ($mode == 'everybody') {
c3df0901 1908 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
b4bac9b6 1909 return $count;
1910 }
1911 }
1912 return NULL;
1913}
1914
1915
a3fb1c45 1916/// GENERAL HELPFUL THINGS ///////////////////////////////////
1917
18a97fd8 1918/**
fbc21ae8 1919 * Dump a given object's information in a PRE block.
1920 *
1921 * Mostly just used for debugging.
1922 *
1923 * @param mixed $object The data to be printed
3564771d 1924 * @return void OUtput is echo'd
fbc21ae8 1925 */
a3fb1c45 1926function print_object($object) {
9f4ec46d
MD
1927 echo '<pre class="notifytiny">';
1928 print_r($object); // Direct to output because some objects get too big for memory otherwise!
1929 echo '</pre>';
a3fb1c45 1930}
1931
62d4e774 1932/**
5930cded 1933 * This function is the official hook inside XMLDB stuff to delegate its debug to one
62d4e774 1934 * external function.
1935 *
1936 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1937 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1938 *
3564771d 1939 * @uses DEBUG_DEVELOPER
1940 * @param string $message string contains the error message
1941 * @param object $object object XMLDB object that fired the debug
62d4e774 1942 */
1943function xmldb_debug($message, $object) {
1944
92b564f4 1945 debugging($message, DEBUG_DEVELOPER);
62d4e774 1946}
1947
49860445 1948/**
3564771d 1949 * @global object
1950 * @uses CONTEXT_COURSECAT
df73f8d4 1951 * @return boolean Whether the user can create courses in any category in the system.
49860445 1952 */
1953function user_can_create_courses() {
c3df0901 1954 global $DB;
df73f8d4 1955 $catsrs = $DB->get_recordset('course_categories');
4d55255b 1956 foreach ($catsrs as $cat) {
df73f8d4 1957 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
1958 $catsrs->close();
1959 return true;
49860445 1960 }
1961 }
df73f8d4 1962 $catsrs->close();
1963 return false;
49860445 1964}