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