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 | */ |
27 | function 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 |
43 | function 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 |
62 | function 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 |
73 | function 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 | |
82 | function 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 |
100 | function 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 |
131 | function 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 |
191 | function 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 |
213 | function 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 |
275 | function 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 |
318 | function 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 |
335 | function 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 | */ |
351 | function 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 | |
368 | function 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 |
387 | function 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 |
413 | function 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 |
497 | function 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 | /** |
82c62d1b |
590 | * Convenience function - lists courses that a user has access to view. |
fbc21ae8 |
591 | * |
82c62d1b |
592 | * For admins and others with access to "every" course in the system, we should |
593 | * try to get courses with explicit RAs. |
594 | * |
595 | * NOTE: this function is heavily geared towards the perspective of the user |
596 | * passed in $userid. So it will hide courses that the user cannot see |
597 | * (for any reason) even if called from cron or from another $USER's |
598 | * perspective. |
599 | * |
600 | * If you really want to know what courses are assigned to the user, |
601 | * without any hiding or scheming, call the lower-level |
602 | * get_user_courses_bycap(). |
603 | * |
604 | * |
605 | * Notes inherited from get_user_courses_bycap(): |
e1d5e5c1 |
606 | * |
607 | * - $fields is an array of fieldnames to ADD |
608 | * so name the fields you really need, which will |
609 | * be added and uniq'd |
610 | * |
611 | * - the course records have $c->context which is a fully |
612 | * valid context object. Saves you a query per course! |
613 | * |
352f6f74 |
614 | * @uses $CFG,$USER |
7290c7fa |
615 | * @param int $userid The user of interest |
33f85740 |
616 | * @param string $sort the sortorder in the course table |
e1d5e5c1 |
617 | * @param array $fields - names of _additional_ fields to return (also accepts a string) |
f8e1c7af |
618 | * @param bool $doanything True if using the doanything flag |
619 | * @param int $limit Maximum number of records to return, or 0 for unlimited |
33f85740 |
620 | * @return array {@link $COURSE} of course objects |
fbc21ae8 |
621 | */ |
e1d5e5c1 |
622 | function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) { |
bdf3bbd1 |
623 | |
352f6f74 |
624 | global $CFG,$USER; |
5930cded |
625 | |
4dbca99e |
626 | // Guest's do not have any courses |
e1d5e5c1 |
627 | $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID); |
61f774e8 |
628 | if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) { |
4dbca99e |
629 | return(array()); |
630 | } |
601edb90 |
631 | |
352f6f74 |
632 | $basefields = array('id', 'category', 'sortorder', |
633 | 'shortname', 'fullname', 'idnumber', |
634 | 'teacher', 'teachers', 'student', 'students', |
635 | 'guest', 'startdate', 'visible', |
636 | 'newsitems', 'cost', 'enrol', |
637 | 'groupmode', 'groupmodeforce'); |
638 | |
e1d5e5c1 |
639 | if (!is_null($fields) && is_string($fields)) { |
640 | if (empty($fields)) { |
352f6f74 |
641 | $fields = $basefields; |
e1d5e5c1 |
642 | } else { |
643 | // turn the fields from a string to an array that |
573674bf |
644 | // get_user_courses_bycap() will like... |
352f6f74 |
645 | $fields = explode(',',$fields); |
646 | $fields = array_map('trim', $fields); |
647 | $fields = array_unique(array_merge($basefields, $fields)); |
648 | } |
649 | } else { |
650 | $fields = $basefields; |
651 | } |
652 | |
653 | // |
654 | // Logged-in user - Check cached courses |
655 | // |
656 | // NOTE! it's a _string_ because |
657 | // - it's all we'll ever use |
658 | // - it serialises much more compact than an array |
82c62d1b |
659 | // this a big concern here - cost of serialise |
660 | // and unserialise gets huge as the session grows |
352f6f74 |
661 | // |
662 | // If the courses are too many - it won't be set |
663 | // for large numbers of courses, caching in the session |
664 | // has marginal benefits (costs too much, not |
665 | // worthwhile...) and we may hit SQL parser limits |
666 | // because we use IN() |
667 | // |
ae1555ae |
668 | if ($userid === $USER->id) { |
fe3141e0 |
669 | if (isset($USER->loginascontext) |
670 | && $USER->loginascontext->contextlevel == CONTEXT_COURSE) { |
ae1555ae |
671 | // list _only_ this course |
672 | // anything else is asking for trouble... |
673 | $courseids = $USER->loginascontext->instanceid; |
674 | } elseif (isset($USER->mycourses) |
675 | && is_string($USER->mycourses)) { |
676 | if ($USER->mycourses === '') { |
677 | // empty str means: user has no courses |
678 | // ... so do the easy thing... |
679 | return array(); |
680 | } else { |
681 | $courseids = $USER->mycourses; |
682 | } |
683 | } |
684 | if (isset($courseids)) { |
352f6f74 |
685 | // The data massaging here MUST be kept in sync with |
686 | // get_user_courses_bycap() so we return |
687 | // the same... |
688 | // (but here we don't need to check has_cap) |
689 | $coursefields = 'c.' .join(',c.', $fields); |
690 | $sql = "SELECT $coursefields, |
82c62d1b |
691 | ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth, |
692 | cc.path AS categorypath |
352f6f74 |
693 | FROM {$CFG->prefix}course c |
82c62d1b |
694 | JOIN {$CFG->prefix}course_categories cc |
695 | ON c.category=cc.id |
352f6f74 |
696 | JOIN {$CFG->prefix}context ctx |
697 | ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.") |
ae1555ae |
698 | WHERE c.id IN ($courseids) |
352f6f74 |
699 | ORDER BY $sort"; |
700 | $rs = get_recordset_sql($sql); |
701 | $courses = array(); |
702 | $cc = 0; // keep count |
703 | if ($rs->RecordCount()) { |
704 | while ($c = rs_fetch_next_record($rs)) { |
705 | // build the context obj |
c1b7a5e5 |
706 | $c = make_context_subobj($c); |
707 | |
352f6f74 |
708 | $courses[$c->id] = $c; |
709 | if ($limit > 0 && $cc++ > $limit) { |
710 | break; |
711 | } |
712 | } |
713 | } |
714 | rs_close($rs); |
715 | return $courses; |
2f3499b7 |
716 | } |
717 | } |
152a9060 |
718 | |
352f6f74 |
719 | // Non-cached - get accessinfo |
e1d5e5c1 |
720 | if ($userid === $USER->id && isset($USER->access)) { |
aeb3916b |
721 | $accessinfo = $USER->access; |
bdf3bbd1 |
722 | } else { |
e1d5e5c1 |
723 | $accessinfo = get_user_access_sitewide($userid); |
aeb3916b |
724 | } |
352f6f74 |
725 | |
726 | |
573674bf |
727 | $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo, |
728 | $doanything, $sort, $fields, |
729 | $limit); |
352f6f74 |
730 | |
82c62d1b |
731 | $cats = NULL; |
732 | // If we have to walk category visibility |
733 | // to eval course visibility, get the categories |
734 | if (empty($CFG->allowvisiblecoursesinhiddencategories)) { |
735 | $sql = "SELECT cc.id, cc.path, cc.visible, |
736 | ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth |
737 | FROM {$CFG->prefix}course_categories cc |
738 | JOIN {$CFG->prefix}context ctx |
739 | ON (cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.") |
740 | ORDER BY id"; |
741 | $rs = get_recordset_sql($sql); |
742 | $cats = array(); |
743 | if ($rs->RecordCount()) { |
744 | while ($cc = rs_fetch_next_record($rs)) { |
745 | // build the context obj |
746 | $cc = make_context_subobj($cc); |
747 | $cats[$cc->id] = $cc; |
748 | } |
749 | } |
750 | unset($cc); |
751 | rs_close($rs); |
752 | } |
352f6f74 |
753 | // |
754 | // Strangely, get_my_courses() is expected to return the |
aeb3916b |
755 | // array keyed on id, which messes up the sorting |
352f6f74 |
756 | // So do that, and also cache the ids in the session if appropriate |
757 | // |
aeb3916b |
758 | $kcourses = array(); |
759 | $cc = count($courses); |
352f6f74 |
760 | $cacheids = NULL; |
82c62d1b |
761 | $vcatpaths = array(); |
352f6f74 |
762 | if ($userid === $USER->id && $cc < 500) { |
763 | $cacheids = array(); |
764 | } |
aeb3916b |
765 | for ($n=0; $n<$cc; $n++) { |
82c62d1b |
766 | |
767 | // |
768 | // Check whether the user can _actually_ see them |
769 | // Easy if $CFG->allowvisiblecoursesinhiddencategories |
770 | // is set, and we don't have to care about categories. |
771 | // Lots of work otherwise... (all in mem though!) |
772 | // |
773 | $cansee = false; |
774 | if (is_null($cats)) { // easy rules! |
775 | if ($courses[$n]->visible == true) { |
776 | $cansee = true; |
777 | } elseif (has_capability('moodle/course:viewhiddencourses', |
778 | $courses[$n]->context, $userid)) { |
779 | $cansee = true; |
780 | } |
781 | } else { |
782 | // |
783 | // Is the cat visible? |
784 | // we have to assume it _is_ visible |
785 | // so we can shortcut when we find a hidden one |
786 | // |
787 | $viscat = true; |
788 | $cpath = $courses[$n]->categorypath; |
789 | if (isset($vcatpaths[$cpath])) { |
790 | $viscat = $vcatpaths[$cpath]; |
791 | } else { |
792 | $cpath = substr($cpath,1); // kill leading slash |
793 | $cpath = explode('/',$cpath); |
794 | $ccct = count($cpath); |
795 | for ($m=0;$m<$ccct;$m++) { |
796 | $ccid = $cpath[$m]; |
797 | if ($cats[$ccid]->visible==false) { |
798 | $viscat = false; |
799 | break; |
800 | } |
801 | } |
802 | $vcatpaths[$courses[$n]->categorypath] = $viscat; |
803 | } |
804 | |
805 | // |
806 | // Perhaps it's actually visible to this user |
807 | // check moodle/category:visibility |
808 | // |
809 | // The name isn't obvious, but the description says |
810 | // "See hidden categories" so the user shall see... |
811 | // |
812 | if ($viscat === false) { |
813 | $catctx = $cats[ $courses[$n]->category ]->context; |
814 | if (has_capability('moodle/category:visibility', |
815 | $catctx, $userid)) { |
816 | $vcatpaths[$courses[$n]->categorypath] = true; |
817 | $viscat = true; |
818 | } |
819 | } |
820 | |
821 | // |
822 | // Decision matrix |
823 | // |
824 | if ($viscat === true) { |
825 | if ($courses[$n]->visible == true) { |
826 | $cansee = true; |
827 | } elseif (has_capability('moodle/course:viewhiddencourses', |
828 | $courses[$n]->context, $userid)) { |
829 | $cansee = true; |
830 | } |
831 | } |
832 | } |
833 | if ($cansee === true) { |
834 | $kcourses[$courses[$n]->id] = $courses[$n]; |
835 | if (is_array($cacheids)) { |
836 | $cacheids[] = $courses[$n]->id; |
837 | } |
352f6f74 |
838 | } |
839 | } |
840 | if (is_array($cacheids)) { |
841 | // Only happens |
842 | // - for the logged in user |
843 | // - below the threshold (500) |
844 | // empty string is _valid_ |
845 | $USER->mycourses = join(',',$cacheids); |
846 | } elseif ($userid === $USER->id && isset($USER->mycourses)) { |
847 | // cheap sanity check |
848 | unset($USER->mycourses); |
aeb3916b |
849 | } |
352f6f74 |
850 | |
aeb3916b |
851 | return $kcourses; |
02ebf404 |
852 | } |
853 | |
18a97fd8 |
854 | /** |
7290c7fa |
855 | * A list of courses that match a search |
fbc21ae8 |
856 | * |
857 | * @uses $CFG |
858 | * @param array $searchterms ? |
859 | * @param string $sort ? |
860 | * @param int $page ? |
861 | * @param int $recordsperpage ? |
862 | * @param int $totalcount Passed in by reference. ? |
7290c7fa |
863 | * @return object {@link $COURSE} records |
fbc21ae8 |
864 | */ |
d4419d55 |
865 | function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) { |
02ebf404 |
866 | |
867 | global $CFG; |
868 | |
18a97fd8 |
869 | //to allow case-insensitive search for postgesql |
48505662 |
870 | if ($CFG->dbfamily == 'postgres') { |
d4419d55 |
871 | $LIKE = 'ILIKE'; |
872 | $NOTLIKE = 'NOT ILIKE'; // case-insensitive |
873 | $REGEXP = '~*'; |
874 | $NOTREGEXP = '!~*'; |
02ebf404 |
875 | } else { |
d4419d55 |
876 | $LIKE = 'LIKE'; |
877 | $NOTLIKE = 'NOT LIKE'; |
878 | $REGEXP = 'REGEXP'; |
879 | $NOTREGEXP = 'NOT REGEXP'; |
02ebf404 |
880 | } |
881 | |
d4419d55 |
882 | $fullnamesearch = ''; |
883 | $summarysearch = ''; |
02ebf404 |
884 | |
02ebf404 |
885 | foreach ($searchterms as $searchterm) { |
6bb0f67f |
886 | |
887 | /// Under Oracle and MSSQL, trim the + and - operators and perform |
888 | /// simpler LIKE search |
48505662 |
889 | if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') { |
6bb0f67f |
890 | $searchterm = trim($searchterm, '+-'); |
891 | } |
892 | |
02ebf404 |
893 | if ($fullnamesearch) { |
d4419d55 |
894 | $fullnamesearch .= ' AND '; |
02ebf404 |
895 | } |
02ebf404 |
896 | if ($summarysearch) { |
d4419d55 |
897 | $summarysearch .= ' AND '; |
02ebf404 |
898 | } |
a8b56716 |
899 | |
d4419d55 |
900 | if (substr($searchterm,0,1) == '+') { |
2c64f65c |
901 | $searchterm = substr($searchterm,1); |
902 | $summarysearch .= " c.summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' "; |
903 | $fullnamesearch .= " c.fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' "; |
a8b56716 |
904 | } else if (substr($searchterm,0,1) == "-") { |
2c64f65c |
905 | $searchterm = substr($searchterm,1); |
906 | $summarysearch .= " c.summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' "; |
907 | $fullnamesearch .= " c.fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' "; |
a8b56716 |
908 | } else { |
2c64f65c |
909 | $summarysearch .= ' c.summary '. $LIKE .' \'%'. $searchterm .'%\' '; |
910 | $fullnamesearch .= ' c.fullname '. $LIKE .' \'%'. $searchterm .'%\' '; |
a8b56716 |
911 | } |
912 | |
02ebf404 |
913 | } |
914 | |
2c64f65c |
915 | $sql = "SELECT c.*, |
916 | ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth |
917 | FROM {$CFG->prefix}course c |
918 | JOIN {$CFG->prefix}context ctx |
919 | ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.") |
920 | WHERE ( $fullnamesearch OR $summarysearch ) |
921 | AND category > 0 |
922 | ORDER BY " . $sort; |
02ebf404 |
923 | |
2c64f65c |
924 | $courses = array(); |
02ebf404 |
925 | |
2c64f65c |
926 | if ($rs = get_recordset_sql($sql)) { |
927 | |
928 | |
929 | // Tiki pagination |
930 | $limitfrom = $page * $recordsperpage; |
931 | $limitto = $limitfrom + $recordsperpage; |
932 | $c = 0; // counts how many visible courses we've seen |
933 | |
934 | while ($course = rs_fetch_next_record($rs)) { |
935 | $course = make_context_subobj($course); |
936 | if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) { |
937 | // Don't exit this loop till the end |
938 | // we need to count all the visible courses |
939 | // to update $totalcount |
940 | if ($c >= $limitfrom && $c < $limitto) { |
941 | $courses[] = $course; |
02ebf404 |
942 | } |
2c64f65c |
943 | $c++; |
02ebf404 |
944 | } |
945 | } |
946 | } |
947 | |
2c64f65c |
948 | // our caller expects 2 bits of data - our return |
949 | // array, and an updated $totalcount |
950 | $totalcount = $c; |
02ebf404 |
951 | return $courses; |
952 | } |
953 | |
954 | |
18a97fd8 |
955 | /** |
fbc21ae8 |
956 | * Returns a sorted list of categories |
957 | * |
613bbd7c |
958 | * @param string $parent The parent category if any |
959 | * @param string $sort the sortorder |
960 | * @return array of categories |
fbc21ae8 |
961 | */ |
d4419d55 |
962 | function get_categories($parent='none', $sort='sortorder ASC') { |
02ebf404 |
963 | |
814748c9 |
964 | if ($parent === 'none') { |
d4419d55 |
965 | $categories = get_records('course_categories', '', '', $sort); |
02ebf404 |
966 | } else { |
d4419d55 |
967 | $categories = get_records('course_categories', 'parent', $parent, $sort); |
02ebf404 |
968 | } |
969 | if ($categories) { /// Remove unavailable categories from the list |
02ebf404 |
970 | foreach ($categories as $key => $category) { |
152a9060 |
971 | if (!$category->visible) { |
115a622d |
972 | if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $category->id))) { |
02ebf404 |
973 | unset($categories[$key]); |
974 | } |
975 | } |
976 | } |
977 | } |
978 | return $categories; |
979 | } |
980 | |
981 | |
2327b9df |
982 | /** |
983 | * Returns an array of category ids of all the subcategories for a given |
984 | * category. |
985 | * @param $catid - The id of the category whose subcategories we want to find. |
986 | * @return array of category ids. |
987 | */ |
988 | function get_all_subcategories($catid) { |
989 | |
990 | $subcats = array(); |
991 | |
992 | if ($categories = get_records('course_categories', 'parent', $catid)) { |
993 | foreach ($categories as $cat) { |
994 | array_push($subcats, $cat->id); |
995 | $subcats = array_merge($subcats, get_all_subcategories($cat->id)); |
996 | } |
997 | } |
998 | return $subcats; |
999 | } |
1000 | |
1001 | |
18a97fd8 |
1002 | /** |
ba87a4da |
1003 | * This recursive function makes sure that the courseorder is consecutive |
1004 | * |
1005 | * @param type description |
1006 | * |
1007 | * $n is the starting point, offered only for compatilibity -- will be ignored! |
1008 | * $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade |
1009 | * safely from 1.4 to 1.5 |
1010 | */ |
f41ef63e |
1011 | function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') { |
5930cded |
1012 | |
ba87a4da |
1013 | global $CFG; |
8f0cd6ef |
1014 | |
02ebf404 |
1015 | $count = 0; |
5930cded |
1016 | |
f41ef63e |
1017 | $catgap = 1000; // "standard" category gap |
1018 | $tolerance = 200; // how "close" categories can get |
5930cded |
1019 | |
f41ef63e |
1020 | if ($categoryid > 0){ |
1021 | // update depth and path |
1022 | $cat = get_record('course_categories', 'id', $categoryid); |
1023 | if ($cat->parent == 0) { |
1024 | $depth = 0; |
1025 | $path = ''; |
1026 | } else if ($depth == 0 ) { // doesn't make sense; get from DB |
1027 | // this is only called if the $depth parameter looks dodgy |
1028 | $parent = get_record('course_categories', 'id', $cat->parent); |
1029 | $path = $parent->path; |
1030 | $depth = $parent->depth; |
1031 | } |
1032 | $path = $path . '/' . $categoryid; |
1033 | $depth = $depth + 1; |
ba87a4da |
1034 | |
5930cded |
1035 | set_field('course_categories', 'path', addslashes($path), 'id', $categoryid); |
1036 | set_field('course_categories', 'depth', $depth, 'id', $categoryid); |
f41ef63e |
1037 | } |
39f65595 |
1038 | |
1039 | // get some basic info about courses in the category |
5930cded |
1040 | $info = get_record_sql('SELECT MIN(sortorder) AS min, |
ba87a4da |
1041 | MAX(sortorder) AS max, |
5930cded |
1042 | COUNT(sortorder) AS count |
1043 | FROM ' . $CFG->prefix . 'course |
ba87a4da |
1044 | WHERE category=' . $categoryid); |
1045 | if (is_object($info)) { // no courses? |
1046 | $max = $info->max; |
1047 | $count = $info->count; |
1048 | $min = $info->min; |
1049 | unset($info); |
1050 | } |
1051 | |
814748c9 |
1052 | if ($categoryid > 0 && $n==0) { // only passed category so don't shift it |
1053 | $n = $min; |
1054 | } |
1055 | |
39f65595 |
1056 | // $hasgap flag indicates whether there's a gap in the sequence |
5930cded |
1057 | $hasgap = false; |
39f65595 |
1058 | if ($max-$min+1 != $count) { |
1059 | $hasgap = true; |
1060 | } |
5930cded |
1061 | |
39f65595 |
1062 | // $mustshift indicates whether the sequence must be shifted to |
1063 | // meet its range |
1064 | $mustshift = false; |
1065 | if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) { |
1066 | $mustshift = true; |
1067 | } |
1068 | |
ba87a4da |
1069 | // actually sort only if there are courses, |
1070 | // and we meet one ofthe triggers: |
1071 | // - safe flag |
1072 | // - they are not in a continuos block |
1073 | // - they are too close to the 'bottom' |
39f65595 |
1074 | if ($count && ( $safe || $hasgap || $mustshift ) ) { |
1075 | // special, optimized case where all we need is to shift |
1076 | if ( $mustshift && !$safe && !$hasgap) { |
1077 | $shift = $n + $catgap - $min; |
f8ea6077 |
1078 | if ($shift < $count) { |
1079 | $shift = $count + $catgap; |
1080 | } |
39f65595 |
1081 | // UPDATE course SET sortorder=sortorder+$shift |
5930cded |
1082 | execute_sql("UPDATE {$CFG->prefix}course |
1083 | SET sortorder=sortorder+$shift |
39f65595 |
1084 | WHERE category=$categoryid", 0); |
5930cded |
1085 | $n = $n + $catgap + $count; |
1086 | |
39f65595 |
1087 | } else { // do it slowly |
5930cded |
1088 | $n = $n + $catgap; |
39f65595 |
1089 | // if the new sequence overlaps the current sequence, lack of transactions |
1090 | // will stop us -- shift things aside for a moment... |
48505662 |
1091 | if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) { |
d6a49dab |
1092 | $shift = $max + $n + 1000; |
5930cded |
1093 | execute_sql("UPDATE {$CFG->prefix}course |
1094 | SET sortorder=sortorder+$shift |
39f65595 |
1095 | WHERE category=$categoryid", 0); |
ba87a4da |
1096 | } |
1097 | |
39f65595 |
1098 | $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder'); |
1099 | begin_sql(); |
f8ea6077 |
1100 | $tx = true; // transaction sanity |
5930cded |
1101 | foreach ($courses as $course) { |
f8ea6077 |
1102 | if ($tx && $course->sortorder != $n ) { // save db traffic |
1103 | $tx = $tx && set_field('course', 'sortorder', $n, |
1104 | 'id', $course->id); |
ba87a4da |
1105 | } |
1106 | $n++; |
1107 | } |
f8ea6077 |
1108 | if ($tx) { |
1109 | commit_sql(); |
1110 | } else { |
1111 | rollback_sql(); |
1112 | if (!$safe) { |
1113 | // if we failed when called with !safe, try |
1114 | // to recover calling self with safe=true |
1115 | return fix_course_sortorder($categoryid, $n, true, $depth, $path); |
1116 | } |
1117 | } |
5930cded |
1118 | } |
02ebf404 |
1119 | } |
d4419d55 |
1120 | set_field('course_categories', 'coursecount', $count, 'id', $categoryid); |
8f0cd6ef |
1121 | |
5930cded |
1122 | // $n could need updating |
814748c9 |
1123 | $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid"); |
1124 | if ($max > $n) { |
1125 | $n = $max; |
1126 | } |
758b9a4d |
1127 | |
6bc502cc |
1128 | if ($categories = get_categories($categoryid)) { |
1129 | foreach ($categories as $category) { |
f41ef63e |
1130 | $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path); |
6bc502cc |
1131 | } |
1132 | } |
8f0cd6ef |
1133 | |
39f65595 |
1134 | return $n+1; |
02ebf404 |
1135 | } |
1136 | |
d8634192 |
1137 | /** |
1138 | * Ensure all courses have a valid course category |
1139 | * useful if a category has been removed manually |
1140 | **/ |
1141 | function fix_coursecategory_orphans() { |
1142 | |
1143 | global $CFG; |
1144 | |
1145 | // Note: the handling of sortorder here is arguably |
1146 | // open to race conditions. Hard to fix here, unlikely |
1147 | // to hit anyone in production. |
1148 | |
1149 | $sql = "SELECT c.id, c.category, c.shortname |
1150 | FROM {$CFG->prefix}course c |
1151 | LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id |
1152 | WHERE cc.id IS NULL AND c.id != " . SITEID; |
1153 | |
1154 | $rs = get_recordset_sql($sql); |
1155 | |
1156 | if ($rs->RecordCount()){ // we have some orphans |
1157 | |
1158 | // the "default" category is the lowest numbered... |
1159 | $default = get_field_sql("SELECT MIN(id) |
1160 | FROM {$CFG->prefix}course_categories"); |
1161 | $sortorder = get_field_sql("SELECT MAX(sortorder) |
1162 | FROM {$CFG->prefix}course |
1163 | WHERE category=$default"); |
1164 | |
1165 | |
1166 | begin_sql(); |
1167 | $tx = true; |
1168 | while ($tx && $course = rs_fetch_next_record($rs)) { |
1169 | $tx = $tx && set_field('course', 'category', $default, 'id', $course->id); |
1170 | $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id); |
1171 | } |
1172 | if ($tx) { |
1173 | commit_sql(); |
1174 | } else { |
1175 | rollback_sql(); |
1176 | } |
1177 | } |
1178 | } |
1179 | |
db4b12eb |
1180 | /** |
1181 | * List of remote courses that a user has access to via MNET. |
1182 | * Works only on the IDP |
1183 | * |
1184 | * @uses $CFG, $USER |
1185 | * @return array {@link $COURSE} of course objects |
1186 | */ |
1187 | function get_my_remotecourses($userid=0) { |
1188 | global $CFG, $USER; |
1189 | |
1190 | if (empty($userid)) { |
1191 | $userid = $USER->id; |
1192 | } |
1193 | |
5930cded |
1194 | $sql = "SELECT c.remoteid, c.shortname, c.fullname, |
86dd62a7 |
1195 | c.hostid, c.summary, c.cat_name, |
1196 | h.name AS hostname |
db4b12eb |
1197 | FROM {$CFG->prefix}mnet_enrol_course c |
1198 | JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid |
86dd62a7 |
1199 | JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id |
db4b12eb |
1200 | WHERE a.userid={$userid}"; |
1201 | |
1202 | return get_records_sql($sql); |
1203 | } |
1204 | |
1205 | /** |
1206 | * List of remote hosts that a user has access to via MNET. |
1207 | * Works on the SP |
1208 | * |
1209 | * @uses $CFG, $USER |
1210 | * @return array of host objects |
1211 | */ |
1212 | function get_my_remotehosts() { |
1213 | global $CFG, $USER; |
1214 | |
1215 | if ($USER->mnethostid == $CFG->mnet_localhost_id) { |
1216 | return false; // Return nothing on the IDP |
1217 | } |
1218 | if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) { |
1219 | return $USER->mnet_foreign_host_array; |
1220 | } |
1221 | return false; |
1222 | } |
fbc21ae8 |
1223 | |
18a97fd8 |
1224 | /** |
fbc21ae8 |
1225 | * This function creates a default separated/connected scale |
1226 | * |
1227 | * This function creates a default separated/connected scale |
1228 | * so there's something in the database. The locations of |
1229 | * strings and files is a bit odd, but this is because we |
1230 | * need to maintain backward compatibility with many different |
1231 | * existing language translations and older sites. |
1232 | * |
1233 | * @uses $CFG |
1234 | */ |
02ebf404 |
1235 | function make_default_scale() { |
02ebf404 |
1236 | |
1237 | global $CFG; |
1238 | |
1239 | $defaultscale = NULL; |
1240 | $defaultscale->courseid = 0; |
1241 | $defaultscale->userid = 0; |
d4419d55 |
1242 | $defaultscale->name = get_string('separateandconnected'); |
1243 | $defaultscale->scale = get_string('postrating1', 'forum').','. |
1244 | get_string('postrating2', 'forum').','. |
1245 | get_string('postrating3', 'forum'); |
02ebf404 |
1246 | $defaultscale->timemodified = time(); |
1247 | |
8f0cd6ef |
1248 | /// Read in the big description from the file. Note this is not |
02ebf404 |
1249 | /// HTML (despite the file extension) but Moodle format text. |
d4419d55 |
1250 | $parentlang = get_string('parentlang'); |
ee6e91d4 |
1251 | if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) { |
1252 | $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html'); |
1253 | } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) { |
d4419d55 |
1254 | $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html'); |
ee6e91d4 |
1255 | } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) { |
1256 | $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html'); |
d4419d55 |
1257 | } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) { |
1258 | $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html'); |
ee6e91d4 |
1259 | } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) { |
1260 | $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html'); |
02ebf404 |
1261 | } else { |
d4419d55 |
1262 | $file = ''; |
02ebf404 |
1263 | } |
1264 | |
d4419d55 |
1265 | $defaultscale->description = addslashes(implode('', $file)); |
02ebf404 |
1266 | |
d4419d55 |
1267 | if ($defaultscale->id = insert_record('scale', $defaultscale)) { |
1268 | execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false); |
02ebf404 |
1269 | } |
1270 | } |
1271 | |
fbc21ae8 |
1272 | |
18a97fd8 |
1273 | /** |
fbc21ae8 |
1274 | * Returns a menu of all available scales from the site as well as the given course |
1275 | * |
1276 | * @uses $CFG |
1277 | * @param int $courseid The id of the course as found in the 'course' table. |
7290c7fa |
1278 | * @return object |
fbc21ae8 |
1279 | */ |
02ebf404 |
1280 | function get_scales_menu($courseid=0) { |
02ebf404 |
1281 | |
1282 | global $CFG; |
8f0cd6ef |
1283 | |
1284 | $sql = "SELECT id, name FROM {$CFG->prefix}scale |
1285 | WHERE courseid = '0' or courseid = '$courseid' |
02ebf404 |
1286 | ORDER BY courseid ASC, name ASC"; |
1287 | |
d4419d55 |
1288 | if ($scales = get_records_sql_menu($sql)) { |
02ebf404 |
1289 | return $scales; |
1290 | } |
1291 | |
1292 | make_default_scale(); |
1293 | |
d4419d55 |
1294 | return get_records_sql_menu($sql); |
02ebf404 |
1295 | } |
1296 | |
5baa0ad6 |
1297 | |
1298 | |
1299 | /** |
1300 | * Given a set of timezone records, put them in the database, replacing what is there |
1301 | * |
1302 | * @uses $CFG |
1303 | * @param array $timezones An array of timezone records |
1304 | */ |
1305 | function update_timezone_records($timezones) { |
1306 | /// Given a set of timezone records, put them in the database |
1307 | |
1308 | global $CFG; |
1309 | |
1310 | /// Clear out all the old stuff |
1311 | execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false); |
1312 | |
1313 | /// Insert all the new stuff |
1314 | foreach ($timezones as $timezone) { |
1315 | insert_record('timezone', $timezone); |
1316 | } |
1317 | } |
1318 | |
1319 | |
df28d6c5 |
1320 | /// MODULE FUNCTIONS ///////////////////////////////////////////////// |
1321 | |
18a97fd8 |
1322 | /** |
fbc21ae8 |
1323 | * Just gets a raw list of all modules in a course |
1324 | * |
1325 | * @uses $CFG |
1326 | * @param int $courseid The id of the course as found in the 'course' table. |
7290c7fa |
1327 | * @return object |
fbc21ae8 |
1328 | */ |
9fa49e22 |
1329 | function get_course_mods($courseid) { |
9fa49e22 |
1330 | global $CFG; |
1331 | |
3a11c548 |
1332 | if (empty($courseid)) { |
1333 | return false; // avoid warnings |
1334 | } |
1335 | |
7acaa63d |
1336 | return get_records_sql("SELECT cm.*, m.name as modname |
8f0cd6ef |
1337 | FROM {$CFG->prefix}modules m, |
7acaa63d |
1338 | {$CFG->prefix}course_modules cm |
8f0cd6ef |
1339 | WHERE cm.course = '$courseid' |
9fa49e22 |
1340 | AND cm.module = m.id "); |
1341 | } |
1342 | |
fbc21ae8 |
1343 | |
18a97fd8 |
1344 | /** |
f9d5371b |
1345 | * Given an id of a course module, finds the coursemodule description |
fbc21ae8 |
1346 | * |
f9d5371b |
1347 | * @param string $modulename name of module type, eg. resource, assignment,... |
1348 | * @param int $cmid course module id (id in course_modules table) |
1349 | * @param int $courseid optional course id for extra validation |
1350 | * @return object course module instance with instance and module name |
1351 | */ |
1352 | function get_coursemodule_from_id($modulename, $cmid, $courseid=0) { |
1353 | |
1354 | global $CFG; |
1355 | |
1356 | $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : ''; |
1357 | |
1358 | return get_record_sql("SELECT cm.*, m.name, md.name as modname |
1359 | FROM {$CFG->prefix}course_modules cm, |
1360 | {$CFG->prefix}modules md, |
1361 | {$CFG->prefix}$modulename m |
1362 | WHERE $courseselect |
1363 | cm.id = '$cmid' AND |
1364 | cm.instance = m.id AND |
1365 | md.name = '$modulename' AND |
1366 | md.id = cm.module"); |
1367 | } |
1368 | |
1369 | /** |
1370 | * Given an instance number of a module, finds the coursemodule description |
1371 | * |
1372 | * @param string $modulename name of module type, eg. resource, assignment,... |
1373 | * @param int $instance module instance number (id in resource, assignment etc. table) |
1374 | * @param int $courseid optional course id for extra validation |
1375 | * @return object course module instance with instance and module name |
fbc21ae8 |
1376 | */ |
b63c0ee5 |
1377 | function get_coursemodule_from_instance($modulename, $instance, $courseid=0) { |
df28d6c5 |
1378 | |
1379 | global $CFG; |
f9d5371b |
1380 | |
b63c0ee5 |
1381 | $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : ''; |
df28d6c5 |
1382 | |
f9d5371b |
1383 | return get_record_sql("SELECT cm.*, m.name, md.name as modname |
8f0cd6ef |
1384 | FROM {$CFG->prefix}course_modules cm, |
1385 | {$CFG->prefix}modules md, |
1386 | {$CFG->prefix}$modulename m |
b63c0ee5 |
1387 | WHERE $courseselect |
8f0cd6ef |
1388 | cm.instance = m.id AND |
1389 | md.name = '$modulename' AND |
df28d6c5 |
1390 | md.id = cm.module AND |
1391 | m.id = '$instance'"); |
1392 | |
1393 | } |
1394 | |
185cfb09 |
1395 | /** |
1396 | * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined |
1397 | * |
1398 | * Returns an array of all the active instances of a particular |
1399 | * module in given courses, sorted in the order they are defined |
1400 | * in the course. Returns false on any errors. |
1401 | * |
1402 | * @uses $CFG |
1403 | * @param string $modulename The name of the module to get instances for |
613bbd7c |
1404 | * @param array $courses This depends on an accurate $course->modinfo |
1405 | * @return array of instances |
185cfb09 |
1406 | */ |
00e12c73 |
1407 | function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) { |
185cfb09 |
1408 | global $CFG; |
1409 | if (empty($courses) || !is_array($courses) || count($courses) == 0) { |
1410 | return array(); |
1411 | } |
1412 | if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course |
1413 | FROM {$CFG->prefix}course_modules cm, |
1414 | {$CFG->prefix}course_sections cw, |
1415 | {$CFG->prefix}modules md, |
1416 | {$CFG->prefix}$modulename m |
1417 | WHERE cm.course IN (".implode(',',array_keys($courses)).") AND |
1418 | cm.instance = m.id AND |
1419 | cm.section = cw.id AND |
1420 | md.name = '$modulename' AND |
1421 | md.id = cm.module")) { |
1422 | return array(); |
1423 | } |
1424 | |
1425 | $outputarray = array(); |
1426 | |
1427 | foreach ($courses as $course) { |
00e12c73 |
1428 | if ($includeinvisible) { |
1429 | $invisible = -1; |
1430 | } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) { |
1431 | // Usually hide non-visible instances from students |
185cfb09 |
1432 | $invisible = -1; |
1433 | } else { |
1434 | $invisible = 0; |
1435 | } |
fea43a7f |
1436 | |
1437 | /// Casting $course->modinfo to string prevents one notice when the field is null |
1438 | if (!$modinfo = unserialize((string)$course->modinfo)) { |
185cfb09 |
1439 | continue; |
1440 | } |
1441 | foreach ($modinfo as $mod) { |
1442 | if ($mod->mod == $modulename and $mod->visible > $invisible) { |
1443 | $instance = $rawmods[$mod->cm]; |
1444 | if (!empty($mod->extra)) { |
1445 | $instance->extra = $mod->extra; |
1446 | } |
1447 | $outputarray[] = $instance; |
1448 | } |
1449 | } |
1450 | } |
1451 | |
1452 | return $outputarray; |
1453 | |
1454 | } |
fbc21ae8 |
1455 | |
18a97fd8 |
1456 | /** |
fbc21ae8 |
1457 | * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined |
1458 | * |
1459 | * Returns an array of all the active instances of a particular |
1460 | * module in a given course, sorted in the order they are defined |
1461 | * in the course. Returns false on any errors. |
1462 | * |
1463 | * @uses $CFG |
1464 | * @param string $modulename The name of the module to get instances for |
1465 | * @param object(course) $course This depends on an accurate $course->modinfo |
fbc21ae8 |
1466 | */ |
00e12c73 |
1467 | function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) { |
df28d6c5 |
1468 | |
1469 | global $CFG; |
1470 | |
3cc8b355 |
1471 | if (empty($course->modinfo)) { |
1472 | return array(); |
1473 | } |
1474 | |
fea43a7f |
1475 | if (!$modinfo = unserialize((string)$course->modinfo)) { |
cccb016a |
1476 | return array(); |
1acfbce5 |
1477 | } |
1478 | |
d8c9d8a1 |
1479 | if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode,cm.groupingid |
8f0cd6ef |
1480 | FROM {$CFG->prefix}course_modules cm, |
1481 | {$CFG->prefix}course_sections cw, |
1482 | {$CFG->prefix}modules md, |
1483 | {$CFG->prefix}$modulename m |
1484 | WHERE cm.course = '$course->id' AND |
1485 | cm.instance = m.id AND |
8f0cd6ef |
1486 | cm.section = cw.id AND |
1487 | md.name = '$modulename' AND |
cccb016a |
1488 | md.id = cm.module")) { |
1489 | return array(); |
1490 | } |
1491 | |
00e12c73 |
1492 | if ($includeinvisible) { |
1493 | $invisible = -1; |
1494 | } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) { |
1495 | // Usually hide non-visible instances from students |
cccb016a |
1496 | $invisible = -1; |
1497 | } else { |
1498 | $invisible = 0; |
1499 | } |
1500 | |
78d4711e |
1501 | $outputarray = array(); |
1502 | |
cccb016a |
1503 | foreach ($modinfo as $mod) { |
8a67b03f |
1504 | $mod->id = $mod->cm; |
e6839677 |
1505 | $mod->course = $course->id; |
8a67b03f |
1506 | if (!groups_course_module_visible($mod)) { |
1507 | continue; |
1508 | } |
cccb016a |
1509 | if ($mod->mod == $modulename and $mod->visible > $invisible) { |
7f12f9cd |
1510 | $instance = $rawmods[$mod->cm]; |
1511 | if (!empty($mod->extra)) { |
1512 | $instance->extra = $mod->extra; |
1513 | } |
1514 | $outputarray[] = $instance; |
cccb016a |
1515 | } |
1516 | } |
1517 | |
1518 | return $outputarray; |
df28d6c5 |
1519 | |
1520 | } |
1521 | |
9fa49e22 |
1522 | |
18a97fd8 |
1523 | /** |
fbc21ae8 |
1524 | * Determine whether a module instance is visible within a course |
1525 | * |
1526 | * Given a valid module object with info about the id and course, |
1527 | * and the module's type (eg "forum") returns whether the object |
1528 | * is visible or not |
1529 | * |
1530 | * @uses $CFG |
613bbd7c |
1531 | * @param $moduletype Name of the module eg 'forum' |
1532 | * @param $module Object which is the instance of the module |
7290c7fa |
1533 | * @return bool |
fbc21ae8 |
1534 | */ |
580f2fbc |
1535 | function instance_is_visible($moduletype, $module) { |
580f2fbc |
1536 | |
1537 | global $CFG; |
1538 | |
2b49ae96 |
1539 | if (!empty($module->id)) { |
e6839677 |
1540 | if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course |
2b49ae96 |
1541 | FROM {$CFG->prefix}course_modules cm, |
1542 | {$CFG->prefix}modules m |
1543 | WHERE cm.course = '$module->course' AND |
1544 | cm.module = m.id AND |
1545 | m.name = '$moduletype' AND |
1546 | cm.instance = '$module->id'")) { |
5930cded |
1547 | |
2b49ae96 |
1548 | foreach ($records as $record) { // there should only be one - use the first one |
13534ef7 |
1549 | return $record->visible && groups_course_module_visible($record); |
2b49ae96 |
1550 | } |
580f2fbc |
1551 | } |
1552 | } |
580f2fbc |
1553 | return true; // visible by default! |
1554 | } |
1555 | |
a3fb1c45 |
1556 | |
1557 | |
1558 | |
9fa49e22 |
1559 | /// LOG FUNCTIONS ///////////////////////////////////////////////////// |
1560 | |
1561 | |
18a97fd8 |
1562 | /** |
fbc21ae8 |
1563 | * Add an entry to the log table. |
1564 | * |
1565 | * Add an entry to the log table. These are "action" focussed rather |
1566 | * than web server hits, and provide a way to easily reconstruct what |
1567 | * any particular student has been doing. |
1568 | * |
1569 | * @uses $CFG |
1570 | * @uses $USER |
1571 | * @uses $db |
1572 | * @uses $REMOTE_ADDR |
1573 | * @uses SITEID |
89dcb99d |
1574 | * @param int $courseid The course id |
fbc21ae8 |
1575 | * @param string $module The module name - e.g. forum, journal, resource, course, user etc |
f7664880 |
1576 | * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify. |
fbc21ae8 |
1577 | * @param string $url The file and parameters used to see the results of the action |
1578 | * @param string $info Additional description information |
1579 | * @param string $cm The course_module->id if there is one |
1580 | * @param string $user If log regards $user other than $USER |
1581 | */ |
d4419d55 |
1582 | function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) { |
e8395a09 |
1583 | // Note that this function intentionally does not follow the normal Moodle DB access idioms. |
1584 | // This is for a good reason: it is the most frequently used DB update function, |
1585 | // so it has been optimised for speed. |
fcaff7ff |
1586 | global $db, $CFG, $USER; |
9fa49e22 |
1587 | |
7a5b1fc5 |
1588 | if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default |
f78b3c34 |
1589 | $cm = 0; |
1590 | } |
1591 | |
3d94772d |
1592 | if ($user) { |
1593 | $userid = $user; |
1594 | } else { |
cb80265b |
1595 | if (!empty($USER->realuser)) { // Don't log |
3d94772d |
1596 | return; |
1597 | } |
d4419d55 |
1598 | $userid = empty($USER->id) ? '0' : $USER->id; |
9fa49e22 |
1599 | } |
1600 | |
fcaff7ff |
1601 | $REMOTE_ADDR = getremoteaddr(); |
1602 | |
9fa49e22 |
1603 | $timenow = time(); |
1604 | $info = addslashes($info); |
10a760b9 |
1605 | if (!empty($url)) { // could break doing html_entity_decode on an empty var. |
1606 | $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php |
1607 | } |
853df85e |
1608 | |
1609 | if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;}; |
1610 | |
8b497bbc |
1611 | if ($CFG->type = 'oci8po') { |
1612 | if (empty($info)) { |
1613 | $info = ' '; |
1614 | } |
1615 | } |
1616 | |
d4419d55 |
1617 | $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info) |
1618 | VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')"); |
ebc3bd2b |
1619 | |
ea82d6b6 |
1620 | if (!$result and debugging()) { |
d4419d55 |
1621 | echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error |
8f0cd6ef |
1622 | } |
cb80265b |
1623 | |
7c3dab9f |
1624 | /// Store lastaccess times for the current user, do not use in cron and other commandline scripts |
a9fcd13a |
1625 | /// only update the lastaccess/timeaccess fields only once every 60s |
7c3dab9f |
1626 | if (!empty($USER->id) && ($userid == $USER->id) && !defined('FULLME')) { |
5930cded |
1627 | $db->Execute('UPDATE '. $CFG->prefix .'user |
cb80265b |
1628 | SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\' |
a9fcd13a |
1629 | WHERE id = \''. $userid .'\' AND '.$timenow.' - lastaccess > 60'); |
cb80265b |
1630 | if ($courseid != SITEID && !empty($courseid)) { |
853df85e |
1631 | if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;}; |
5930cded |
1632 | |
a9fcd13a |
1633 | if ($ulid = get_field('user_lastaccess', 'id', 'userid', $userid, 'courseid', $courseid)) { |
1634 | $db->Execute("UPDATE {$CFG->prefix}user_lastaccess |
1635 | SET timeaccess=$timenow |
1636 | WHERE id = $ulid AND $timenow - timeaccess > 60"); |
cb80265b |
1637 | } else { |
a9fcd13a |
1638 | $db->Execute("INSERT INTO {$CFG->prefix}user_lastaccess |
1639 | ('userid', 'courseid', 'timeaccess') |
1640 | VALUES ($userid, $courseid, $timenow)"); |
114176a2 |
1641 | } |
a9fcd13a |
1642 | if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;}; |
3d94772d |
1643 | } |
8f0cd6ef |
1644 | } |
9fa49e22 |
1645 | } |
1646 | |
1647 | |
18a97fd8 |
1648 | /** |
fbc21ae8 |
1649 | * Select all log records based on SQL criteria |
1650 | * |
1651 | * @uses $CFG |
1652 | * @param string $select SQL select criteria |
1653 | * @param string $order SQL order by clause to sort the records returned |
1654 | * @param string $limitfrom ? |
1655 | * @param int $limitnum ? |
1656 | * @param int $totalcount Passed in by reference. |
7290c7fa |
1657 | * @return object |
fbc21ae8 |
1658 | * @todo Finish documenting this function |
1659 | */ |
d4419d55 |
1660 | function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) { |
9fa49e22 |
1661 | global $CFG; |
1662 | |
519d369f |
1663 | if ($order) { |
d4419d55 |
1664 | $order = 'ORDER BY '. $order; |
519d369f |
1665 | } |
1666 | |
fbc21ae8 |
1667 | $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : ''); |
a2ddd957 |
1668 | $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : ''); |
1669 | |
1670 | $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql"); |
519d369f |
1671 | |
d4419d55 |
1672 | return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture |
93a89227 |
1673 | FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ; |
9fa49e22 |
1674 | } |
1675 | |
519d369f |
1676 | |
18a97fd8 |
1677 | /** |
fbc21ae8 |
1678 | * Select all log records for a given course and user |
1679 | * |
1680 | * @uses $CFG |
2f87145b |
1681 | * @uses DAYSECS |
fbc21ae8 |
1682 | * @param int $userid The id of the user as found in the 'user' table. |
1683 | * @param int $courseid The id of the course as found in the 'course' table. |
1684 | * @param string $coursestart ? |
1685 | * @todo Finish documenting this function |
1686 | */ |
9fa49e22 |
1687 | function get_logs_usercourse($userid, $courseid, $coursestart) { |
1688 | global $CFG; |
1689 | |
da0c90c3 |
1690 | if ($courseid) { |
d4419d55 |
1691 | $courseselect = ' AND course = \''. $courseid .'\' '; |
2700d113 |
1692 | } else { |
1693 | $courseselect = ''; |
da0c90c3 |
1694 | } |
1695 | |
1604a0fc |
1696 | return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num |
8f0cd6ef |
1697 | FROM {$CFG->prefix}log |
1698 | WHERE userid = '$userid' |
1604a0fc |
1699 | AND time > '$coursestart' $courseselect |
9fa49e22 |
1700 | GROUP BY day "); |
1701 | } |
1702 | |
18a97fd8 |
1703 | /** |
fbc21ae8 |
1704 | * Select all log records for a given course, user, and day |
1705 | * |
1706 | * @uses $CFG |
2f87145b |
1707 | * @uses HOURSECS |
fbc21ae8 |
1708 | * @param int $userid The id of the user as found in the 'user' table. |
1709 | * @param int $courseid The id of the course as found in the 'course' table. |
1710 | * @param string $daystart ? |
7290c7fa |
1711 | * @return object |
fbc21ae8 |
1712 | * @todo Finish documenting this function |
1713 | */ |
9fa49e22 |
1714 | function get_logs_userday($userid, $courseid, $daystart) { |
1715 | global $CFG; |
1716 | |
7e4a6488 |
1717 | if ($courseid) { |
d4419d55 |
1718 | $courseselect = ' AND course = \''. $courseid .'\' '; |
2700d113 |
1719 | } else { |
1720 | $courseselect = ''; |
7e4a6488 |
1721 | } |
1722 | |
1604a0fc |
1723 | return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num |
9fa49e22 |
1724 | FROM {$CFG->prefix}log |
8f0cd6ef |
1725 | WHERE userid = '$userid' |
1604a0fc |
1726 | AND time > '$daystart' $courseselect |
9fa49e22 |
1727 | GROUP BY hour "); |
1728 | } |
1729 | |
b4bac9b6 |
1730 | /** |
1731 | * Returns an object with counts of failed login attempts |
1732 | * |
8f0cd6ef |
1733 | * Returns information about failed login attempts. If the current user is |
1734 | * an admin, then two numbers are returned: the number of attempts and the |
b4bac9b6 |
1735 | * number of accounts. For non-admins, only the attempts on the given user |
1736 | * are shown. |
1737 | * |
fbc21ae8 |
1738 | * @param string $mode Either 'admin', 'teacher' or 'everybody' |
1739 | * @param string $username The username we are searching for |
1740 | * @param string $lastlogin The date from which we are searching |
1741 | * @return int |
b4bac9b6 |
1742 | */ |
b4bac9b6 |
1743 | function count_login_failures($mode, $username, $lastlogin) { |
1744 | |
d4419d55 |
1745 | $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin; |
b4bac9b6 |
1746 | |
51792df0 |
1747 | if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID))) { // Return information about all accounts |
b4bac9b6 |
1748 | if ($count->attempts = count_records_select('log', $select)) { |
1749 | $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)'); |
1750 | return $count; |
1751 | } |
9407d456 |
1752 | } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) { |
d4419d55 |
1753 | if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) { |
b4bac9b6 |
1754 | return $count; |
1755 | } |
1756 | } |
1757 | return NULL; |
1758 | } |
1759 | |
1760 | |
a3fb1c45 |
1761 | /// GENERAL HELPFUL THINGS /////////////////////////////////// |
1762 | |
18a97fd8 |
1763 | /** |
fbc21ae8 |
1764 | * Dump a given object's information in a PRE block. |
1765 | * |
1766 | * Mostly just used for debugging. |
1767 | * |
1768 | * @param mixed $object The data to be printed |
fbc21ae8 |
1769 | */ |
a3fb1c45 |
1770 | function print_object($object) { |
1aa7b31d |
1771 | echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>'; |
a3fb1c45 |
1772 | } |
1773 | |
0986271b |
1774 | function course_parent_visible($course = null) { |
fa145ae1 |
1775 | global $CFG; |
1776 | |
418b4e5a |
1777 | if (empty($course)) { |
1778 | return true; |
1779 | } |
1780 | if (!empty($CFG->allowvisiblecoursesinhiddencategories)) { |
1781 | return true; |
1782 | } |
0986271b |
1783 | return category_parent_visible($course->category); |
1784 | } |
1785 | |
1786 | function category_parent_visible($parent = 0) { |
5930cded |
1787 | |
824f1c40 |
1788 | static $visible; |
1789 | |
0986271b |
1790 | if (!$parent) { |
1791 | return true; |
1792 | } |
5930cded |
1793 | |
824f1c40 |
1794 | if (empty($visible)) { |
1795 | $visible = array(); // initialize |
1796 | } |
1797 | |
1798 | if (array_key_exists($parent,$visible)) { |
1799 | return $visible[$parent]; |
1800 | } |
5930cded |
1801 | |
0986271b |
1802 | $category = get_record('course_categories', 'id', $parent); |
1803 | $list = explode('/', preg_replace('/^\/(.*)$/', '$1', $category->path)); |
1804 | $list[] = $parent; |
1805 | $parents = get_records_list('course_categories', 'id', implode(',', $list), 'depth DESC'); |
824f1c40 |
1806 | $v = true; |
1807 | foreach ($parents as $p) { |
1808 | if (!$p->visible) { |
1809 | $v = false; |
0986271b |
1810 | } |
1811 | } |
824f1c40 |
1812 | $visible[$parent] = $v; // now cache it |
1813 | return $v; |
0986271b |
1814 | } |
1815 | |
62d4e774 |
1816 | /** |
5930cded |
1817 | * This function is the official hook inside XMLDB stuff to delegate its debug to one |
62d4e774 |
1818 | * external function. |
1819 | * |
1820 | * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before |
1821 | * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-) |
1822 | * |
1823 | * @param $message string contains the error message |
1824 | * @param $object object XMLDB object that fired the debug |
1825 | */ |
1826 | function xmldb_debug($message, $object) { |
1827 | |
92b564f4 |
1828 | debugging($message, DEBUG_DEVELOPER); |
62d4e774 |
1829 | } |
1830 | |
49860445 |
1831 | /** |
1832 | * Get the lists of courses the current user has $cap capability in |
5930cded |
1833 | * I am not sure if this is needed, it loops through all courses so |
1834 | * could cause performance problems. |
1835 | * If it's not used, we can use a faster function to detect |
49860445 |
1836 | * capability in restorelib.php |
1837 | * @param string $cap |
1838 | * @return array |
1839 | */ |
1840 | function get_capability_courses($cap) { |
1841 | global $USER; |
5930cded |
1842 | |
49860445 |
1843 | $mycourses = array(); |
1844 | if ($courses = get_records('course')) { |
1845 | foreach ($courses as $course) { |
1846 | if (has_capability($cap, get_context_instance(CONTEXT_COURSE, $course->id))) { |
5930cded |
1847 | $mycourses[] = $course->id; |
49860445 |
1848 | } |
1849 | } |
1850 | } |
5930cded |
1851 | |
49860445 |
1852 | return $mycourses; |
5930cded |
1853 | } |
1854 | |
49860445 |
1855 | /** |
1856 | * true or false function to see if user can create any courses at all |
1857 | * @return bool |
1858 | */ |
1859 | function user_can_create_courses() { |
1860 | global $USER; |
1861 | // if user has course creation capability at any site or course cat, then return true; |
5930cded |
1862 | |
49860445 |
1863 | if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) { |
5930cded |
1864 | return true; |
49860445 |
1865 | } else { |
5930cded |
1866 | return (bool) count(get_creatable_categories()); |
49860445 |
1867 | } |
5930cded |
1868 | |
49860445 |
1869 | } |
1870 | |
1871 | /** |
1872 | * get the list of categories the current user can create courses in |
1873 | * @return array |
1874 | */ |
1875 | function get_creatable_categories() { |
5930cded |
1876 | |
49860445 |
1877 | $creatablecats = array(); |
1878 | if ($cats = get_records('course_categories')) { |
1879 | foreach ($cats as $cat) { |
1880 | if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) { |
1881 | $creatablecats[$cat->id] = $cat->name; |
1882 | } |
1883 | } |
1884 | } |
1885 | return $creatablecats; |
1886 | } |
1887 | |
41883f79 |
1888 | /** |
1889 | * Turn an array of ints into a string usable in an IN sql clause... |
1890 | * |
1891 | **/ |
1892 | function sql_intarray_to_in($array) { |
1893 | |
1894 | $na = array(); |
1895 | $c = count($array); |
1896 | for ($n=0;$n<$c;$n++) { |
1897 | if (isset($array[$n]) && is_int($array[$n])) { |
1898 | $na[] = $array[$n]; |
1899 | } |
1900 | } |
1901 | return join(',',$array); |
1902 | } |
1903 | |
9d5b689c |
1904 | // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: |
03517306 |
1905 | ?> |