accesslib: get_user_courses_bycap() also returns categorypath
[moodle.git] / lib / datalib.php
CommitLineData
6078ba30 1<?php // $Id$
7cf1c7bd 2
3/**
4 * Library of functions for database manipulation.
5930cded 5 *
7cf1c7bd 6 * Other main libraries:
7 * - weblib.php - functions that produce web output
8 * - moodlelib.php - general-purpose Moodle functions
6159ce65 9 * @author Martin Dougiamas and many others
7cf1c7bd 10 * @version $Id$
89dcb99d 11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 12 * @package moodlecore
13 */
14
df28d6c5 15
5930cded 16/**
11a052a6 17 * Escape all dangerous characters in a data record
18 *
19 * $dataobject is an object containing needed data
20 * Run over each field exectuting addslashes() function
21 * to escape SQL unfriendly characters (e.g. quotes)
22 * Handy when writing back data read from the database
23 *
24 * @param $dataobject Object containing the database record
25 * @return object Same object with neccessary characters escaped
26 */
27function addslashes_object( $dataobject ) {
28 $a = get_object_vars( $dataobject);
29 foreach ($a as $key=>$value) {
30 $a[$key] = addslashes( $value );
31 }
32 return (object)$a;
33}
0892f7bd 34
df28d6c5 35/// USER DATABASE ////////////////////////////////////////////////
36
18a97fd8 37/**
fbc21ae8 38 * Returns $user object of the main admin user
20aeb4b8 39 * primary admin = admin with lowest role_assignment id among admins
fbc21ae8 40 * @uses $CFG
41 * @return object(admin) An associative array representing the admin user.
fbc21ae8 42 */
df28d6c5 43function get_admin () {
df28d6c5 44
45 global $CFG;
46
47 if ( $admins = get_admins() ) {
48 foreach ($admins as $admin) {
8f0cd6ef 49 return $admin; // ie the first one
df28d6c5 50 }
51 } else {
52 return false;
53 }
54}
55
18a97fd8 56/**
fbc21ae8 57 * Returns list of all admins
58 *
59 * @uses $CFG
7290c7fa 60 * @return object
fbc21ae8 61 */
df28d6c5 62function get_admins() {
df28d6c5 63
64 global $CFG;
5930cded 65
20aeb4b8 66 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
df28d6c5 67
41f6ed56 68 return get_users_by_capability($context, 'moodle/site:doanything', 'u.*, ra.id as adminid', 'ra.id ASC'); // only need first one
5930cded 69
df28d6c5 70}
71
72
b61efafb 73function get_courses_in_metacourse($metacourseid) {
74 global $CFG;
75
5f37b628 76 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
5afa0de6 77 AND mc.child_course = c.id ORDER BY c.shortname";
b61efafb 78
79 return get_records_sql($sql);
80}
81
82function get_courses_notin_metacourse($metacourseid,$count=false) {
83
84 global $CFG;
85
b61efafb 86 if ($count) {
87 $sql = "SELECT COUNT(c.id)";
c44d5d42 88 } else {
b61efafb 89 $sql = "SELECT c.id,c.shortname,c.fullname";
90 }
178ccd11 91
ffed6bf3 92 $alreadycourses = get_courses_in_metacourse($metacourseid);
5930cded 93
c44d5d42 94 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
5afa0de6 95 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
5930cded 96
b61efafb 97 return get_records_sql($sql);
98}
99
493cde24 100function count_courses_notin_metacourse($metacourseid) {
101 global $CFG;
102
103 $alreadycourses = get_courses_in_metacourse($metacourseid);
104
69cd298a 105 $sql = "SELECT COUNT(c.id) AS notin FROM {$CFG->prefix}course c
493cde24 106 WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
107 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1";
108
69cd298a 109 if (!$count = get_record_sql($sql)) {
493cde24 110 return 0;
111 }
112
69cd298a 113 return $count->notin;
493cde24 114}
115
900df8b6 116/**
fbc21ae8 117 * Search through course users
118 *
5930cded 119 * If $coursid specifies the site course then this function searches
fbc21ae8 120 * through all undeleted and confirmed users
121 *
122 * @uses $CFG
123 * @uses SITEID
124 * @param int $courseid The course in question.
125 * @param int $groupid The group in question.
126 * @param string $searchtext ?
127 * @param string $sort ?
5930cded 128 * @param string $exceptions ?
7290c7fa 129 * @return object
fbc21ae8 130 */
900df8b6 131function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
132 global $CFG;
0720313b 133
29daf3a0 134 $LIKE = sql_ilike();
135 $fullname = sql_fullname('u.firstname', 'u.lastname');
8f0cd6ef 136
900df8b6 137 if (!empty($exceptions)) {
d4419d55 138 $except = ' AND u.id NOT IN ('. $exceptions .') ';
900df8b6 139 } else {
140 $except = '';
141 }
2700d113 142
900df8b6 143 if (!empty($sort)) {
d4419d55 144 $order = ' ORDER BY '. $sort;
900df8b6 145 } else {
146 $order = '';
147 }
8f0cd6ef 148
d4419d55 149 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
2700d113 150
222ac91b 151 if (!$courseid or $courseid == SITEID) {
2700d113 152 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
153 FROM {$CFG->prefix}user u
154 WHERE $select
900df8b6 155 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
2700d113 156 $except $order");
8f0cd6ef 157 } else {
2700d113 158
900df8b6 159 if ($groupid) {
f3f7610c 160//TODO:check. Remove group DB dependencies.
900df8b6 161 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 162 FROM {$CFG->prefix}user u,
1d684195 163 {$CFG->prefix}groups_members gm
164 WHERE $select AND gm.groupid = '$groupid' AND gm.userid = u.id
900df8b6 165 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
166 $except $order");
167 } else {
ea8158c1 168 $context = get_context_instance(CONTEXT_COURSE, $courseid);
169 $contextlists = get_related_contexts_string($context);
170 $users = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
8f0cd6ef 171 FROM {$CFG->prefix}user u,
ea8158c1 172 {$CFG->prefix}role_assignments ra
173 WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id
900df8b6 174 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
ea8158c1 175 $except $order");
900df8b6 176 }
ea8158c1 177 return $users;
900df8b6 178 }
df28d6c5 179}
180
2700d113 181
18a97fd8 182/**
fbc21ae8 183 * Returns a list of all site users
184 * Obsolete, just calls get_course_users(SITEID)
185 *
186 * @uses SITEID
c6d15803 187 * @deprecated Use {@link get_course_users()} instead.
fbc21ae8 188 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 189 * @return object|false {@link $USER} records or false if error.
fbc21ae8 190 */
d4419d55 191function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='') {
2d0b30a0 192
65ee9c16 193 return get_course_users(SITEID, $sort, $exceptions, $fields);
2d0b30a0 194}
195
9fa49e22 196
18a97fd8 197/**
fbc21ae8 198 * Returns a subset of users
199 *
200 * @uses $CFG
7290c7fa 201 * @param bool $get If false then only a count of the records is returned
fbc21ae8 202 * @param string $search A simple string to search for
7290c7fa 203 * @param bool $confirmed A switch to allow/disallow unconfirmed users
fbc21ae8 204 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
205 * @param string $sort A SQL snippet for the sorting criteria to use
206 * @param string $firstinitial ?
207 * @param string $lastinitial ?
208 * @param string $page ?
209 * @param string $recordsperpage ?
210 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 211 * @return object|false|int {@link $USER} records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.
fbc21ae8 212 */
d4419d55 213function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
36075e09 214 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*') {
18a97fd8 215
216 global $CFG;
5930cded 217
36075e09 218 if ($get && !$recordsperpage) {
219 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
220 'On large installations, this will probably cause an out of memory error. ' .
221 'Please think again and change your code so that it does not try to ' .
03517306 222 'load so much data into memory.', DEBUG_DEVELOPER);
36075e09 223 }
18a97fd8 224
29daf3a0 225 $LIKE = sql_ilike();
226 $fullname = sql_fullname();
e384fb7b 227
e8e0bb2d 228 $select = 'username <> \'guest\' AND deleted = 0';
488acd1b 229
0044147e 230 if (!empty($search)){
231 $search = trim($search);
488acd1b 232 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
e384fb7b 233 }
234
5a741655 235 if ($confirmed) {
d4419d55 236 $select .= ' AND confirmed = \'1\' ';
5a741655 237 }
238
239 if ($exceptions) {
d4419d55 240 $select .= ' AND id NOT IN ('. $exceptions .') ';
5a741655 241 }
242
488acd1b 243 if ($firstinitial) {
d4419d55 244 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
8f0cd6ef 245 }
488acd1b 246 if ($lastinitial) {
d4419d55 247 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
8f0cd6ef 248 }
488acd1b 249
5a741655 250 if ($get) {
36075e09 251 return get_records_select('user', $select, $sort, $fields, $page, $recordsperpage);
5a741655 252 } else {
36075e09 253 return count_records_select('user', $select);
5a741655 254 }
9fa49e22 255}
256
5a741655 257
18a97fd8 258/**
fbc21ae8 259 * shortdesc (optional)
260 *
261 * longdesc
262 *
263 * @uses $CFG
264 * @param string $sort ?
265 * @param string $dir ?
266 * @param int $categoryid ?
267 * @param int $categoryid ?
268 * @param string $search ?
269 * @param string $firstinitial ?
270 * @param string $lastinitial ?
7290c7fa 271 * @returnobject {@link $USER} records
fbc21ae8 272 * @todo Finish documenting this function
273 */
274
36075e09 275function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
03d820c7 276 $search='', $firstinitial='', $lastinitial='', $remotewhere='') {
488acd1b 277
9fa49e22 278 global $CFG;
31fefa63 279
29daf3a0 280 $LIKE = sql_ilike();
281 $fullname = sql_fullname();
c2a96d6b 282
e8e0bb2d 283 $select = "deleted <> '1'";
488acd1b 284
0044147e 285 if (!empty($search)) {
286 $search = trim($search);
39dc779a 287 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
488acd1b 288 }
289
290 if ($firstinitial) {
d4419d55 291 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
488acd1b 292 }
293
294 if ($lastinitial) {
d4419d55 295 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
c750592a 296 }
297
03d820c7 298 $select .= $remotewhere;
299
488acd1b 300 if ($sort) {
d4419d55 301 $sort = ' ORDER BY '. $sort .' '. $dir;
488acd1b 302 }
303
304/// warning: will return UNCONFIRMED USERS
03d820c7 305 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
8f0cd6ef 306 FROM {$CFG->prefix}user
422770d8 307 WHERE $select $sort", $page, $recordsperpage);
9fa49e22 308
309}
310
488acd1b 311
18a97fd8 312/**
7290c7fa 313 * Full list of users that have confirmed their accounts.
fbc21ae8 314 *
315 * @uses $CFG
7290c7fa 316 * @return object
fbc21ae8 317 */
9fa49e22 318function get_users_confirmed() {
319 global $CFG;
8f0cd6ef 320 return get_records_sql("SELECT *
321 FROM {$CFG->prefix}user
322 WHERE confirmed = 1
9fa49e22 323 AND deleted = 0
e8e0bb2d 324 AND username <> 'guest'");
9fa49e22 325}
326
327
18a97fd8 328/**
7290c7fa 329 * Full list of users that have not yet confirmed their accounts.
fbc21ae8 330 *
331 * @uses $CFG
332 * @param string $cutofftime ?
7290c7fa 333 * @return object {@link $USER} records
fbc21ae8 334 */
99988d1a 335function get_users_unconfirmed($cutofftime=2000000000) {
9fa49e22 336 global $CFG;
8f0cd6ef 337 return get_records_sql("SELECT *
338 FROM {$CFG->prefix}user
9fa49e22 339 WHERE confirmed = 0
8f0cd6ef 340 AND firstaccess > 0
cf36da64 341 AND firstaccess < $cutofftime");
9fa49e22 342}
343
613bbd7c 344/**
345 * All users that we have not seen for a really long time (ie dead accounts)
346 *
347 * @uses $CFG
348 * @param string $cutofftime ?
349 * @return object {@link $USER} records
613bbd7c 350 */
351function get_users_longtimenosee($cutofftime) {
352 global $CFG;
cc7c0592 353 return get_records_sql("SELECT userid as id, courseid
354 FROM {$CFG->prefix}user_lastaccess
cf36da64 355 WHERE courseid != ".SITEID."
356 AND timeaccess > 0
357 AND timeaccess < $cutofftime ");
613bbd7c 358}
9fa49e22 359
fa22fd5f 360/**
361 * Full list of bogus accounts that are probably not ever going to be used
362 *
363 * @uses $CFG
364 * @param string $cutofftime ?
365 * @return object {@link $USER} records
fa22fd5f 366 */
367
368function get_users_not_fully_set_up($cutofftime=2000000000) {
369 global $CFG;
370 return get_records_sql("SELECT *
371 FROM {$CFG->prefix}user
372 WHERE confirmed = 1
373 AND lastaccess > 0
cf36da64 374 AND lastaccess < $cutofftime
fa22fd5f 375 AND deleted = 0
376 AND (lastname = '' OR firstname = '' OR email = '')");
377}
378
02ebf404 379/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
380
381
18a97fd8 382/**
fbc21ae8 383 * Returns $course object of the top-level site.
384 *
89dcb99d 385 * @return course A {@link $COURSE} object for the site
fbc21ae8 386 */
c44d5d42 387function get_site() {
388
389 global $SITE;
390
391 if (!empty($SITE->id)) { // We already have a global to use, so return that
392 return $SITE;
393 }
02ebf404 394
c44d5d42 395 if ($course = get_record('course', 'category', 0)) {
02ebf404 396 return $course;
397 } else {
398 return false;
399 }
400}
401
18a97fd8 402/**
613bbd7c 403 * Returns list of courses, for whole site, or category
404 *
405 * Returns list of courses, for whole site, or category
406 * Important: Using c.* for fields is extremely expensive because
407 * we are using distinct. You almost _NEVER_ need all the fields
408 * in such a large SELECT
409 *
410 * @param type description
411 *
613bbd7c 412 */
6315b1c8 413function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 414
8ef9cb56 415 global $USER, $CFG;
5930cded 416
6315b1c8 417 if ($categoryid != "all" && is_numeric($categoryid)) {
71dea306 418 $categoryselect = "WHERE c.category = '$categoryid'";
419 } else {
5930cded 420 $categoryselect = "";
09575480 421 }
422
423 if (empty($sort)) {
424 $sortstatement = "";
425 } else {
426 $sortstatement = "ORDER BY $sort";
427 }
428
429 $visiblecourses = array();
5930cded 430
71dea306 431 // pull out all course matching the cat
5930cded 432 if ($courses = get_records_sql("SELECT $fields
433 FROM {$CFG->prefix}course c
71dea306 434 $categoryselect
09575480 435 $sortstatement")) {
436
437 // loop throught them
438 foreach ($courses as $course) {
439
285f94f5 440 if (isset($course->visible) && $course->visible <= 0) {
09575480 441 // for hidden courses, require visibility check
285f94f5 442 if (has_capability('moodle/course:viewhiddencourses',
443 get_context_instance(CONTEXT_COURSE, $course->id))) {
5930cded 444 $visiblecourses [] = $course;
09575480 445 }
446 } else {
5930cded 447 $visiblecourses [] = $course;
448 }
09575480 449 }
6315b1c8 450 }
71dea306 451 return $visiblecourses;
6315b1c8 452
71dea306 453/*
6315b1c8 454 $teachertable = "";
455 $visiblecourses = "";
456 $sqland = "";
457 if (!empty($categoryselect)) {
458 $sqland = "AND ";
459 }
460 if (!empty($USER->id)) { // May need to check they are a teacher
ae9e4c06 461 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6315b1c8 462 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
463 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
464 }
465 } else {
466 $visiblecourses = "$sqland c.visible > 0";
8ef9cb56 467 }
468
6315b1c8 469 if ($categoryselect or $visiblecourses) {
470 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
14f32609 471 } else {
6315b1c8 472 $selectsql = "{$CFG->prefix}course c $teachertable";
14f32609 473 }
474
5b66416f 475 $extrafield = str_replace('ASC','',$sort);
476 $extrafield = str_replace('DESC','',$extrafield);
477 $extrafield = trim($extrafield);
478 if (!empty($extrafield)) {
479 $extrafield = ','.$extrafield;
480 }
481 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
71dea306 482 */
8130b77b 483}
484
8130b77b 485
6315b1c8 486/**
613bbd7c 487 * Returns list of courses, for whole site, or category
488 *
489 * Similar to get_courses, but allows paging
5930cded 490 * Important: Using c.* for fields is extremely expensive because
613bbd7c 491 * we are using distinct. You almost _NEVER_ need all the fields
492 * in such a large SELECT
493 *
494 * @param type description
495 *
613bbd7c 496 */
6315b1c8 497function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
498 &$totalcount, $limitfrom="", $limitnum="") {
c7fe5c6f 499
8130b77b 500 global $USER, $CFG;
5930cded 501
71dea306 502 $categoryselect = "";
503 if ($categoryid != "all" && is_numeric($categoryid)) {
504 $categoryselect = "WHERE c.category = '$categoryid'";
505 } else {
5930cded 506 $categoryselect = "";
507 }
508
71dea306 509 // pull out all course matching the cat
12490fc2 510 $visiblecourses = array();
679b6179 511 if (!($rs = get_recordset_sql("SELECT $fields,
512 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth
513 FROM {$CFG->prefix}course c
514 JOIN {$CFG->prefix}context ctx
515 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
516 $categoryselect
517 ORDER BY $sort"))) {
12490fc2 518 return $visiblecourses;
519 }
71dea306 520 $totalcount = 0;
5930cded 521
71dea306 522 if (!$limitnum) {
679b6179 523 $limitnum = $rs->RecordCount();
71dea306 524 }
5930cded 525
285f94f5 526 if (!$limitfrom) {
5930cded 527 $limitfrom = 0;
71dea306 528 }
5930cded 529
71dea306 530 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
679b6179 531 if ($rs->RecordCount()) {
532 while ($course = rs_fetch_next_record($rs)) {
533 $course = make_context_subobj($course);
534 if ($course->visible <= 0) {
535 // for hidden courses, require visibility check
536 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
537 $totalcount++;
538 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
539 $visiblecourses [] = $course;
540 }
541 }
542 } else {
71dea306 543 $totalcount++;
544 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
545 $visiblecourses [] = $course;
546 }
547 }
5930cded 548 }
71dea306 549 }
71dea306 550 return $visiblecourses;
551
552/**
8130b77b 553
6315b1c8 554 $categoryselect = "";
b565bbdf 555 if ($categoryid != "all" && is_numeric($categoryid)) {
6315b1c8 556 $categoryselect = "c.category = '$categoryid'";
8130b77b 557 }
558
6315b1c8 559 $teachertable = "";
560 $visiblecourses = "";
561 $sqland = "";
562 if (!empty($categoryselect)) {
563 $sqland = "AND ";
c7fe5c6f 564 }
2d2da684 565 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
ae9e4c06 566 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6315b1c8 567 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
568 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
569 }
8130b77b 570 } else {
6315b1c8 571 $visiblecourses = "$sqland c.visible > 0";
8130b77b 572 }
573
6315b1c8 574 if ($limitfrom !== "") {
29daf3a0 575 $limit = sql_paging_limit($limitfrom, $limitnum);
6315b1c8 576 } else {
577 $limit = "";
02ebf404 578 }
8ef9cb56 579
6315b1c8 580 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
8ef9cb56 581
6315b1c8 582 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
8ef9cb56 583
2338ad32 584 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
71dea306 585 */
02ebf404 586}
587
588
18a97fd8 589/**
f8e1c7af 590 * List of courses that a user has access to view. Note that for admins,
591 * this usually includes every course on the system.
fbc21ae8 592 *
573674bf 593 * Notes (inherited from get_user_courses_bycap()):
e1d5e5c1 594 *
595 * - $fields is an array of fieldnames to ADD
596 * so name the fields you really need, which will
597 * be added and uniq'd
598 *
599 * - the course records have $c->context which is a fully
600 * valid context object. Saves you a query per course!
601 *
352f6f74 602 * @uses $CFG,$USER
7290c7fa 603 * @param int $userid The user of interest
33f85740 604 * @param string $sort the sortorder in the course table
e1d5e5c1 605 * @param array $fields - names of _additional_ fields to return (also accepts a string)
f8e1c7af 606 * @param bool $doanything True if using the doanything flag
607 * @param int $limit Maximum number of records to return, or 0 for unlimited
33f85740 608 * @return array {@link $COURSE} of course objects
fbc21ae8 609 */
e1d5e5c1 610function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
bdf3bbd1 611
352f6f74 612 global $CFG,$USER;
5930cded 613
4dbca99e 614 // Guest's do not have any courses
e1d5e5c1 615 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
61f774e8 616 if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
4dbca99e 617 return(array());
618 }
601edb90 619
352f6f74 620 $basefields = array('id', 'category', 'sortorder',
621 'shortname', 'fullname', 'idnumber',
622 'teacher', 'teachers', 'student', 'students',
623 'guest', 'startdate', 'visible',
624 'newsitems', 'cost', 'enrol',
625 'groupmode', 'groupmodeforce');
626
e1d5e5c1 627 if (!is_null($fields) && is_string($fields)) {
628 if (empty($fields)) {
352f6f74 629 $fields = $basefields;
e1d5e5c1 630 } else {
631 // turn the fields from a string to an array that
573674bf 632 // get_user_courses_bycap() will like...
352f6f74 633 $fields = explode(',',$fields);
634 $fields = array_map('trim', $fields);
635 $fields = array_unique(array_merge($basefields, $fields));
636 }
637 } else {
638 $fields = $basefields;
639 }
640
641 //
642 // Logged-in user - Check cached courses
643 //
644 // NOTE! it's a _string_ because
645 // - it's all we'll ever use
646 // - it serialises much more compact than an array
647 // this a BIG concern here - cost of serialise
648 // and unserialise is HUGE if the session grows
649 //
650 // If the courses are too many - it won't be set
651 // for large numbers of courses, caching in the session
652 // has marginal benefits (costs too much, not
653 // worthwhile...) and we may hit SQL parser limits
654 // because we use IN()
655 //
ae1555ae 656 if ($userid === $USER->id) {
fe3141e0 657 if (isset($USER->loginascontext)
658 && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
ae1555ae 659 // list _only_ this course
660 // anything else is asking for trouble...
661 $courseids = $USER->loginascontext->instanceid;
662 } elseif (isset($USER->mycourses)
663 && is_string($USER->mycourses)) {
664 if ($USER->mycourses === '') {
665 // empty str means: user has no courses
666 // ... so do the easy thing...
667 return array();
668 } else {
669 $courseids = $USER->mycourses;
670 }
671 }
672 if (isset($courseids)) {
352f6f74 673 // The data massaging here MUST be kept in sync with
674 // get_user_courses_bycap() so we return
675 // the same...
676 // (but here we don't need to check has_cap)
677 $coursefields = 'c.' .join(',c.', $fields);
678 $sql = "SELECT $coursefields,
679 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth
680 FROM {$CFG->prefix}course c
681 JOIN {$CFG->prefix}context ctx
682 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
ae1555ae 683 WHERE c.id IN ($courseids)
352f6f74 684 ORDER BY $sort";
685 $rs = get_recordset_sql($sql);
686 $courses = array();
687 $cc = 0; // keep count
688 if ($rs->RecordCount()) {
689 while ($c = rs_fetch_next_record($rs)) {
690 // build the context obj
c1b7a5e5 691 $c = make_context_subobj($c);
692
352f6f74 693 $courses[$c->id] = $c;
694 if ($limit > 0 && $cc++ > $limit) {
695 break;
696 }
697 }
698 }
699 rs_close($rs);
700 return $courses;
2f3499b7 701 }
702 }
152a9060 703
352f6f74 704 // Non-cached - get accessinfo
e1d5e5c1 705 if ($userid === $USER->id && isset($USER->access)) {
aeb3916b 706 $accessinfo = $USER->access;
bdf3bbd1 707 } else {
e1d5e5c1 708 $accessinfo = get_user_access_sitewide($userid);
aeb3916b 709 }
352f6f74 710
711
573674bf 712 $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
713 $doanything, $sort, $fields,
714 $limit);
352f6f74 715
716 //
717 // Strangely, get_my_courses() is expected to return the
aeb3916b 718 // array keyed on id, which messes up the sorting
352f6f74 719 // So do that, and also cache the ids in the session if appropriate
720 //
aeb3916b 721 $kcourses = array();
722 $cc = count($courses);
352f6f74 723 $cacheids = NULL;
724 if ($userid === $USER->id && $cc < 500) {
725 $cacheids = array();
726 }
aeb3916b 727 for ($n=0; $n<$cc; $n++) {
728 $kcourses[$courses[$n]->id] = $courses[$n];
352f6f74 729 if (is_array($cacheids)) {
730 $cacheids[] = $courses[$n]->id;
731 }
732 }
733 if (is_array($cacheids)) {
734 // Only happens
735 // - for the logged in user
736 // - below the threshold (500)
737 // empty string is _valid_
738 $USER->mycourses = join(',',$cacheids);
739 } elseif ($userid === $USER->id && isset($USER->mycourses)) {
740 // cheap sanity check
741 unset($USER->mycourses);
aeb3916b 742 }
352f6f74 743
aeb3916b 744 return $kcourses;
02ebf404 745}
746
18a97fd8 747/**
7290c7fa 748 * A list of courses that match a search
fbc21ae8 749 *
750 * @uses $CFG
751 * @param array $searchterms ?
752 * @param string $sort ?
753 * @param int $page ?
754 * @param int $recordsperpage ?
755 * @param int $totalcount Passed in by reference. ?
7290c7fa 756 * @return object {@link $COURSE} records
fbc21ae8 757 */
d4419d55 758function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
02ebf404 759
760 global $CFG;
761
18a97fd8 762 //to allow case-insensitive search for postgesql
48505662 763 if ($CFG->dbfamily == 'postgres') {
d4419d55 764 $LIKE = 'ILIKE';
765 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
766 $REGEXP = '~*';
767 $NOTREGEXP = '!~*';
02ebf404 768 } else {
d4419d55 769 $LIKE = 'LIKE';
770 $NOTLIKE = 'NOT LIKE';
771 $REGEXP = 'REGEXP';
772 $NOTREGEXP = 'NOT REGEXP';
02ebf404 773 }
774
d4419d55 775 $fullnamesearch = '';
776 $summarysearch = '';
02ebf404 777
02ebf404 778 foreach ($searchterms as $searchterm) {
6bb0f67f 779
780 /// Under Oracle and MSSQL, trim the + and - operators and perform
781 /// simpler LIKE search
48505662 782 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
6bb0f67f 783 $searchterm = trim($searchterm, '+-');
784 }
785
02ebf404 786 if ($fullnamesearch) {
d4419d55 787 $fullnamesearch .= ' AND ';
02ebf404 788 }
02ebf404 789 if ($summarysearch) {
d4419d55 790 $summarysearch .= ' AND ';
02ebf404 791 }
a8b56716 792
d4419d55 793 if (substr($searchterm,0,1) == '+') {
2c64f65c 794 $searchterm = substr($searchterm,1);
795 $summarysearch .= " c.summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
796 $fullnamesearch .= " c.fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
a8b56716 797 } else if (substr($searchterm,0,1) == "-") {
2c64f65c 798 $searchterm = substr($searchterm,1);
799 $summarysearch .= " c.summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
800 $fullnamesearch .= " c.fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
a8b56716 801 } else {
2c64f65c 802 $summarysearch .= ' c.summary '. $LIKE .' \'%'. $searchterm .'%\' ';
803 $fullnamesearch .= ' c.fullname '. $LIKE .' \'%'. $searchterm .'%\' ';
a8b56716 804 }
805
02ebf404 806 }
807
2c64f65c 808 $sql = "SELECT c.*,
809 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth
810 FROM {$CFG->prefix}course c
811 JOIN {$CFG->prefix}context ctx
812 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
813 WHERE ( $fullnamesearch OR $summarysearch )
814 AND category > 0
815 ORDER BY " . $sort;
02ebf404 816
2c64f65c 817 $courses = array();
02ebf404 818
2c64f65c 819 if ($rs = get_recordset_sql($sql)) {
820
821
822 // Tiki pagination
823 $limitfrom = $page * $recordsperpage;
824 $limitto = $limitfrom + $recordsperpage;
825 $c = 0; // counts how many visible courses we've seen
826
827 while ($course = rs_fetch_next_record($rs)) {
828 $course = make_context_subobj($course);
829 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) {
830 // Don't exit this loop till the end
831 // we need to count all the visible courses
832 // to update $totalcount
833 if ($c >= $limitfrom && $c < $limitto) {
834 $courses[] = $course;
02ebf404 835 }
2c64f65c 836 $c++;
02ebf404 837 }
838 }
839 }
840
2c64f65c 841 // our caller expects 2 bits of data - our return
842 // array, and an updated $totalcount
843 $totalcount = $c;
02ebf404 844 return $courses;
845}
846
847
18a97fd8 848/**
fbc21ae8 849 * Returns a sorted list of categories
850 *
613bbd7c 851 * @param string $parent The parent category if any
852 * @param string $sort the sortorder
853 * @return array of categories
fbc21ae8 854 */
d4419d55 855function get_categories($parent='none', $sort='sortorder ASC') {
02ebf404 856
814748c9 857 if ($parent === 'none') {
d4419d55 858 $categories = get_records('course_categories', '', '', $sort);
02ebf404 859 } else {
d4419d55 860 $categories = get_records('course_categories', 'parent', $parent, $sort);
02ebf404 861 }
862 if ($categories) { /// Remove unavailable categories from the list
02ebf404 863 foreach ($categories as $key => $category) {
152a9060 864 if (!$category->visible) {
115a622d 865 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $category->id))) {
02ebf404 866 unset($categories[$key]);
867 }
868 }
869 }
870 }
871 return $categories;
872}
873
874
2327b9df 875/**
876 * Returns an array of category ids of all the subcategories for a given
877 * category.
878 * @param $catid - The id of the category whose subcategories we want to find.
879 * @return array of category ids.
880 */
881function get_all_subcategories($catid) {
882
883 $subcats = array();
884
885 if ($categories = get_records('course_categories', 'parent', $catid)) {
886 foreach ($categories as $cat) {
887 array_push($subcats, $cat->id);
888 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
889 }
890 }
891 return $subcats;
892}
893
894
18a97fd8 895/**
ba87a4da 896* This recursive function makes sure that the courseorder is consecutive
897*
898* @param type description
899*
900* $n is the starting point, offered only for compatilibity -- will be ignored!
901* $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
902* safely from 1.4 to 1.5
903*/
f41ef63e 904function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
5930cded 905
ba87a4da 906 global $CFG;
8f0cd6ef 907
02ebf404 908 $count = 0;
5930cded 909
f41ef63e 910 $catgap = 1000; // "standard" category gap
911 $tolerance = 200; // how "close" categories can get
5930cded 912
f41ef63e 913 if ($categoryid > 0){
914 // update depth and path
915 $cat = get_record('course_categories', 'id', $categoryid);
916 if ($cat->parent == 0) {
917 $depth = 0;
918 $path = '';
919 } else if ($depth == 0 ) { // doesn't make sense; get from DB
920 // this is only called if the $depth parameter looks dodgy
921 $parent = get_record('course_categories', 'id', $cat->parent);
922 $path = $parent->path;
923 $depth = $parent->depth;
924 }
925 $path = $path . '/' . $categoryid;
926 $depth = $depth + 1;
ba87a4da 927
5930cded 928 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
929 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
f41ef63e 930 }
39f65595 931
932 // get some basic info about courses in the category
5930cded 933 $info = get_record_sql('SELECT MIN(sortorder) AS min,
ba87a4da 934 MAX(sortorder) AS max,
5930cded 935 COUNT(sortorder) AS count
936 FROM ' . $CFG->prefix . 'course
ba87a4da 937 WHERE category=' . $categoryid);
938 if (is_object($info)) { // no courses?
939 $max = $info->max;
940 $count = $info->count;
941 $min = $info->min;
942 unset($info);
943 }
944
814748c9 945 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
946 $n = $min;
947 }
948
39f65595 949 // $hasgap flag indicates whether there's a gap in the sequence
5930cded 950 $hasgap = false;
39f65595 951 if ($max-$min+1 != $count) {
952 $hasgap = true;
953 }
5930cded 954
39f65595 955 // $mustshift indicates whether the sequence must be shifted to
956 // meet its range
957 $mustshift = false;
958 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
959 $mustshift = true;
960 }
961
ba87a4da 962 // actually sort only if there are courses,
963 // and we meet one ofthe triggers:
964 // - safe flag
965 // - they are not in a continuos block
966 // - they are too close to the 'bottom'
39f65595 967 if ($count && ( $safe || $hasgap || $mustshift ) ) {
968 // special, optimized case where all we need is to shift
969 if ( $mustshift && !$safe && !$hasgap) {
970 $shift = $n + $catgap - $min;
f8ea6077 971 if ($shift < $count) {
972 $shift = $count + $catgap;
973 }
39f65595 974 // UPDATE course SET sortorder=sortorder+$shift
5930cded 975 execute_sql("UPDATE {$CFG->prefix}course
976 SET sortorder=sortorder+$shift
39f65595 977 WHERE category=$categoryid", 0);
5930cded 978 $n = $n + $catgap + $count;
979
39f65595 980 } else { // do it slowly
5930cded 981 $n = $n + $catgap;
39f65595 982 // if the new sequence overlaps the current sequence, lack of transactions
983 // will stop us -- shift things aside for a moment...
48505662 984 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
d6a49dab 985 $shift = $max + $n + 1000;
5930cded 986 execute_sql("UPDATE {$CFG->prefix}course
987 SET sortorder=sortorder+$shift
39f65595 988 WHERE category=$categoryid", 0);
ba87a4da 989 }
990
39f65595 991 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
992 begin_sql();
f8ea6077 993 $tx = true; // transaction sanity
5930cded 994 foreach ($courses as $course) {
f8ea6077 995 if ($tx && $course->sortorder != $n ) { // save db traffic
996 $tx = $tx && set_field('course', 'sortorder', $n,
997 'id', $course->id);
ba87a4da 998 }
999 $n++;
1000 }
f8ea6077 1001 if ($tx) {
1002 commit_sql();
1003 } else {
1004 rollback_sql();
1005 if (!$safe) {
1006 // if we failed when called with !safe, try
1007 // to recover calling self with safe=true
1008 return fix_course_sortorder($categoryid, $n, true, $depth, $path);
1009 }
1010 }
5930cded 1011 }
02ebf404 1012 }
d4419d55 1013 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
8f0cd6ef 1014
5930cded 1015 // $n could need updating
814748c9 1016 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
1017 if ($max > $n) {
1018 $n = $max;
1019 }
758b9a4d 1020
6bc502cc 1021 if ($categories = get_categories($categoryid)) {
1022 foreach ($categories as $category) {
f41ef63e 1023 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
6bc502cc 1024 }
1025 }
8f0cd6ef 1026
39f65595 1027 return $n+1;
02ebf404 1028}
1029
d8634192 1030/**
1031 * Ensure all courses have a valid course category
1032 * useful if a category has been removed manually
1033 **/
1034function fix_coursecategory_orphans() {
1035
1036 global $CFG;
1037
1038 // Note: the handling of sortorder here is arguably
1039 // open to race conditions. Hard to fix here, unlikely
1040 // to hit anyone in production.
1041
1042 $sql = "SELECT c.id, c.category, c.shortname
1043 FROM {$CFG->prefix}course c
1044 LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id
1045 WHERE cc.id IS NULL AND c.id != " . SITEID;
1046
1047 $rs = get_recordset_sql($sql);
1048
1049 if ($rs->RecordCount()){ // we have some orphans
1050
1051 // the "default" category is the lowest numbered...
1052 $default = get_field_sql("SELECT MIN(id)
1053 FROM {$CFG->prefix}course_categories");
1054 $sortorder = get_field_sql("SELECT MAX(sortorder)
1055 FROM {$CFG->prefix}course
1056 WHERE category=$default");
1057
1058
1059 begin_sql();
1060 $tx = true;
1061 while ($tx && $course = rs_fetch_next_record($rs)) {
1062 $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
1063 $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
1064 }
1065 if ($tx) {
1066 commit_sql();
1067 } else {
1068 rollback_sql();
1069 }
1070 }
1071}
1072
db4b12eb 1073/**
1074 * List of remote courses that a user has access to via MNET.
1075 * Works only on the IDP
1076 *
1077 * @uses $CFG, $USER
1078 * @return array {@link $COURSE} of course objects
1079 */
1080function get_my_remotecourses($userid=0) {
1081 global $CFG, $USER;
1082
1083 if (empty($userid)) {
1084 $userid = $USER->id;
1085 }
1086
5930cded 1087 $sql = "SELECT c.remoteid, c.shortname, c.fullname,
86dd62a7 1088 c.hostid, c.summary, c.cat_name,
1089 h.name AS hostname
db4b12eb 1090 FROM {$CFG->prefix}mnet_enrol_course c
1091 JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid
86dd62a7 1092 JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id
db4b12eb 1093 WHERE a.userid={$userid}";
1094
1095 return get_records_sql($sql);
1096}
1097
1098/**
1099 * List of remote hosts that a user has access to via MNET.
1100 * Works on the SP
1101 *
1102 * @uses $CFG, $USER
1103 * @return array of host objects
1104 */
1105function get_my_remotehosts() {
1106 global $CFG, $USER;
1107
1108 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1109 return false; // Return nothing on the IDP
1110 }
1111 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1112 return $USER->mnet_foreign_host_array;
1113 }
1114 return false;
1115}
fbc21ae8 1116
18a97fd8 1117/**
fbc21ae8 1118 * This function creates a default separated/connected scale
1119 *
1120 * This function creates a default separated/connected scale
1121 * so there's something in the database. The locations of
1122 * strings and files is a bit odd, but this is because we
1123 * need to maintain backward compatibility with many different
1124 * existing language translations and older sites.
1125 *
1126 * @uses $CFG
1127 */
02ebf404 1128function make_default_scale() {
02ebf404 1129
1130 global $CFG;
1131
1132 $defaultscale = NULL;
1133 $defaultscale->courseid = 0;
1134 $defaultscale->userid = 0;
d4419d55 1135 $defaultscale->name = get_string('separateandconnected');
1136 $defaultscale->scale = get_string('postrating1', 'forum').','.
1137 get_string('postrating2', 'forum').','.
1138 get_string('postrating3', 'forum');
02ebf404 1139 $defaultscale->timemodified = time();
1140
8f0cd6ef 1141 /// Read in the big description from the file. Note this is not
02ebf404 1142 /// HTML (despite the file extension) but Moodle format text.
d4419d55 1143 $parentlang = get_string('parentlang');
ee6e91d4 1144 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1145 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1146 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
d4419d55 1147 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
ee6e91d4 1148 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1149 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
d4419d55 1150 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1151 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
ee6e91d4 1152 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1153 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
02ebf404 1154 } else {
d4419d55 1155 $file = '';
02ebf404 1156 }
1157
d4419d55 1158 $defaultscale->description = addslashes(implode('', $file));
02ebf404 1159
d4419d55 1160 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
1161 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
02ebf404 1162 }
1163}
1164
fbc21ae8 1165
18a97fd8 1166/**
fbc21ae8 1167 * Returns a menu of all available scales from the site as well as the given course
1168 *
1169 * @uses $CFG
1170 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1171 * @return object
fbc21ae8 1172 */
02ebf404 1173function get_scales_menu($courseid=0) {
02ebf404 1174
1175 global $CFG;
8f0cd6ef 1176
1177 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1178 WHERE courseid = '0' or courseid = '$courseid'
02ebf404 1179 ORDER BY courseid ASC, name ASC";
1180
d4419d55 1181 if ($scales = get_records_sql_menu($sql)) {
02ebf404 1182 return $scales;
1183 }
1184
1185 make_default_scale();
1186
d4419d55 1187 return get_records_sql_menu($sql);
02ebf404 1188}
1189
5baa0ad6 1190
1191
1192/**
1193 * Given a set of timezone records, put them in the database, replacing what is there
1194 *
1195 * @uses $CFG
1196 * @param array $timezones An array of timezone records
1197 */
1198function update_timezone_records($timezones) {
1199/// Given a set of timezone records, put them in the database
1200
1201 global $CFG;
1202
1203/// Clear out all the old stuff
1204 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
1205
1206/// Insert all the new stuff
1207 foreach ($timezones as $timezone) {
1208 insert_record('timezone', $timezone);
1209 }
1210}
1211
1212
df28d6c5 1213/// MODULE FUNCTIONS /////////////////////////////////////////////////
1214
18a97fd8 1215/**
fbc21ae8 1216 * Just gets a raw list of all modules in a course
1217 *
1218 * @uses $CFG
1219 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1220 * @return object
fbc21ae8 1221 */
9fa49e22 1222function get_course_mods($courseid) {
9fa49e22 1223 global $CFG;
1224
3a11c548 1225 if (empty($courseid)) {
1226 return false; // avoid warnings
1227 }
1228
7acaa63d 1229 return get_records_sql("SELECT cm.*, m.name as modname
8f0cd6ef 1230 FROM {$CFG->prefix}modules m,
7acaa63d 1231 {$CFG->prefix}course_modules cm
8f0cd6ef 1232 WHERE cm.course = '$courseid'
9fa49e22 1233 AND cm.module = m.id ");
1234}
1235
fbc21ae8 1236
18a97fd8 1237/**
f9d5371b 1238 * Given an id of a course module, finds the coursemodule description
fbc21ae8 1239 *
f9d5371b 1240 * @param string $modulename name of module type, eg. resource, assignment,...
1241 * @param int $cmid course module id (id in course_modules table)
1242 * @param int $courseid optional course id for extra validation
1243 * @return object course module instance with instance and module name
1244 */
1245function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1246
1247 global $CFG;
1248
1249 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
1250
1251 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1252 FROM {$CFG->prefix}course_modules cm,
1253 {$CFG->prefix}modules md,
1254 {$CFG->prefix}$modulename m
1255 WHERE $courseselect
1256 cm.id = '$cmid' AND
1257 cm.instance = m.id AND
1258 md.name = '$modulename' AND
1259 md.id = cm.module");
1260}
1261
1262/**
1263 * Given an instance number of a module, finds the coursemodule description
1264 *
1265 * @param string $modulename name of module type, eg. resource, assignment,...
1266 * @param int $instance module instance number (id in resource, assignment etc. table)
1267 * @param int $courseid optional course id for extra validation
1268 * @return object course module instance with instance and module name
fbc21ae8 1269 */
b63c0ee5 1270function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
df28d6c5 1271
1272 global $CFG;
f9d5371b 1273
b63c0ee5 1274 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
df28d6c5 1275
f9d5371b 1276 return get_record_sql("SELECT cm.*, m.name, md.name as modname
8f0cd6ef 1277 FROM {$CFG->prefix}course_modules cm,
1278 {$CFG->prefix}modules md,
1279 {$CFG->prefix}$modulename m
b63c0ee5 1280 WHERE $courseselect
8f0cd6ef 1281 cm.instance = m.id AND
1282 md.name = '$modulename' AND
df28d6c5 1283 md.id = cm.module AND
1284 m.id = '$instance'");
1285
1286}
1287
185cfb09 1288/**
1289 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1290 *
1291 * Returns an array of all the active instances of a particular
1292 * module in given courses, sorted in the order they are defined
1293 * in the course. Returns false on any errors.
1294 *
1295 * @uses $CFG
1296 * @param string $modulename The name of the module to get instances for
613bbd7c 1297 * @param array $courses This depends on an accurate $course->modinfo
1298 * @return array of instances
185cfb09 1299 */
00e12c73 1300function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
185cfb09 1301 global $CFG;
1302 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1303 return array();
1304 }
1305 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course
1306 FROM {$CFG->prefix}course_modules cm,
1307 {$CFG->prefix}course_sections cw,
1308 {$CFG->prefix}modules md,
1309 {$CFG->prefix}$modulename m
1310 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1311 cm.instance = m.id AND
1312 cm.section = cw.id AND
1313 md.name = '$modulename' AND
1314 md.id = cm.module")) {
1315 return array();
1316 }
1317
1318 $outputarray = array();
1319
1320 foreach ($courses as $course) {
00e12c73 1321 if ($includeinvisible) {
1322 $invisible = -1;
1323 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1324 // Usually hide non-visible instances from students
185cfb09 1325 $invisible = -1;
1326 } else {
1327 $invisible = 0;
1328 }
fea43a7f 1329
1330 /// Casting $course->modinfo to string prevents one notice when the field is null
1331 if (!$modinfo = unserialize((string)$course->modinfo)) {
185cfb09 1332 continue;
1333 }
1334 foreach ($modinfo as $mod) {
1335 if ($mod->mod == $modulename and $mod->visible > $invisible) {
1336 $instance = $rawmods[$mod->cm];
1337 if (!empty($mod->extra)) {
1338 $instance->extra = $mod->extra;
1339 }
1340 $outputarray[] = $instance;
1341 }
1342 }
1343 }
1344
1345 return $outputarray;
1346
1347}
fbc21ae8 1348
18a97fd8 1349/**
fbc21ae8 1350 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
1351 *
1352 * Returns an array of all the active instances of a particular
1353 * module in a given course, sorted in the order they are defined
1354 * in the course. Returns false on any errors.
1355 *
1356 * @uses $CFG
1357 * @param string $modulename The name of the module to get instances for
1358 * @param object(course) $course This depends on an accurate $course->modinfo
fbc21ae8 1359 */
00e12c73 1360function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
df28d6c5 1361
1362 global $CFG;
1363
3cc8b355 1364 if (empty($course->modinfo)) {
1365 return array();
1366 }
1367
fea43a7f 1368 if (!$modinfo = unserialize((string)$course->modinfo)) {
cccb016a 1369 return array();
1acfbce5 1370 }
1371
d8c9d8a1 1372 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode,cm.groupingid
8f0cd6ef 1373 FROM {$CFG->prefix}course_modules cm,
1374 {$CFG->prefix}course_sections cw,
1375 {$CFG->prefix}modules md,
1376 {$CFG->prefix}$modulename m
1377 WHERE cm.course = '$course->id' AND
1378 cm.instance = m.id AND
8f0cd6ef 1379 cm.section = cw.id AND
1380 md.name = '$modulename' AND
cccb016a 1381 md.id = cm.module")) {
1382 return array();
1383 }
1384
00e12c73 1385 if ($includeinvisible) {
1386 $invisible = -1;
1387 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1388 // Usually hide non-visible instances from students
cccb016a 1389 $invisible = -1;
1390 } else {
1391 $invisible = 0;
1392 }
1393
78d4711e 1394 $outputarray = array();
1395
cccb016a 1396 foreach ($modinfo as $mod) {
8a67b03f 1397 $mod->id = $mod->cm;
e6839677 1398 $mod->course = $course->id;
8a67b03f 1399 if (!groups_course_module_visible($mod)) {
1400 continue;
1401 }
cccb016a 1402 if ($mod->mod == $modulename and $mod->visible > $invisible) {
7f12f9cd 1403 $instance = $rawmods[$mod->cm];
1404 if (!empty($mod->extra)) {
1405 $instance->extra = $mod->extra;
1406 }
1407 $outputarray[] = $instance;
cccb016a 1408 }
1409 }
1410
1411 return $outputarray;
df28d6c5 1412
1413}
1414
9fa49e22 1415
18a97fd8 1416/**
fbc21ae8 1417 * Determine whether a module instance is visible within a course
1418 *
1419 * Given a valid module object with info about the id and course,
1420 * and the module's type (eg "forum") returns whether the object
1421 * is visible or not
1422 *
1423 * @uses $CFG
613bbd7c 1424 * @param $moduletype Name of the module eg 'forum'
1425 * @param $module Object which is the instance of the module
7290c7fa 1426 * @return bool
fbc21ae8 1427 */
580f2fbc 1428function instance_is_visible($moduletype, $module) {
580f2fbc 1429
1430 global $CFG;
1431
2b49ae96 1432 if (!empty($module->id)) {
e6839677 1433 if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
2b49ae96 1434 FROM {$CFG->prefix}course_modules cm,
1435 {$CFG->prefix}modules m
1436 WHERE cm.course = '$module->course' AND
1437 cm.module = m.id AND
1438 m.name = '$moduletype' AND
1439 cm.instance = '$module->id'")) {
5930cded 1440
2b49ae96 1441 foreach ($records as $record) { // there should only be one - use the first one
13534ef7 1442 return $record->visible && groups_course_module_visible($record);
2b49ae96 1443 }
580f2fbc 1444 }
1445 }
580f2fbc 1446 return true; // visible by default!
1447}
1448
a3fb1c45 1449
1450
1451
9fa49e22 1452/// LOG FUNCTIONS /////////////////////////////////////////////////////
1453
1454
18a97fd8 1455/**
fbc21ae8 1456 * Add an entry to the log table.
1457 *
1458 * Add an entry to the log table. These are "action" focussed rather
1459 * than web server hits, and provide a way to easily reconstruct what
1460 * any particular student has been doing.
1461 *
1462 * @uses $CFG
1463 * @uses $USER
1464 * @uses $db
1465 * @uses $REMOTE_ADDR
1466 * @uses SITEID
89dcb99d 1467 * @param int $courseid The course id
fbc21ae8 1468 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
f7664880 1469 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
fbc21ae8 1470 * @param string $url The file and parameters used to see the results of the action
1471 * @param string $info Additional description information
1472 * @param string $cm The course_module->id if there is one
1473 * @param string $user If log regards $user other than $USER
1474 */
d4419d55 1475function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
e8395a09 1476 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1477 // This is for a good reason: it is the most frequently used DB update function,
1478 // so it has been optimised for speed.
fcaff7ff 1479 global $db, $CFG, $USER;
9fa49e22 1480
7a5b1fc5 1481 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 1482 $cm = 0;
1483 }
1484
3d94772d 1485 if ($user) {
1486 $userid = $user;
1487 } else {
cb80265b 1488 if (!empty($USER->realuser)) { // Don't log
3d94772d 1489 return;
1490 }
d4419d55 1491 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 1492 }
1493
fcaff7ff 1494 $REMOTE_ADDR = getremoteaddr();
1495
9fa49e22 1496 $timenow = time();
1497 $info = addslashes($info);
10a760b9 1498 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1499 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1500 }
853df85e 1501
1502 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
1503
8b497bbc 1504 if ($CFG->type = 'oci8po') {
1505 if (empty($info)) {
1506 $info = ' ';
1507 }
1508 }
1509
d4419d55 1510 $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
1511 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
ebc3bd2b 1512
ea82d6b6 1513 if (!$result and debugging()) {
d4419d55 1514 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
8f0cd6ef 1515 }
cb80265b 1516
7c3dab9f 1517/// Store lastaccess times for the current user, do not use in cron and other commandline scripts
a9fcd13a 1518/// only update the lastaccess/timeaccess fields only once every 60s
7c3dab9f 1519 if (!empty($USER->id) && ($userid == $USER->id) && !defined('FULLME')) {
5930cded 1520 $db->Execute('UPDATE '. $CFG->prefix .'user
cb80265b 1521 SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
a9fcd13a 1522 WHERE id = \''. $userid .'\' AND '.$timenow.' - lastaccess > 60');
cb80265b 1523 if ($courseid != SITEID && !empty($courseid)) {
853df85e 1524 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
5930cded 1525
a9fcd13a 1526 if ($ulid = get_field('user_lastaccess', 'id', 'userid', $userid, 'courseid', $courseid)) {
1527 $db->Execute("UPDATE {$CFG->prefix}user_lastaccess
1528 SET timeaccess=$timenow
1529 WHERE id = $ulid AND $timenow - timeaccess > 60");
cb80265b 1530 } else {
a9fcd13a 1531 $db->Execute("INSERT INTO {$CFG->prefix}user_lastaccess
1532 ('userid', 'courseid', 'timeaccess')
1533 VALUES ($userid, $courseid, $timenow)");
114176a2 1534 }
a9fcd13a 1535 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
3d94772d 1536 }
8f0cd6ef 1537 }
9fa49e22 1538}
1539
1540
18a97fd8 1541/**
fbc21ae8 1542 * Select all log records based on SQL criteria
1543 *
1544 * @uses $CFG
1545 * @param string $select SQL select criteria
1546 * @param string $order SQL order by clause to sort the records returned
1547 * @param string $limitfrom ?
1548 * @param int $limitnum ?
1549 * @param int $totalcount Passed in by reference.
7290c7fa 1550 * @return object
fbc21ae8 1551 * @todo Finish documenting this function
1552 */
d4419d55 1553function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
9fa49e22 1554 global $CFG;
1555
519d369f 1556 if ($order) {
d4419d55 1557 $order = 'ORDER BY '. $order;
519d369f 1558 }
1559
fbc21ae8 1560 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
a2ddd957 1561 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
1562
1563 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
519d369f 1564
d4419d55 1565 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
93a89227 1566 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
9fa49e22 1567}
1568
519d369f 1569
18a97fd8 1570/**
fbc21ae8 1571 * Select all log records for a given course and user
1572 *
1573 * @uses $CFG
2f87145b 1574 * @uses DAYSECS
fbc21ae8 1575 * @param int $userid The id of the user as found in the 'user' table.
1576 * @param int $courseid The id of the course as found in the 'course' table.
1577 * @param string $coursestart ?
1578 * @todo Finish documenting this function
1579 */
9fa49e22 1580function get_logs_usercourse($userid, $courseid, $coursestart) {
1581 global $CFG;
1582
da0c90c3 1583 if ($courseid) {
d4419d55 1584 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 1585 } else {
1586 $courseselect = '';
da0c90c3 1587 }
1588
1604a0fc 1589 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
8f0cd6ef 1590 FROM {$CFG->prefix}log
1591 WHERE userid = '$userid'
1604a0fc 1592 AND time > '$coursestart' $courseselect
9fa49e22 1593 GROUP BY day ");
1594}
1595
18a97fd8 1596/**
fbc21ae8 1597 * Select all log records for a given course, user, and day
1598 *
1599 * @uses $CFG
2f87145b 1600 * @uses HOURSECS
fbc21ae8 1601 * @param int $userid The id of the user as found in the 'user' table.
1602 * @param int $courseid The id of the course as found in the 'course' table.
1603 * @param string $daystart ?
7290c7fa 1604 * @return object
fbc21ae8 1605 * @todo Finish documenting this function
1606 */
9fa49e22 1607function get_logs_userday($userid, $courseid, $daystart) {
1608 global $CFG;
1609
7e4a6488 1610 if ($courseid) {
d4419d55 1611 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 1612 } else {
1613 $courseselect = '';
7e4a6488 1614 }
1615
1604a0fc 1616 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
9fa49e22 1617 FROM {$CFG->prefix}log
8f0cd6ef 1618 WHERE userid = '$userid'
1604a0fc 1619 AND time > '$daystart' $courseselect
9fa49e22 1620 GROUP BY hour ");
1621}
1622
b4bac9b6 1623/**
1624 * Returns an object with counts of failed login attempts
1625 *
8f0cd6ef 1626 * Returns information about failed login attempts. If the current user is
1627 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 1628 * number of accounts. For non-admins, only the attempts on the given user
1629 * are shown.
1630 *
fbc21ae8 1631 * @param string $mode Either 'admin', 'teacher' or 'everybody'
1632 * @param string $username The username we are searching for
1633 * @param string $lastlogin The date from which we are searching
1634 * @return int
b4bac9b6 1635 */
b4bac9b6 1636function count_login_failures($mode, $username, $lastlogin) {
1637
d4419d55 1638 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
b4bac9b6 1639
51792df0 1640 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID))) { // Return information about all accounts
b4bac9b6 1641 if ($count->attempts = count_records_select('log', $select)) {
1642 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
1643 return $count;
1644 }
9407d456 1645 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
d4419d55 1646 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
b4bac9b6 1647 return $count;
1648 }
1649 }
1650 return NULL;
1651}
1652
1653
a3fb1c45 1654/// GENERAL HELPFUL THINGS ///////////////////////////////////
1655
18a97fd8 1656/**
fbc21ae8 1657 * Dump a given object's information in a PRE block.
1658 *
1659 * Mostly just used for debugging.
1660 *
1661 * @param mixed $object The data to be printed
fbc21ae8 1662 */
a3fb1c45 1663function print_object($object) {
1aa7b31d 1664 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
a3fb1c45 1665}
1666
0986271b 1667function course_parent_visible($course = null) {
fa145ae1 1668 global $CFG;
1669
418b4e5a 1670 if (empty($course)) {
1671 return true;
1672 }
1673 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
1674 return true;
1675 }
0986271b 1676 return category_parent_visible($course->category);
1677}
1678
1679function category_parent_visible($parent = 0) {
5930cded 1680
824f1c40 1681 static $visible;
1682
0986271b 1683 if (!$parent) {
1684 return true;
1685 }
5930cded 1686
824f1c40 1687 if (empty($visible)) {
1688 $visible = array(); // initialize
1689 }
1690
1691 if (array_key_exists($parent,$visible)) {
1692 return $visible[$parent];
1693 }
5930cded 1694
0986271b 1695 $category = get_record('course_categories', 'id', $parent);
1696 $list = explode('/', preg_replace('/^\/(.*)$/', '$1', $category->path));
1697 $list[] = $parent;
1698 $parents = get_records_list('course_categories', 'id', implode(',', $list), 'depth DESC');
824f1c40 1699 $v = true;
1700 foreach ($parents as $p) {
1701 if (!$p->visible) {
1702 $v = false;
0986271b 1703 }
1704 }
824f1c40 1705 $visible[$parent] = $v; // now cache it
1706 return $v;
0986271b 1707}
1708
62d4e774 1709/**
5930cded 1710 * This function is the official hook inside XMLDB stuff to delegate its debug to one
62d4e774 1711 * external function.
1712 *
1713 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1714 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1715 *
1716 * @param $message string contains the error message
1717 * @param $object object XMLDB object that fired the debug
1718 */
1719function xmldb_debug($message, $object) {
1720
92b564f4 1721 debugging($message, DEBUG_DEVELOPER);
62d4e774 1722}
1723
49860445 1724/**
1725 * Get the lists of courses the current user has $cap capability in
5930cded 1726 * I am not sure if this is needed, it loops through all courses so
1727 * could cause performance problems.
1728 * If it's not used, we can use a faster function to detect
49860445 1729 * capability in restorelib.php
1730 * @param string $cap
1731 * @return array
1732 */
1733function get_capability_courses($cap) {
1734 global $USER;
5930cded 1735
49860445 1736 $mycourses = array();
1737 if ($courses = get_records('course')) {
1738 foreach ($courses as $course) {
1739 if (has_capability($cap, get_context_instance(CONTEXT_COURSE, $course->id))) {
5930cded 1740 $mycourses[] = $course->id;
49860445 1741 }
1742 }
1743 }
5930cded 1744
49860445 1745 return $mycourses;
5930cded 1746}
1747
49860445 1748/**
1749 * true or false function to see if user can create any courses at all
1750 * @return bool
1751 */
1752function user_can_create_courses() {
1753 global $USER;
1754 // if user has course creation capability at any site or course cat, then return true;
5930cded 1755
49860445 1756 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
5930cded 1757 return true;
49860445 1758 } else {
5930cded 1759 return (bool) count(get_creatable_categories());
49860445 1760 }
5930cded 1761
49860445 1762}
1763
1764/**
1765 * get the list of categories the current user can create courses in
1766 * @return array
1767 */
1768function get_creatable_categories() {
5930cded 1769
49860445 1770 $creatablecats = array();
1771 if ($cats = get_records('course_categories')) {
1772 foreach ($cats as $cat) {
1773 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
1774 $creatablecats[$cat->id] = $cat->name;
1775 }
1776 }
1777 }
1778 return $creatablecats;
1779}
1780
41883f79 1781/**
1782 * Turn an array of ints into a string usable in an IN sql clause...
1783 *
1784 **/
1785function sql_intarray_to_in($array) {
1786
1787 $na = array();
1788 $c = count($array);
1789 for ($n=0;$n<$c;$n++) {
1790 if (isset($array[$n]) && is_int($array[$n])) {
1791 $na[] = $array[$n];
1792 }
1793 }
1794 return join(',',$array);
1795}
1796
9d5b689c 1797// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
03517306 1798?>