MDL-13919 Fixed undefined variable. Merging from MOODLE_19_STABLE
[moodle.git] / course / lib.php
CommitLineData
e4027ac9 1<?php // $Id$
97c270e9 2 // Library of useful functions
f9903ed0 3
f9903ed0 4
92890025 5define('COURSE_MAX_LOG_DISPLAY', 150); // days
6define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
7define('COURSE_LIVELOG_REFRESH', 60); // Seconds
8define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
9define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
950c35a9 10define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
92890025 11define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
220a90c5 12define('FRONTPAGENEWS', '0');
13define('FRONTPAGECOURSELIST', '1');
14define('FRONTPAGECATEGORYNAMES', '2');
15define('FRONTPAGETOPICONLY', '3');
16define('FRONTPAGECATEGORYCOMBO', '4');
6f24e48e 17define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
18define('EXCELROWS', 65535);
19define('FIRSTUSEDEXCELROW', 3);
60fdc714 20
89bfeee0 21define('MOD_CLASS_ACTIVITY', 0);
22define('MOD_CLASS_RESOURCE', 1);
23
f9903ed0 24
600149be 25function make_log_url($module, $url) {
26 switch ($module) {
bd7be234 27 case 'user':
28 case 'course':
29 case 'file':
30 case 'login':
31 case 'lib':
32 case 'admin':
bd7be234 33 case 'calendar':
bd5d0ce5 34 case 'mnet course':
35 return "/course/$url";
36 break;
bd7be234 37 case 'blog':
600149be 38 return "/$module/$url";
39 break;
bd7be234 40 case 'upload':
41 return $url;
c80b7585 42 break;
bd7be234 43 case 'library':
44 case '':
45 return '/';
de2dfe68 46 break;
4597d533 47 case 'message':
48 return "/message/$url";
49 break;
600149be 50 default:
51 return "/mod/$module/$url";
52 break;
53 }
54}
55
92890025 56
c215b32b 57function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
58 $modname="", $modid=0, $modaction="", $groupid=0) {
59
60 global $CFG;
61
62 // It is assumed that $date is the GMT time of midnight for that day,
63 // and so the next 86400 seconds worth of logs are printed.
64
65 /// Setup for group handling.
66
67 // TODO: I don't understand group/context/etc. enough to be able to do
68 // something interesting with it here
69 // What is the context of a remote course?
70
71 /// If the group mode is separate, and this user does not have editing privileges,
72 /// then only the user's group can be viewed.
73 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
74 // $groupid = get_current_group($course->id);
75 //}
76 /// If this course doesn't have groups, no groupid can be specified.
77 //else if (!$course->groupmode) {
78 // $groupid = 0;
79 //}
80 $groupid = 0;
81
82 $joins = array();
83
84 $qry = "
85 SELECT
86 l.*,
87 u.firstname,
88 u.lastname,
89 u.picture
90 FROM
91 {$CFG->prefix}mnet_log l
92 LEFT JOIN
93 {$CFG->prefix}user u
94 ON
95 l.userid = u.id
96 WHERE
97 ";
98
99 $where .= "l.hostid = '$hostid'";
100
101 // TODO: Is 1 really a magic number referring to the sitename?
102 if ($course != 1 || $modid != 0) {
103 $where .= " AND\n l.course='$course'";
104 }
105
106 if ($modname) {
107 $where .= " AND\n l.module = '$modname'";
108 }
109
110 if ('site_errors' === $modid) {
111 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
112 } else if ($modid) {
113 //TODO: This assumes that modids are the same across sites... probably
114 //not true
115 $where .= " AND\n l.cmid = '$modid'";
116 }
117
118 if ($modaction) {
119 $firstletter = substr($modaction, 0, 1);
120 if (ctype_alpha($firstletter)) {
121 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
122 } else if ($firstletter == '-') {
123 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
124 }
125 }
126
127 if ($user) {
128 $where .= " AND\n l.userid = '$user'";
129 }
130
131 if ($date) {
132 $enddate = $date + 86400;
133 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
134 }
135
136 $result = array();
137 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
138 if(!empty($result['totalcount'])) {
139 $where .= "\n ORDER BY\n $order";
140 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
141 } else {
142 $result['logs'] = array();
143 }
144 return $result;
145}
146
92890025 147function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
148 $modname="", $modid=0, $modaction="", $groupid=0) {
f24cffb9 149
e0161bff 150 // It is assumed that $date is the GMT time of midnight for that day,
151 // and so the next 86400 seconds worth of logs are printed.
f9903ed0 152
69c76405 153 /// Setup for group handling.
264867fd 154
69c76405 155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
3924b988 157 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
69c76405 158 $groupid = get_current_group($course->id);
159 }
160 /// If this course doesn't have groups, no groupid can be specified.
161 else if (!$course->groupmode) {
162 $groupid = 0;
163 }
164
e0161bff 165 $joins = array();
a2ab3b05 166
e15ef260 167 if ($course->id != SITEID || $modid != 0) {
8f0cd6ef 168 $joins[] = "l.course='$course->id'";
e15ef260 169 }
f9903ed0 170
c469a7ef 171 if ($modname) {
e0161bff 172 $joins[] = "l.module = '$modname'";
f24cffb9 173 }
174
e21922f0 175 if ('site_errors' === $modid) {
bf35eb15 176 $joins[] = "( l.action='error' OR l.action='infected' )";
e21922f0 177 } else if ($modid) {
178 $joins[] = "l.cmid = '$modid'";
69d79bc3 179 }
180
181 if ($modaction) {
ee35e0b8 182 $firstletter = substr($modaction, 0, 1);
183 if (ctype_alpha($firstletter)) {
184 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
185 } else if ($firstletter == '-') {
186 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
187 }
f24cffb9 188 }
189
05a33439 190
69c76405 191 /// Getting all members of a group.
192 if ($groupid and !$user) {
62d63838 193 if ($gusers = groups_get_members($groupid)) {
194 $gusers = array_keys($gusers);
1e95d7b7 195 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
196 } else {
05a33439 197 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
69c76405 198 }
199 }
200 else if ($user) {
e0161bff 201 $joins[] = "l.userid = '$user'";
f9903ed0 202 }
203
204 if ($date) {
205 $enddate = $date + 86400;
e0161bff 206 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
f9903ed0 207 }
208
1e95d7b7 209 $selector = implode(' AND ', $joins);
e0161bff 210
d09f3c80 211 $totalcount = 0; // Initialise
92890025 212 $result = array();
213 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
214 $result['totalcount'] = $totalcount;
215 return $result;
216}
264867fd 217
218
92890025 219function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
220 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
264867fd 221
92890025 222 global $CFG;
264867fd 223
92890025 224 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
225 $modname, $modid, $modaction, $groupid)) {
f9903ed0 226 notify("No logs found!");
227 print_footer($course);
228 exit;
229 }
264867fd 230
ea49a66c 231 $courses = array();
232
92890025 233 if ($course->id == SITEID) {
234 $courses[0] = '';
ea49a66c 235 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
92890025 236 foreach ($ccc as $cc) {
237 $courses[$cc->id] = $cc->shortname;
238 }
239 }
ea49a66c 240 } else {
241 $courses[$course->id] = $course->shortname;
92890025 242 }
264867fd 243
92890025 244 $totalcount = $logs['totalcount'];
f9903ed0 245 $count=0;
2eb68e6f 246 $ldcache = array();
f9903ed0 247 $tt = getdate(time());
248 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
1c0200e0 249
dcde9f02 250 $strftimedatetime = get_string("strftimedatetime");
251
5577ceb3 252 echo "<div class=\"info\">\n";
519d369f 253 print_string("displayingrecords", "", $totalcount);
5577ceb3 254 echo "</div>\n";
1c0200e0 255
8f0cd6ef 256 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
519d369f 257
56595370 258 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
259 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
21283ddc 260 echo "<tr>";
1548978d 261 if ($course->id == SITEID) {
54926e78 262 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
1548978d 263 }
54926e78 264 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
265 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
266 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
267 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
268 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
21283ddc 269 echo "</tr>\n";
1548978d 270
1e95d7b7 271 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
2b2d182a 272 if (empty($logs['logs'])) {
1e95d7b7 273 $logs['logs'] = array();
2b2d182a 274 }
1e95d7b7 275
1548978d 276 $row = 1;
92890025 277 foreach ($logs['logs'] as $log) {
600149be 278
1548978d 279 $row = ($row + 1) % 2;
280
2eb68e6f 281 if (isset($ldcache[$log->module][$log->action])) {
282 $ld = $ldcache[$log->module][$log->action];
283 } else {
1548978d 284 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
2eb68e6f 285 $ldcache[$log->module][$log->action] = $ld;
286 }
edf3ef00 287 if ($ld && is_numeric($log->info)) {
181b888e 288 // ugly hack to make sure fullname is shown correctly
4068bedb 289 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
181b888e 290 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
291 } else {
292 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
293 }
600149be 294 }
295
264867fd 296 //Filter log->info
c8b0a50b 297 $log->info = format_string($log->info);
298
d7d145b1 299 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
300 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
024ef528 301 $log->url = s($log->url); /// XSS protection and XHTML compatibility - should be in link_to_popup_window() instead!!
d7d145b1 302
1548978d 303 echo '<tr class="r'.$row.'">';
304 if ($course->id == SITEID) {
56595370 305 echo "<td class=\"cell c0\">\n";
bd5d0ce5 306 if (empty($log->course)) {
05a33439 307 echo get_string('site') . "\n";
bd5d0ce5 308 } else {
309 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
310 }
21283ddc 311 echo "</td>\n";
720a43ce 312 }
56595370 313 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
21283ddc 314 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
56595370 315 echo "<td class=\"cell c2\">\n";
7c09710c 316 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 440, 700);
21283ddc 317 echo "</td>\n";
1c45e42e 318 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
56595370 319 echo "<td class=\"cell c3\">\n";
d3a75287 320 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
21283ddc 321 echo "</td>\n";
56595370 322 echo "<td class=\"cell c4\">\n";
7c09710c 323 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',"$log->module $log->action", 440, 700);
21283ddc 324 echo "</td>\n";;
56595370 325 echo "<td class=\"cell c5\">{$log->info}</td>\n";
21283ddc 326 echo "</tr>\n";
f9903ed0 327 }
21283ddc 328 echo "</table>\n";
519d369f 329
8f0cd6ef 330 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
f9903ed0 331}
332
333
c215b32b 334function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
335 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
336
337 global $CFG;
338
339 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
340 $modname, $modid, $modaction, $groupid)) {
341 notify("No logs found!");
342 print_footer($course);
343 exit;
344 }
345
346 if ($course->id == SITEID) {
347 $courses[0] = '';
348 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
349 foreach ($ccc as $cc) {
350 $courses[$cc->id] = $cc->shortname;
351 }
352 }
353 }
354
355 $totalcount = $logs['totalcount'];
356 $count=0;
357 $ldcache = array();
358 $tt = getdate(time());
359 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
360
361 $strftimedatetime = get_string("strftimedatetime");
362
5577ceb3 363 echo "<div class=\"info\">\n";
c215b32b 364 print_string("displayingrecords", "", $totalcount);
5577ceb3 365 echo "</div>\n";
c215b32b 366
367 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
368
5577ceb3 369 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
c215b32b 370 echo "<tr>";
371 if ($course->id == SITEID) {
372 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
373 }
374 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
375 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
376 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
377 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
378 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
379 echo "</tr>\n";
380
381 if (empty($logs['logs'])) {
382 echo "</table>\n";
383 return;
384 }
385
386 $row = 1;
387 foreach ($logs['logs'] as $log) {
388
389 $log->info = $log->coursename;
390 $row = ($row + 1) % 2;
391
392 if (isset($ldcache[$log->module][$log->action])) {
393 $ld = $ldcache[$log->module][$log->action];
394 } else {
395 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
396 $ldcache[$log->module][$log->action] = $ld;
397 }
398 if (0 && $ld && !empty($log->info)) {
399 // ugly hack to make sure fullname is shown correctly
400 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
401 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
402 } else {
403 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
404 }
405 }
406
407 //Filter log->info
408 $log->info = format_string($log->info);
409
410 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
411 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
412 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
413
414 echo '<tr class="r'.$row.'">';
415 if ($course->id == SITEID) {
5577ceb3 416 echo "<td class=\"r$row c0\" >\n";
c215b32b 417 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
418 echo "</td>\n";
419 }
5577ceb3 420 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
c215b32b 421 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
5577ceb3 422 echo "<td class=\"r$row c2\" >\n";
c215b32b 423 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
424 echo "</td>\n";
425 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
5577ceb3 426 echo "<td class=\"r$row c3\" >\n";
c215b32b 427 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
428 echo "</td>\n";
5577ceb3 429 echo "<td class=\"r$row c4\">\n";
c215b32b 430 echo $log->action .': '.$log->module;
431 echo "</td>\n";;
5577ceb3 432 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
c215b32b 433 echo "</tr>\n";
434 }
435 echo "</table>\n";
436
437 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
438}
439
440
92890025 441function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
442 $modid, $modaction, $groupid) {
4068bedb 443
954fdb42 444 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
445 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
264867fd 446
954fdb42 447 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
92890025 448 $modname, $modid, $modaction, $groupid)) {
449 return false;
450 }
264867fd 451
ea49a66c 452 $courses = array();
453
92890025 454 if ($course->id == SITEID) {
455 $courses[0] = '';
456 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
457 foreach ($ccc as $cc) {
458 $courses[$cc->id] = $cc->shortname;
459 }
460 }
ea49a66c 461 } else {
462 $courses[$course->id] = $course->shortname;
92890025 463 }
264867fd 464
92890025 465 $count=0;
466 $ldcache = array();
467 $tt = getdate(time());
468 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
469
470 $strftimedatetime = get_string("strftimedatetime");
92890025 471
954fdb42 472 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
473 $filename .= '.txt';
264867fd 474 header("Content-Type: application/download\n");
954fdb42 475 header("Content-Disposition: attachment; filename=$filename");
476 header("Expires: 0");
477 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
478 header("Pragma: public");
479
480 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
481 echo $text;
482
2b2d182a 483 if (empty($logs['logs'])) {
484 return true;
485 }
486
954fdb42 487 foreach ($logs['logs'] as $log) {
488 if (isset($ldcache[$log->module][$log->action])) {
489 $ld = $ldcache[$log->module][$log->action];
490 } else {
491 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
492 $ldcache[$log->module][$log->action] = $ld;
493 }
494 if ($ld && !empty($log->info)) {
495 // ugly hack to make sure fullname is shown correctly
4068bedb 496 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
954fdb42 497 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
498 } else {
499 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
500 }
501 }
502
264867fd 503 //Filter log->info
954fdb42 504 $log->info = format_string($log->info);
505
506 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
507 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
508 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
509
510 $firstField = $courses[$log->course];
1c45e42e 511 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
954fdb42 512 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
513 $text = implode("\t", $row);
514 echo $text." \n";
515 }
516 return true;
92890025 517}
518
519
520function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
521 $modid, $modaction, $groupid) {
264867fd 522
92890025 523 global $CFG;
524
954fdb42 525 require_once("$CFG->libdir/excellib.class.php");
264867fd 526
954fdb42 527 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
92890025 528 $modname, $modid, $modaction, $groupid)) {
529 return false;
530 }
264867fd 531
ea49a66c 532 $courses = array();
533
92890025 534 if ($course->id == SITEID) {
535 $courses[0] = '';
536 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
537 foreach ($ccc as $cc) {
538 $courses[$cc->id] = $cc->shortname;
539 }
540 }
ea49a66c 541 } else {
542 $courses[$course->id] = $course->shortname;
92890025 543 }
264867fd 544
92890025 545 $count=0;
546 $ldcache = array();
547 $tt = getdate(time());
548 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
549
550 $strftimedatetime = get_string("strftimedatetime");
92890025 551
954fdb42 552 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
553 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
554 $filename .= '.xls';
264867fd 555
92890025 556 $workbook = new MoodleExcelWorkbook('-');
557 $workbook->send($filename);
264867fd 558
954fdb42 559 $worksheet = array();
560 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
561 get_string('fullname'), get_string('action'), get_string('info'));
264867fd 562
954fdb42 563 // Creating worksheets
564 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
565 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
566 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
567 $worksheet[$wsnumber]->set_column(1, 1, 30);
568 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
569 userdate(time(), $strftimedatetime));
570 $col = 0;
571 foreach ($headers as $item) {
572 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
573 $col++;
574 }
575 }
576
2b2d182a 577 if (empty($logs['logs'])) {
578 $workbook->close();
579 return true;
580 }
581
954fdb42 582 $formatDate =& $workbook->add_format();
583 $formatDate->set_num_format(get_string('log_excel_date_format'));
584
585 $row = FIRSTUSEDEXCELROW;
586 $wsnumber = 1;
587 $myxls =& $worksheet[$wsnumber];
588 foreach ($logs['logs'] as $log) {
589 if (isset($ldcache[$log->module][$log->action])) {
590 $ld = $ldcache[$log->module][$log->action];
591 } else {
592 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
593 $ldcache[$log->module][$log->action] = $ld;
594 }
595 if ($ld && !empty($log->info)) {
596 // ugly hack to make sure fullname is shown correctly
4068bedb 597 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
954fdb42 598 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
599 } else {
600 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
601 }
602 }
603
604 // Filter log->info
605 $log->info = format_string($log->info);
606 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
607
608 if ($nroPages>1) {
609 if ($row > EXCELROWS) {
610 $wsnumber++;
611 $myxls =& $worksheet[$wsnumber];
612 $row = FIRSTUSEDEXCELROW;
613 }
614 }
264867fd 615
954fdb42 616 $myxls->write($row, 0, $courses[$log->course], '');
617 // Excel counts from 1/1/1900
618 $excelTime=25569+$log->time/(3600*24);
619 $myxls->write($row, 1, $excelTime, $formatDate);
620 $myxls->write($row, 2, $log->ip, '');
1c45e42e 621 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
954fdb42 622 $myxls->write($row, 3, $fullname, '');
623 $myxls->write($row, 4, $log->module.' '.$log->action, '');
624 $myxls->write($row, 5, $log->info, '');
264867fd 625
954fdb42 626 $row++;
627 }
628
629 $workbook->close();
ea49a66c 630 return true;
631}
632
633function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
634 $modid, $modaction, $groupid) {
635
636 global $CFG;
637
638 require_once("$CFG->libdir/odslib.class.php");
639
640 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
641 $modname, $modid, $modaction, $groupid)) {
642 return false;
643 }
644
645 $courses = array();
646
647 if ($course->id == SITEID) {
648 $courses[0] = '';
649 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
650 foreach ($ccc as $cc) {
651 $courses[$cc->id] = $cc->shortname;
652 }
653 }
654 } else {
655 $courses[$course->id] = $course->shortname;
656 }
657
658 $count=0;
659 $ldcache = array();
660 $tt = getdate(time());
661 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
662
663 $strftimedatetime = get_string("strftimedatetime");
664
665 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
666 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
667 $filename .= '.ods';
668
669 $workbook = new MoodleODSWorkbook('-');
670 $workbook->send($filename);
671
672 $worksheet = array();
673 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
674 get_string('fullname'), get_string('action'), get_string('info'));
675
676 // Creating worksheets
677 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
678 $sheettitle = get_string('excel_sheettitle', 'logs', $wsnumber).$nroPages;
679 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
680 $worksheet[$wsnumber]->set_column(1, 1, 30);
681 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
682 userdate(time(), $strftimedatetime));
683 $col = 0;
684 foreach ($headers as $item) {
685 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
686 $col++;
687 }
688 }
689
690 if (empty($logs['logs'])) {
691 $workbook->close();
692 return true;
693 }
694
695 $formatDate =& $workbook->add_format();
696 $formatDate->set_num_format(get_string('log_excel_date_format'));
697
698 $row = FIRSTUSEDEXCELROW;
699 $wsnumber = 1;
700 $myxls =& $worksheet[$wsnumber];
701 foreach ($logs['logs'] as $log) {
702 if (isset($ldcache[$log->module][$log->action])) {
703 $ld = $ldcache[$log->module][$log->action];
704 } else {
705 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
706 $ldcache[$log->module][$log->action] = $ld;
707 }
708 if ($ld && !empty($log->info)) {
709 // ugly hack to make sure fullname is shown correctly
710 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
711 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
712 } else {
713 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
714 }
715 }
716
717 // Filter log->info
718 $log->info = format_string($log->info);
719 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
720
721 if ($nroPages>1) {
722 if ($row > EXCELROWS) {
723 $wsnumber++;
724 $myxls =& $worksheet[$wsnumber];
725 $row = FIRSTUSEDEXCELROW;
726 }
727 }
728
d81b7ffb 729 $myxls->write_string($row, 0, $courses[$log->course]);
730 $myxls->write_date($row, 1, $log->time);
731 $myxls->write_string($row, 2, $log->ip);
ea49a66c 732 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
d81b7ffb 733 $myxls->write_string($row, 3, $fullname);
734 $myxls->write_string($row, 4, $log->module.' '.$log->action);
735 $myxls->write_string($row, 5, $log->info);
ea49a66c 736
737 $row++;
738 }
739
740 $workbook->close();
954fdb42 741 return true;
92890025 742}
743
92890025 744
c2cb4545 745function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
a683deec 746 global $CFG, $USER;
c2cb4545 747 if (empty($CFG->gdversion)) {
748 echo "(".get_string("gdneed").")";
d887b5a7 749 } else {
a683deec 750 // MDL-10818, do not display broken graph when user has no permission to view graph
751 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_COURSE, $course->id)) ||
752 ($course->showreports and $USER->id == $userid)) {
753 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
754 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
755 }
d887b5a7 756 }
757}
758
759
185cfb09 760function print_overview($courses) {
0d6b9d4f 761
762 global $CFG, $USER;
763
185cfb09 764 $htmlarray = array();
f8716988 765 if ($modules = get_records('modules')) {
766 foreach ($modules as $mod) {
767 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
f461e8ec 768 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
f8716988 769 $fname = $mod->name.'_print_overview';
0d6b9d4f 770 if (function_exists($fname)) {
185cfb09 771 $fname($courses,$htmlarray);
0d6b9d4f 772 }
773 }
774 }
775 }
185cfb09 776 foreach ($courses as $course) {
fe5a1e23 777 print_simple_box_start('center', '100%', '', 5, "coursebox");
185cfb09 778 $linkcss = '';
779 if (empty($course->visible)) {
780 $linkcss = 'class="dimmed"';
781 }
6ba65fa0 782 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
185cfb09 783 if (array_key_exists($course->id,$htmlarray)) {
784 foreach ($htmlarray[$course->id] as $modname => $html) {
785 echo $html;
786 }
787 }
788 print_simple_box_end();
789 }
0d6b9d4f 790}
791
792
600149be 793function print_recent_activity($course) {
794 // $course is an object
89adb174 795 // This function trawls through the logs looking for
600149be 796 // anything new since the user's last login
797
810393c8 798 global $CFG, $USER, $SESSION;
600149be 799
e2a3a0e7 800 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2ac64806 801
dd97c328 802 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
803
804 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
0f87cb1d 805
e2a3a0e7 806 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
807 if (!empty($USER->lastcourseaccess[$course->id])) {
808 if ($USER->lastcourseaccess[$course->id] > $timestart) {
809 $timestart = $USER->lastcourseaccess[$course->id];
810 }
9e51847a 811 }
3d891989 812 }
0f87cb1d 813
de785682 814 echo '<div class="activitydate">';
27bf9e20 815 echo get_string('activitysince', '', userdate($timestart));
de785682 816 echo '</div>';
817 echo '<div class="activityhead">';
0f87cb1d 818
de785682 819 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
0f87cb1d 820
5fc835a5 821 echo "</div>\n";
0f87cb1d 822
600149be 823 $content = false;
1b5910c4 824
dd97c328 825/// Firstly, have there been any new enrolments?
826
6c38b7e0 827 $users = get_recent_enrolments($course->id, $timestart);
1b5910c4 828
5fc835a5 829 //Accessibility: new users now appear in an <OL> list.
6c38b7e0 830 if ($users) {
27bf9e20 831 echo '<div class="newusers">';
dd97c328 832 print_headline(get_string("newusers").':', 3);
833 $content = true;
5fc835a5 834 echo "<ol class=\"list\">\n";
6c38b7e0 835 foreach ($users as $user) {
dd97c328 836 $fullname = fullname($user, $viewfullnames);
837 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
600149be 838 }
5fc835a5 839 echo "</ol>\n</div>\n";
600149be 840 }
841
dd97c328 842/// Next, have there been any modifications to the course structure?
843
844 $modinfo =& get_fast_modinfo($course);
845
846 $changelist = array();
1b5910c4 847
dd97c328 848 $logs = get_records_select('log', "time > $timestart AND course = $course->id AND
849 module = 'course' AND
850 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
851 "id ASC");
1b5910c4 852
853 if ($logs) {
dd97c328 854 $actions = array('add mod', 'update mod', 'delete mod');
855 $newgones = array(); // added and later deleted items
1b5910c4 856 foreach ($logs as $key => $log) {
dd97c328 857 if (!in_array($log->action, $actions)) {
858 continue;
859 }
27bf9e20 860 $info = split(' ', $log->info);
c9f6251e 861
dd97c328 862 if ($info[0] == 'label') { // Labels are ignored in recent activity
c9f6251e 863 continue;
864 }
865
dd97c328 866 if (count($info) != 2) {
867 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
868 continue;
869 }
870
871 $modname = $info[0];
872 $instanceid = $info[1];
873
874 if ($log->action == 'delete mod') {
875 // unfortunately we do not know if the mod was visible
876 if (!array_key_exists($log->info, $newgones)) {
877 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
878 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
879 }
880 } else {
881 if (!isset($modinfo->instances[$modname][$instanceid])) {
882 if ($log->action == 'add mod') {
883 // do not display added and later deleted activities
884 $newgones[$log->info] = true;
885 }
886 continue;
887 }
888 $cm = $modinfo->instances[$modname][$instanceid];
889 if (!$cm->uservisible) {
890 //continue;
891 }
892
893 if ($log->action == 'add mod') {
894 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
895 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
896
897 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
898 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
899 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
600149be 900 }
ef25340c 901 }
902 }
903 }
904
9c9f7d77 905 if (!empty($changelist)) {
dd97c328 906 print_headline(get_string('courseupdates').':', 3);
907 $content = true;
ef25340c 908 foreach ($changelist as $changeinfo => $change) {
dd97c328 909 echo '<p class="activity">'.$change['text'].'</p>';
600149be 910 }
89adb174 911 }
bf40f9c1 912
dd97c328 913/// Now display new things from each module
0fd7da81 914
dd97c328 915 $usedmodules = array();
916 foreach($modinfo->cms as $cm) {
917 if (isset($usedmodules[$cm->modname])) {
918 continue;
919 }
920 if (!$cm->uservisible) {
921 continue;
922 }
923 $usedmodules[$cm->modname] = $cm->modname;
924 }
e2a3a0e7 925
dd97c328 926 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
927 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
928 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
929 $print_recent_activity = $modname.'_print_recent_activity';
296c6ac2 930 if (function_exists($print_recent_activity)) {
dd97c328 931 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
932 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
600149be 933 }
296c6ac2 934 } else {
dd97c328 935 debugging("Missing lib.php in lib/{$mod->name} - please reinstall files or uninstall the module");
600149be 936 }
937 }
938
939 if (! $content) {
27bf9e20 940 echo '<p class="message">'.get_string('nothingnew').'</p>';
600149be 941 }
600149be 942}
943
e1360728 944
d897cae4 945function get_array_of_activities($courseid) {
89adb174 946// For a given course, returns an array of course activity objects
d897cae4 947// Each item in the array contains he following properties:
948// cm - course module id
949// mod - name of the module (eg forum)
950// section - the number of the section (eg week or topic)
951// name - the name of the instance
5867bfb5 952// visible - is the instance visible or not
13534ef7
ML
953// groupingid - grouping id
954// groupmembersonly - is this instance visible to group members only
86aa7ccf 955// extra - contains extra string to include in any link
d897cae4 956
8dddba42 957 global $CFG;
958
d897cae4 959 $mod = array();
960
9fa49e22 961 if (!$rawmods = get_course_mods($courseid)) {
dd97c328 962 return $mod; // always return array
d897cae4 963 }
964
965 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
966 foreach ($sections as $section) {
74666583 967 if (!empty($section->sequence)) {
d897cae4 968 $sequence = explode(",", $section->sequence);
969 foreach ($sequence as $seq) {
7af6281f 970 if (empty($rawmods[$seq])) {
971 continue;
972 }
dd97c328 973 $mod[$seq]->id = $rawmods[$seq]->instance;
974 $mod[$seq]->cm = $rawmods[$seq]->id;
975 $mod[$seq]->mod = $rawmods[$seq]->modname;
976 $mod[$seq]->section = $section->section;
dd97c328 977 $mod[$seq]->visible = $rawmods[$seq]->visible;
978 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
979 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
13534ef7 980 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
dd97c328 981 $mod[$seq]->extra = "";
8dddba42 982
983 $modname = $mod[$seq]->mod;
984 $functionname = $modname."_get_coursemodule_info";
985
986 include_once("$CFG->dirroot/mod/$modname/lib.php");
987
988 if (function_exists($functionname)) {
9d361034 989 if ($info = $functionname($rawmods[$seq])) {
990 if (!empty($info->extra)) {
991 $mod[$seq]->extra = $info->extra;
992 }
993 if (!empty($info->icon)) {
994 $mod[$seq]->icon = $info->icon;
995 }
1ea543df 996 if (!empty($info->name)) {
997 $mod[$seq]->name = urlencode($info->name);
998 }
c9f6251e 999 }
1000 }
1ea543df 1001 if (!isset($mod[$seq]->name)) {
1002 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1003 }
d897cae4 1004 }
1005 }
1006 }
1007 }
1008 return $mod;
1009}
1010
1011
dd97c328 1012/**
1013 * Returns reference to full info about modules in course (including visibility).
1014 * Cached and as fast as possible (0 or 1 db query).
65a00c97 1015 * @param $course object or 'reset' string to reset caches, modinfo may be updated in db
dd97c328 1016 * @return mixed courseinfo object or nothing if resetting
1017 */
65a00c97 1018function &get_fast_modinfo(&$course, $userid=0) {
dd97c328 1019 global $CFG, $USER;
1020
1021 static $cache = array();
1022
1023 if ($course === 'reset') {
1024 $cache = array();
1025 $nothing = null;
1026 return $nothing; // we must return some reference
1027 }
1028
1029 if (empty($userid)) {
1030 $userid = $USER->id;
1031 }
1032
1033 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1034 return $cache[$course->id];
1035 }
1036
1037 if (empty($course->modinfo)) {
1038 // no modinfo yet - load it
1039 rebuild_course_cache($course->id);
af88aeb0 1040 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
dd97c328 1041 }
1042
1043 $modinfo = new object();
1044 $modinfo->courseid = $course->id;
1045 $modinfo->userid = $userid;
1046 $modinfo->sections = array();
1047 $modinfo->cms = array();
1048 $modinfo->instances = array();
1049 $modinfo->groups = null; // loaded only when really needed - the only one db query
1050
1051 $info = unserialize($course->modinfo);
1052 if (!is_array($info)) {
1053 // hmm, something is wrong - lets try to fix it
1054 rebuild_course_cache($course->id);
af88aeb0 1055 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
dd97c328 1056 $info = unserialize($course->modinfo);
1057 if (!is_array($info)) {
1058 return $modinfo;
1059 }
1060 }
1061
1062 if ($info) {
1063 // detect if upgrade required
1064 $first = reset($info);
1065 if (!isset($first->id)) {
1066 rebuild_course_cache($course->id);
af88aeb0 1067 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
dd97c328 1068 $info = unserialize($course->modinfo);
1069 if (!is_array($info)) {
1070 return $modinfo;
1071 }
1072 }
1073 }
1074
1075 $modlurals = array();
1076
65bcf17b 1077 $cmids = array();
1078 $contexts = null;
1079 foreach ($info as $mod) {
1080 $cmids[$mod->cm] = $mod->cm;
1081 }
1082 if ($cmids) {
1083 // preload all module contexts with one query
1084 $contexts = get_context_instance(CONTEXT_MODULE, $cmids);
1085 }
1086
dd97c328 1087 foreach ($info as $mod) {
1088 // reconstruct minimalistic $cm
1089 $cm = new object();
1090 $cm->id = $mod->cm;
1091 $cm->instance = $mod->id;
1092 $cm->course = $course->id;
1093 $cm->modname = $mod->mod;
1094 $cm->name = urldecode($mod->name);
1095 $cm->visible = $mod->visible;
76cbde41 1096 $cm->sectionnum = $mod->section;
dd97c328 1097 $cm->groupmode = $mod->groupmode;
1098 $cm->groupingid = $mod->groupingid;
1099 $cm->groupmembersonly = $mod->groupmembersonly;
1100 $cm->extra = isset($mod->extra) ? urldecode($mod->extra) : '';
1101 $cm->icon = isset($mod->icon) ? $mod->icon : '';
1102 $cm->uservisible = true;
1103
1104 // preload long names plurals - used very often
1105 if (!isset($modlurals[$cm->modname])) {
1106 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
1107 }
1108 $cm->modplural = $modlurals[$cm->modname];
1109
65bcf17b 1110 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $contexts[$cm->id], $userid)) {
dd97c328 1111 $cm->uservisible = false;
1112
1113 } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
65bcf17b 1114 and !has_capability('moodle/site:accessallgroups', $contexts[$cm->id], $userid)) {
dd97c328 1115 if (is_null($modinfo->groups)) {
1116 $modinfo->groups = groups_get_user_groups($course->id, $userid);
1117 }
1118 if (empty($modinfo->groups[$cm->groupingid])) {
1119 $cm->uservisible = false;
1120 }
1121 }
1122
1123 if (!isset($modinfo->instances[$cm->modname])) {
1124 $modinfo->instances[$cm->modname] = array();
1125 }
1126 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
1127 $modinfo->cms[$cm->id] =& $cm;
1128
1129 // reconstruct sections
76cbde41 1130 if (!isset($modinfo->sections[$cm->sectionnum])) {
1131 $modinfo->sections[$cm->sectionnum] = array();
dd97c328 1132 }
76cbde41 1133 $modinfo->sections[$cm->sectionnum][] = $cm->id;
dd97c328 1134
1135 unset($cm);
1136 }
1137
76cbde41 1138 unset($cache[$course->id]); // prevent potential reference problems when switching users
dd97c328 1139 $cache[$course->id] = $modinfo;
1140
1141 return $cache[$course->id];
1142}
d897cae4 1143
e1360728 1144
90845098 1145function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1146// Returns a number of useful structures for course displays
7468bf01 1147
dd97c328 1148 $mods = array(); // course modules indexed by id
1149 $modnames = array(); // all course module names (except resource!)
1150 $modnamesplural= array(); // all course module names (plural form)
1151 $modnamesused = array(); // course module names used
7468bf01 1152
9fa49e22 1153 if ($allmods = get_records("modules")) {
90845098 1154 foreach ($allmods as $mod) {
5867bfb5 1155 if ($mod->visible) {
1156 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1157 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1158 }
90845098 1159 }
91374f3e 1160 asort($modnames, SORT_LOCALE_STRING);
90845098 1161 } else {
1162 error("No modules are installed!");
1163 }
1164
9fa49e22 1165 if ($rawmods = get_course_mods($courseid)) {
7468bf01 1166 foreach($rawmods as $mod) { // Index the mods
959ae824 1167 if (empty($modnames[$mod->modname])) {
1168 continue;
1169 }
dd97c328 1170 $mods[$mod->id] = $mod;
1171 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1172 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1173 continue;
1174 }
13534ef7
ML
1175 // Check groupings
1176 if (!groups_course_module_visible($mod)) {
1177 continue;
1178 }
dd97c328 1179 $modnamesused[$mod->modname] = $modnames[$mod->modname];
7468bf01 1180 }
c7da6f7a 1181 if ($modnamesused) {
dba21d4a 1182 asort($modnamesused, SORT_LOCALE_STRING);
c7da6f7a 1183 }
7468bf01 1184 }
7468bf01 1185}
1186
9fa49e22 1187
7468bf01 1188function get_all_sections($courseid) {
89adb174 1189
1190 return get_records("course_sections", "course", "$courseid", "section",
7d99d695 1191 "section, id, course, summary, sequence, visible");
7468bf01 1192}
1193
b86fc0e2 1194function course_set_display($courseid, $display=0) {
1195 global $USER;
1196
b86fc0e2 1197 if ($display == "all" or empty($display)) {
1198 $display = 0;
1199 }
1200
7b678e0a 1201 if (empty($USER->id) or $USER->username == 'guest') {
1202 //do not store settings in db for guests
1203 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
b86fc0e2 1204 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1205 } else {
dd97c328 1206 $record = new object();
b86fc0e2 1207 $record->userid = $USER->id;
1208 $record->course = $courseid;
1209 $record->display = $display;
1210 if (!insert_record("course_display", $record)) {
1211 notify("Could not save your course display!");
1212 }
1213 }
1214
1215 return $USER->display[$courseid] = $display; // Note: = not ==
1216}
1217
7d99d695 1218function set_section_visible($courseid, $sectionnumber, $visibility) {
1219/// For a given course section, markes it visible or hidden,
1220/// and does the same for every activity in that section
1221
1222 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1223 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1224 if (!empty($section->sequence)) {
1225 $modules = explode(",", $section->sequence);
1226 foreach ($modules as $moduleid) {
02f66c42 1227 set_coursemodule_visible($moduleid, $visibility, true);
7d99d695 1228 }
1229 }
5867bfb5 1230 rebuild_course_cache($courseid);
7d99d695 1231 }
1232}
ba2e5d73 1233
5e367a2d 1234
d897cae4 1235function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
52dcc2f9 1236/// Prints a section full of activity modules
7977cffd 1237 global $CFG, $USER;
1238
dd97c328 1239 static $initialised;
1240
3d575e6f 1241 static $groupbuttons;
32d03b7b 1242 static $groupbuttonslink;
52dcc2f9 1243 static $isediting;
7977cffd 1244 static $ismoving;
1245 static $strmovehere;
1246 static $strmovefull;
54669989 1247 static $strunreadpostsone;
4877707e 1248 static $untracked;
a2d71d8e 1249 static $usetracking;
dd97c328 1250 static $groupings;
4877707e 1251
110a32e2 1252
dd97c328 1253 if (!isset($initialised)) {
9fd9c29b 1254 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
32d03b7b 1255 $groupbuttonslink = (!$course->groupmodeforce);
dd97c328 1256 $isediting = isediting($course->id);
1257 $ismoving = $isediting && ismoving($course->id);
3d575e6f 1258 if ($ismoving) {
dd97c328 1259 $strmovehere = get_string("movehere");
1260 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
3d575e6f 1261 }
94a6a70f 1262 include_once($CFG->dirroot.'/mod/forum/lib.php');
1263 if ($usetracking = forum_tp_can_track_forums()) {
dd97c328 1264 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1265 $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
a2d71d8e 1266 }
dd97c328 1267 $initialised = true;
7977cffd 1268 }
dd97c328 1269
1270 $labelformatoptions = new object();
60bd11cf 1271 $labelformatoptions->noclean = true;
94361e02 1272
fea43a7f 1273/// Casting $course->modinfo to string prevents one notice when the field is null
dd97c328 1274 $modinfo = get_fast_modinfo($course);
acf000b0 1275
94361e02 1276
c6a55371 1277 //Acccessibility: replace table with list <ul>, but don't output empty list.
74666583 1278 if (!empty($section->sequence)) {
94361e02 1279
f2d660dc 1280 // Fix bug #5027, don't want style=\"width:$width\".
6285f8a8 1281 echo "<ul class=\"section img-text\">\n";
94361e02 1282 $sectionmods = explode(",", $section->sequence);
1283
1284 foreach ($sectionmods as $modnumber) {
9ae687af 1285 if (empty($mods[$modnumber])) {
1286 continue;
1287 }
dd97c328 1288
94361e02 1289 $mod = $mods[$modnumber];
c9f6251e 1290
dd97c328 1291 if ($ismoving and $mod->id == $USER->activitycopy) {
1292 // do not display moving mod
1293 continue;
1294 }
c9f6251e 1295
dd97c328 1296 if (isset($modinfo->cms[$modnumber])) {
1297 if (!$modinfo->cms[$modnumber]->uservisible) {
1298 // visibility shortcut
1299 continue;
86aa7ccf 1300 }
dd97c328 1301 } else {
1302 if (!coursemodule_visible_for_user($mod)) {
1303 // full visibility check
1304 continue;
9d361034 1305 }
dd97c328 1306 }
1307
1308 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1309 if ($ismoving) {
1310 echo '<a title="'.$strmovefull.'"'.
1311 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1312 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1313 ' alt="'.$strmovehere.'" /></a><br />
1314 ';
1315 }
9d361034 1316
dd97c328 1317 if ($mod->indent) {
1318 print_spacer(12, 20 * $mod->indent, false);
1319 }
1320
1321 $extra = $modinfo->cms[$modnumber]->extra;
1322
1323 if ($mod->modname == "label") {
1324 if (!$mod->visible) {
1325 echo "<span class=\"dimmed_text\">";
1326 }
1327 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1328 if (!$mod->visible) {
1329 echo "</span>";
aac94fd0 1330 }
c4d989a1 1331 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1332 if (!isset($groupings)) {
1333 $groupings = groups_get_all_groupings($course->id);
1334 }
1470825e 1335 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
c4d989a1 1336 }
aac94fd0 1337
dd97c328 1338 } else { // Normal activity
1339 $instancename = format_string($modinfo->cms[$modnumber]->name, true, $course->id);
c9f6251e 1340
dd97c328 1341 if (!empty($modinfo->cms[$modnumber]->icon)) {
1342 $icon = "$CFG->pixpath/".$modinfo->cms[$modnumber]->icon;
1343 } else {
1344 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1345 }
e0b033d5 1346
dd97c328 1347 //Accessibility: for files get description via icon.
1348 $altname = '';
1349 if ('resource'==$mod->modname) {
1350 if (!empty($modinfo->cms[$modnumber]->icon)) {
1351 $possaltname = $modinfo->cms[$modnumber]->icon;
6285f8a8 1352
dd97c328 1353 $mimetype = mimeinfo_from_icon('type', $possaltname);
1354 $altname = get_mimetype_description($mimetype);
6285f8a8 1355 } else {
1356 $altname = $mod->modfullname;
1357 }
dd97c328 1358 } else {
1359 $altname = $mod->modfullname;
1360 }
1361 // Avoid unnecessary duplication.
1362 if (false!==stripos($instancename, $altname)) {
1363 $altname = '';
1364 }
1365 // File type after name, for alphabetic lists (screen reader).
1366 if ($altname) {
1367 $altname = get_accesshide(' '.$altname);
1368 }
6285f8a8 1369
dd97c328 1370 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1371 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1372 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1373 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1374 $instancename.$altname.'</span></a>';
806ebc15 1375
dd97c328 1376 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1377 if (!isset($groupings)) {
1378 $groupings = groups_get_all_groupings($course->id);
acf000b0 1379 }
1470825e 1380 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
c9f6251e 1381 }
dd97c328 1382 }
1383 if ($usetracking && $mod->modname == 'forum') {
1384 if ($usetracking and !isset($untracked[$mod->instance])) {
1385 $groupid = groups_get_activity_group($mod);
1386 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1387 if ($unread) {
1388 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1389 if ($unread == 1) {
1390 echo $strunreadpostsone;
1391 } else {
1392 print_string('unreadpostsnumber', 'forum', $unread);
d0388ebe 1393 }
dd97c328 1394 echo '</a> </span>';
54669989 1395 }
f37da850 1396 }
dd97c328 1397 }
f37da850 1398
dd97c328 1399 if ($isediting) {
1400 // TODO: we must define this as mod property!
1401 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1402 if (! $mod->groupmodelink = $groupbuttonslink) {
1403 $mod->groupmode = $course->groupmode;
3d575e6f 1404 }
dd97c328 1405
1406 } else {
1407 $mod->groupmode = false;
c9f6251e 1408 }
dd97c328 1409 echo '&nbsp;&nbsp;';
1410 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
94361e02 1411 }
dd97c328 1412 echo "</li>\n";
94361e02 1413 }
dd97c328 1414
f2d660dc 1415 } elseif ($ismoving) {
1416 echo "<ul class=\"section\">\n";
264867fd 1417 }
dd97c328 1418
7977cffd 1419 if ($ismoving) {
64fdc686 1420 echo '<li><a title="'.$strmovefull.'"'.
8b92f5bb 1421 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1422 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
c6a55371 1423 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1424 ';
7977cffd 1425 }
c6a55371 1426 if (!empty($section->sequence) || $ismoving) {
1427 echo "</ul><!--class='section'-->\n\n";
1428 }
a7ad3ea6 1429}
1430
89bfeee0 1431/**
1432 * Prints the menus to add activities and resources.
1433 */
cb57e6f4 1434function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
89bfeee0 1435 global $CFG;
e0161bff 1436
217a8ee9 1437 // check to see if user can add menus
1438 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
e2cd3ed0 1439 return false;
217a8ee9 1440 }
1441
89bfeee0 1442 static $resources = false;
1443 static $activities = false;
e0161bff 1444
89bfeee0 1445 if ($resources === false) {
1446 $resources = array();
1447 $activities = array();
6da4b261 1448
89bfeee0 1449 foreach($modnames as $modname=>$modnamestr) {
1450 if (!course_allowed_module($course, $modname)) {
1451 continue;
1452 }
6da4b261 1453
ffd58dd6 1454 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1455 if (!file_exists($libfile)) {
1456 continue;
1457 }
1458 include_once($libfile);
89bfeee0 1459 $gettypesfunc = $modname.'_get_types';
1460 if (function_exists($gettypesfunc)) {
1461 $types = $gettypesfunc();
1462 foreach($types as $type) {
65bcf17b 1463 if (!isset($type->modclass) or !isset($type->typestr)) {
ddb0a19f 1464 debugging('Incorrect activity type in '.$modname);
65bcf17b 1465 continue;
1466 }
89bfeee0 1467 if ($type->modclass == MOD_CLASS_RESOURCE) {
1468 $resources[$type->type] = $type->typestr;
1469 } else {
1470 $activities[$type->type] = $type->typestr;
1471 }
1472 }
1473 } else {
1474 // all mods without type are considered activity
1475 $activities[$modname] = $modnamestr;
1476 }
0705ff84 1477 }
e0161bff 1478 }
1479
89bfeee0 1480 $straddactivity = get_string('addactivity');
1481 $straddresource = get_string('addresource');
1482
4f24b3e3 1483 $output = '<div class="section_add_menus">';
1484
1485 if (!$vertical) {
1486 $output .= '<div class="horizontal">';
1487 }
89bfeee0 1488
1489 if (!empty($resources)) {
1490 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
0705ff84 1491 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1492 }
cb57e6f4 1493
89bfeee0 1494 if (!empty($activities)) {
1495 $output .= ' ';
1496 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1497 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
0705ff84 1498 }
1499
4f24b3e3 1500 if (!$vertical) {
d33d0cda 1501 $output .= '</div>';
1502 }
1503
cb57e6f4 1504 $output .= '</div>';
1505
1506 if ($return) {
1507 return $output;
1508 } else {
1509 echo $output;
1510 }
e0161bff 1511}
1512
f36cbf1d 1513/**
1514 * Rebuilds the cached list of course activities stored in the database
1515 * @param int $courseid - id of course to rebuil, empty means all
1516 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1517 */
1518function rebuild_course_cache($courseid=0, $clearonly=false) {
dd97c328 1519 global $COURSE;
f36cbf1d 1520
1521 if ($clearonly) {
1522 $courseselect = empty($courseid) ? "" : "id = $courseid";
1523 set_field_select('course', 'modinfo', null, $courseselect);
1524 // update cached global COURSE too ;-)
1525 if ($courseid == $COURSE->id) {
1526 $COURSE->modinfo = null;
1527 }
1528 // reset the fast modinfo cache
1529 $reset = 'reset';
1530 get_fast_modinfo($reset);
1531 return;
1532 }
5867bfb5 1533
1534 if ($courseid) {
1535 $select = "id = '$courseid'";
1536 } else {
1537 $select = "";
6cf890e3 1538 @set_time_limit(0); // this could take a while! MDL-10954
5867bfb5 1539 }
1540
f36cbf1d 1541 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1542 while($course = rs_fetch_next_record($rs)) {
5867bfb5 1543 $modinfo = serialize(get_array_of_activities($course->id));
1544 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
6ba65fa0 1545 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
5867bfb5 1546 }
dd97c328 1547 // update cached global COURSE too ;-)
1548 if ($course->id == $COURSE->id) {
1549 $COURSE->modinfo = $modinfo;
1550 }
5867bfb5 1551 }
f36cbf1d 1552 rs_close($rs);
5867bfb5 1553 }
dd97c328 1554 // reset the fast modinfo cache
65a00c97 1555 $reset = 'reset';
1556 get_fast_modinfo($reset);
5867bfb5 1557}
1558
9bb19e58 1559function get_child_categories($parent) {
1560/// Returns an array of the children categories for the given category
1561/// ID by caching all of the categories in a static hash
1562
1563 static $allcategories = null;
1564
1565 // only fill in this variable the first time
1566 if (null == $allcategories) {
1567 $allcategories = array();
1568
1569 $categories = get_categories();
1570 foreach ($categories as $category) {
1571 if (empty($allcategories[$category->parent])) {
1572 $allcategories[$category->parent] = array();
1573 }
1574 $allcategories[$category->parent][] = $category;
1575 }
1576 }
1577
1578 if (empty($allcategories[$parent])) {
1579 return array();
1580 } else {
1581 return $allcategories[$parent];
1582 }
1583}
1584
c2cb4545 1585
1586function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
89adb174 1587/// Given an empty array, this function recursively travels the
c2cb4545 1588/// categories, building up a nice list for display. It also makes
1589/// an array that list all the parents for each category.
1590
9d866ae0 1591 // initialize the arrays if needed
1592 if (!is_array($list)) {
264867fd 1593 $list = array();
9d866ae0 1594 }
1595 if (!is_array($parents)) {
264867fd 1596 $parents = array();
9d866ae0 1597 }
1598
c2cb4545 1599 if ($category) {
1600 if ($path) {
6ba65fa0 1601 $path = $path.' / '.format_string($category->name);
c2cb4545 1602 } else {
6ba65fa0 1603 $path = format_string($category->name);
c2cb4545 1604 }
1605 $list[$category->id] = $path;
1606 } else {
1607 $category->id = 0;
1608 }
1609
9bb19e58 1610 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1611 foreach ($categories as $cat) {
1612 if (!empty($category->id)) {
3bd4de22 1613 if (isset($parents[$category->id])) {
2832badf 1614 $parents[$cat->id] = $parents[$category->id];
1615 }
c2cb4545 1616 $parents[$cat->id][] = $category->id;
1617 }
89adb174 1618 make_categories_list($list, $parents, $cat, $path);
c2cb4545 1619 }
1620 }
1621}
1622
1623
d157bd5b 1624function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
89adb174 1625/// Recursive function to print out all the categories in a nice format
c2cb4545 1626/// with or without courses included
9ff5310a 1627 global $CFG;
e05bcf2f 1628
1629 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1630 return;
9ff5310a 1631 }
c2cb4545 1632
1633 if (!$displaylist) {
e92fe848 1634 make_categories_list($displaylist, $parentslist);
c2cb4545 1635 }
1636
1637 if ($category) {
ec7a8b79 1638 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6f24e48e 1639 print_category_info($category, $depth, $files);
c2cb4545 1640 } else {
1641 return; // Don't bother printing children of invisible categories
1642 }
89adb174 1643
c2cb4545 1644 } else {
c2cb4545 1645 $category->id = "0";
1646 }
1647
9bb19e58 1648 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1649 $countcats = count($categories);
1650 $count = 0;
1651 $first = true;
1652 $last = false;
1653 foreach ($categories as $cat) {
1654 $count++;
1655 if ($count == $countcats) {
1656 $last = true;
1657 }
1658 $up = $first ? false : true;
1659 $down = $last ? false : true;
1660 $first = false;
1661
6f24e48e 1662 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
c2cb4545 1663 }
1664 }
c2cb4545 1665}
1666
0705ff84 1667// this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1668
1669function make_categories_options() {
1670 make_categories_list($cats,$parents);
1671 foreach ($cats as $key => $value) {
1672 if (array_key_exists($key,$parents)) {
1673 if ($indent = count($parents[$key])) {
1674 for ($i = 0; $i < $indent; $i++) {
1675 $cats[$key] = '&nbsp;'.$cats[$key];
1676 }
1677 }
1678 }
1679 }
1680 return $cats;
1681}
c2cb4545 1682
6f24e48e 1683function print_category_info($category, $depth, $files = false) {
d2b6ba70 1684/// Prints the category info in indented fashion
1685/// This function is only used by print_whole_category_list() above
c2cb4545 1686
1687 global $CFG;
b48f834c 1688 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 1689
b48f834c 1690 if (empty($strsummary)) {
e05bcf2f 1691 $strallowguests = get_string('allowguests');
1692 $strrequireskey = get_string('requireskey');
1693 $strsummary = get_string('summary');
b48f834c 1694 }
ba2e5d73 1695
e05bcf2f 1696 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 1697
6f24e48e 1698 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1699 if ($files and $coursecount) {
fcf9577a 1700 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
b48f834c 1701 } else {
7b0b5c14 1702 $catimage = "&nbsp;";
8ef9cb56 1703 }
b48f834c 1704
fcf9577a 1705 echo "\n\n".'<table class="categorylist">';
d2b6ba70 1706
7ffcbfe1 1707 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.guest,c.cost,c.currency');
6f24e48e 1708 if ($files and $coursecount) {
b48f834c 1709
978abb42 1710 echo '<tr>';
b48f834c 1711
1712 if ($depth) {
1713 $indent = $depth*30;
1714 $rows = count($courses) + 1;
1c919752 1715 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
b48f834c 1716 print_spacer(10, $indent);
e05bcf2f 1717 echo '</td>';
b48f834c 1718 }
89adb174 1719
9deaeaa1 1720 echo '<td valign="top" class="category image">'.$catimage.'</td>';
fcf9577a 1721 echo '<td valign="top" class="category name">';
6ba65fa0 1722 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1723 echo '</td>';
290130b3 1724 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 1725 echo '</tr>';
b48f834c 1726
9ff5310a 1727 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
c2cb4545 1728 foreach ($courses as $course) {
e05bcf2f 1729 $linkcss = $course->visible ? '' : ' class="dimmed" ';
fcf9577a 1730 echo '<tr><td valign="top">&nbsp;';
1731 echo '</td><td valign="top" class="course name">';
6ba65fa0 1732 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
fcf9577a 1733 echo '</td><td align="right" valign="top" class="course info">';
c2cb4545 1734 if ($course->guest ) {
e05bcf2f 1735 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1736 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 1737 } else {
fcf9577a 1738 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1739 }
c2cb4545 1740 if ($course->password) {
e05bcf2f 1741 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1742 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 1743 } else {
fcf9577a 1744 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 1745 }
1746 if ($course->summary) {
e05bcf2f 1747 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
fcf9577a 1748 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 1749 400, 500, $strsummary);
ebe8ddc1 1750 } else {
fcf9577a 1751 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1752 }
e05bcf2f 1753 echo '</td></tr>';
0c656181 1754 }
ba2e5d73 1755 }
d2b6ba70 1756 } else {
b48f834c 1757
e0140f24 1758 echo '<tr>';
1759
b48f834c 1760 if ($depth) {
1761 $indent = $depth*20;
e05bcf2f 1762 echo '<td valign="top" width="'.$indent.'">';
b48f834c 1763 print_spacer(10, $indent);
e05bcf2f 1764 echo '</td>';
d2b6ba70 1765 }
89adb174 1766
fcf9577a 1767 echo '<td valign="top" class="category name">';
6ba65fa0 1768 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1769 echo '</td>';
290130b3 1770 echo '<td valign="top" class="category number">';
7ffcbfe1 1771 if (count($courses)) {
1772 echo count($courses);
e05bcf2f 1773 }
1774 echo '</td></tr>';
c2cb4545 1775 }
e05bcf2f 1776 echo '</table>';
c2cb4545 1777}
1778
c2cb4545 1779
e0b033d5 1780
6c54240a 1781function print_courses($category) {
c2cb4545 1782/// Category is 0 (for all courses) or an object
1783
810393c8 1784 global $CFG;
c2cb4545 1785
4dde1463 1786 if (!is_object($category) && $category==0) {
9bb19e58 1787 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
4dde1463 1788 if (is_array($categories) && count($categories) == 1) {
90c2ca2e 1789 $category = array_shift($categories);
4dde1463 1790 $courses = get_courses_wmanagers($category->id,
1791 'c.sortorder ASC',
1792 array('password','summary','currency'));
90c2ca2e 1793 } else {
4dde1463 1794 $courses = get_courses_wmanagers('all',
1795 'c.sortorder ASC',
1796 array('password','summary','currency'));
90c2ca2e 1797 }
1798 unset($categories);
607809b3 1799 } else {
4dde1463 1800 $courses = get_courses_wmanagers($category->id,
1801 'c.sortorder ASC',
1802 array('password','summary','currency'));
c2cb4545 1803 }
1804
49cd4d79 1805 if ($courses) {
8fee6c60 1806 echo '<ul class="unlist">';
c2cb4545 1807 foreach ($courses as $course) {
4dde1463 1808 if ($course->visible == 1
003bbcc8 1809 || has_capability('moodle/course:viewhiddencourses',$course->context)) {
8fee6c60 1810 echo '<li>';
4dde1463 1811 print_course($course);
8fee6c60 1812 echo "</li>\n";
4dde1463 1813 }
c2cb4545 1814 }
8fee6c60 1815 echo "</ul>\n";
c2cb4545 1816 } else {
f9667a5a 1817 print_heading(get_string("nocoursesyet"));
954fdb42 1818 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1819 if (has_capability('moodle/course:create', $context)) {
255d1033 1820 $options = array();
1821 $options['category'] = $category->id;
6b7425d2 1822 echo '<div class="addcoursebutton">';
255d1033 1823 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1824 echo '</div>';
1825 }
c2cb4545 1826 }
86dd62a7 1827
1828
1829
c2cb4545 1830}
1831
1832
35d0244a 1833function print_course($course) {
c2cb4545 1834
861efb19 1835 global $CFG, $USER;
c2cb4545 1836
4dde1463 1837 if (isset($course->context)) {
1838 $context = $course->context;
1839 } else {
1840 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1841 }
146bbb8f 1842
88768091 1843 $linkcss = $course->visible ? '' : ' class="dimmed" ';
22288704 1844
7cd266e9 1845 echo '<div class="coursebox clearfix">';
afba7be1 1846 echo '<div class="info">';
7f9c4fb9 1847 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
e5e81e78 1848 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
6ba65fa0 1849 format_string($course->fullname).'</a></div>';
b06334e8 1850
d42c64ba 1851 /// first find all roles that are supposed to be displayed
4dde1463 1852
6b4d8c4d 1853 if (!empty($CFG->coursemanager)) {
1854 $managerroles = split(',', $CFG->coursemanager);
3bf13d05 1855 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
4dde1463 1856 $namesarray = array();
1857 if (isset($course->managers)) {
1858 if (count($course->managers)) {
1859 $rusers = $course->managers;
1860 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
b682cee9 1861
1862 /// Rename some of the role names if needed
1863 if (isset($context)) {
87486420 1864 $aliasnames = get_records('role_names', 'contextid', $context->id,'','roleid,contextid,name');
b682cee9 1865 }
1866
4dde1463 1867 foreach ($rusers as $ra) {
1868 if ($ra->hidden == 0 || $canseehidden) {
1869 $fullname = fullname($ra->user, $canviewfullnames);
b682cee9 1870
1871 if (isset($aliasnames[$ra->roleid])) {
87486420 1872 $ra->rolename = $aliasnames[$ra->roleid]->name;
b682cee9 1873 }
1874
4dde1463 1875 $namesarray[] = format_string($ra->rolename)
1876 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
1877 . $fullname . '</a>';
1878 }
1879 }
1880 }
1881 } else {
6b4d8c4d 1882 $rusers = get_role_users($managerroles, $context,
4dde1463 1883 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1884 if (is_array($rusers) && count($rusers)) {
1885 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1886 foreach ($rusers as $teacher) {
1887 $fullname = fullname($teacher, $canviewfullnames);
1888 $namesarray[] = format_string($teacher->rolename)
1889 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
1890 . $fullname . '</a>';
1891 }
431cad0d 1892 }
c2cb4545 1893 }
431cad0d 1894
d42c64ba 1895 if (!empty($namesarray)) {
88768091 1896 echo "<ul class=\"teachers\">\n<li>";
1897 echo implode('</li><li>', $namesarray);
1898 echo "</li></ul>";
1899 }
c2cb4545 1900 }
d42c64ba 1901
88768091 1902 require_once("$CFG->dirroot/enrol/enrol.class.php");
1903 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 1904 echo $enrol->get_access_icons($course);
c2cb4545 1905
afba7be1 1906 echo '</div><div class="summary">';
9f39c190 1907 $options = NULL;
1908 $options->noclean = true;
34b5847a 1909 $options->para = false;
9f39c190 1910 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
afba7be1 1911 echo '</div>';
1912 echo '</div>';
c2cb4545 1913}
1914
1915
1916function print_my_moodle() {
1917/// Prints custom user information on the home page.
1918/// Over time this can include all sorts of information
1919
1920 global $USER, $CFG;
1921
86a1ba04 1922 if (empty($USER->id)) {
c2cb4545 1923 error("It shouldn't be possible to see My Moodle without being logged in.");
1924 }
1925
5b9e50ca 1926 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
86dd62a7 1927 $rhosts = array();
1928 $rcourses = array();
36e6379e 1929 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
86dd62a7 1930 $rcourses = get_my_remotecourses($USER->id);
643b67b8 1931 $rhosts = get_my_remotehosts();
86dd62a7 1932 }
1933
1934 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1935
1936 if (!empty($courses)) {
8fee6c60 1937 echo '<ul class="unlist">';
86dd62a7 1938 foreach ($courses as $course) {
1939 if ($course->id == SITEID) {
1940 continue;
1941 }
8fee6c60 1942 echo '<li>';
86dd62a7 1943 print_course($course, "100%");
8fee6c60 1944 echo "</li>\n";
86dd62a7 1945 }
8fee6c60 1946 echo "</ul>\n";
86dd62a7 1947 }
1948
1949 // MNET
1950 if (!empty($rcourses)) {
1951 // at the IDP, we know of all the remote courses
1952 foreach ($rcourses as $course) {
1953 print_remote_course($course, "100%");
1954 }
1955 } elseif (!empty($rhosts)) {
1956 // non-IDP, we know of all the remote servers, but not courses
1957 foreach ($rhosts as $host) {
643b67b8 1958 print_remote_host($host, "100%");
c81696e5 1959 }
c2cb4545 1960 }
86dd62a7 1961 unset($course);
1962 unset($host);
38a10939 1963
7f989948 1964 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1965 echo "<table width=\"100%\"><tr><td align=\"center\">";
1966 print_course_search("", false, "short");
1967 echo "</td><td align=\"center\">";
1968 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1969 echo "</td></tr></table>\n";
1970 }
86dd62a7 1971
26330001 1972 } else {
1973 if (count_records("course_categories") > 1) {
cb29b020 1974 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 1975 print_whole_category_list();
1976 print_simple_box_end();
1977 } else {
35d0244a 1978 print_courses(0);
26330001 1979 }
607809b3 1980 }
2b8cef80 1981}
1982
11b0c469 1983
a8b56716 1984function print_course_search($value="", $return=false, $format="plain") {
38a10939 1985
1986 global $CFG;
1e0fb105 1987 static $count = 0;
1988
1989 $count++;
1990
1991 $id = 'coursesearch';
1992
1993 if ($count > 1) {
1994 $id .= $count;
1995 }
38a10939 1996
1997 $strsearchcourses= get_string("searchcourses");
1998
1c919752 1999 if ($format == 'plain') {
1e0fb105 2000 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2001 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2002 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
8fee6c60 2003 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
e42f4d92 2004 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2005 $output .= '</fieldset></form>';
1c919752 2006 } else if ($format == 'short') {
1e0fb105 2007 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2008 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2009 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
8fee6c60 2010 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" value="'.s($value, true).'" />';
e42f4d92 2011 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2012 $output .= '</fieldset></form>';
1c919752 2013 } else if ($format == 'navbar') {
fcf9577a 2014 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2015 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2016 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
8fee6c60 2017 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" value="'.s($value, true).'" />';
e42f4d92 2018 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2019 $output .= '</fieldset></form>';
a8b56716 2020 }
2021
2022 if ($return) {
2023 return $output;
2024 }
2025 echo $output;
38a10939 2026}
11b0c469 2027
86dd62a7 2028function print_remote_course($course, $width="100%") {
2029
2030 global $CFG, $USER;
2031
2032 $linkcss = '';
2033
2034 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2035
7cd266e9 2036 echo '<div class="coursebox remotecoursebox clearfix">';
86dd62a7 2037 echo '<div class="info">';
2038 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2039 $linkcss.' href="'.$url.'">'
6ba65fa0 2040 . format_string($course->fullname) .'</a><br />'
2041 . format_string($course->hostname) . ' : '
2042 . format_string($course->cat_name) . ' : '
2043 . format_string($course->shortname). '</div>';
86dd62a7 2044 echo '</div><div class="summary">';
2045 $options = NULL;
2046 $options->noclean = true;
2047 $options->para = false;
2048 echo format_text($course->summary, FORMAT_MOODLE, $options);
2049 echo '</div>';
2050 echo '</div>';
86dd62a7 2051}
2052
643b67b8 2053function print_remote_host($host, $width="100%") {
2054
2055 global $CFG, $USER;
2056
2057 $linkcss = '';
2058
7cd266e9 2059 echo '<div class="coursebox clearfix">';
643b67b8 2060 echo '<div class="info">';
2061 echo '<div class="name">';
2062 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2063 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2064 . s($host['name']).'</a> - ';
1fd80ad3 2065 echo $host['count'] . ' ' . get_string('courses');
643b67b8 2066 echo '</div>';
2067 echo '</div>';
caa90d56 2068 echo '</div>';
643b67b8 2069}
2070
86dd62a7 2071
11b0c469 2072/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2073
2074function add_course_module($mod) {
11b0c469 2075
e5dfd0f3 2076 $mod->added = time();
53f4ad2c 2077 unset($mod->id);
11b0c469 2078
e5dfd0f3 2079 return insert_record("course_modules", $mod);
11b0c469 2080}
2081
97928ddf 2082/**
2083 * Returns course section - creates new if does not exist yet.
2084 * @param int $relative section number
2085 * @param int $courseid
2086 * @return object $course_section object
2087 */
2088function get_course_section($section, $courseid) {
2089 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2090 return $cw;
2091 }
2092 $cw = new object();
2093 $cw->course = $courseid;
2094 $cw->section = $section;
2095 $cw->summary = "";
2096 $cw->sequence = "";
2097 $id = insert_record("course_sections", $cw);
2098 return get_record("course_sections", "id", $id);
2099}
ece966f0 2100/**
2101 * Given a full mod object with section and course already defined, adds this module to that section.
2102 *
2103 * @param object $mod
2104 * @param int $beforemod An existing ID which we will insert the new module before
2105 * @return int The course_sections ID where the mod is inserted
2106 */
7977cffd 2107function add_mod_to_section($mod, $beforemod=NULL) {
11b0c469 2108
9fa49e22 2109 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
7977cffd 2110
2111 $section->sequence = trim($section->sequence);
2112
2113 if (empty($section->sequence)) {
11b0c469 2114 $newsequence = "$mod->coursemodule";
7977cffd 2115
2116 } else if ($beforemod) {
2117 $modarray = explode(",", $section->sequence);
2118
2119 if ($key = array_keys ($modarray, $beforemod->id)) {
2120 $insertarray = array($mod->id, $beforemod->id);
2121 array_splice($modarray, $key[0], 1, $insertarray);
2122 $newsequence = implode(",", $modarray);
2123
2124 } else { // Just tack it on the end anyway
2125 $newsequence = "$section->sequence,$mod->coursemodule";
2126 }
2127
2128 } else {
2129 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 2130 }
89adb174 2131
e5dfd0f3 2132 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2133 return $section->id; // Return course_sections ID that was used.
11b0c469 2134 } else {
e5dfd0f3 2135 return 0;
11b0c469 2136 }
89adb174 2137
11b0c469 2138 } else { // Insert a new record
e5dfd0f3 2139 $section->course = $mod->course;
2140 $section->section = $mod->section;
2141 $section->summary = "";
2142 $section->sequence = $mod->coursemodule;
2143 return insert_record("course_sections", $section);
11b0c469 2144 }
2145}
2146
48e535bc 2147function set_coursemodule_groupmode($id, $groupmode) {
3d575e6f 2148 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2149}
2150
24f41672 2151function set_coursemodule_groupingid($id, $groupingid) {
2152 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2153}
2154
2155function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2156 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2157}
2158
177d4abf 2159function set_coursemodule_idnumber($id, $idnumber) {
2160 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2161}
02f66c42 2162/**
2163* $prevstateoverrides = true will set the visibility of the course module
2164* to what is defined in visibleold. This enables us to remember the current
2165* visibility when making a whole section hidden, so that when we toggle
2166* that section back to visible, we are able to return the visibility of
2167* the course module back to what it was originally.
2168*/
2169function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
978abb42 2170 if (!$cm = get_record('course_modules', 'id', $id)) {
2171 return false;
2172 }
2173 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2174 return false;
2175 }
dcd338ff 2176 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2177 foreach($events as $event) {
48e535bc 2178 if ($visible) {
2179 show_event($event);
2180 } else {
2181 hide_event($event);
2182 }
dcd338ff 2183 }
2184 }
02f66c42 2185 if ($prevstateoverrides) {
2186 if ($visible == '0') {
2187 // Remember the current visible state so we can toggle this back.
2188 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2189 } else {
2190 // Get the previous saved visible states.
2191 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2192 }
2193 }
48e535bc 2194 return set_field("course_modules", "visible", $visible, "id", $id);
1acfbce5 2195}
2196
290130b3 2197/*
2198 * Delete a course module and any associated data at the course level (events)
264867fd 2199 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2200 * deletes it completely.
2201 *
2202 */
48e535bc 2203function delete_course_module($id) {
f615fbab 2204 global $CFG;
2205 require_once($CFG->libdir.'/gradelib.php');
2206
290130b3 2207 if (!$cm = get_record('course_modules', 'id', $id)) {
2208 return true;
2209 }
dcd338ff 2210 $modulename = get_field('modules', 'name', 'id', $cm->module);
f615fbab 2211 //delete events from calendar
dcd338ff 2212 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2213 foreach($events as $event) {
0ea03696 2214 delete_event($event->id);
dcd338ff 2215 }
2216 }
f615fbab 2217 //delete grade items, outcome items and grades attached to modules
2218 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2219 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2220 foreach ($grade_items as $grade_item) {
2221 $grade_item->delete('moddelete');
2222 }
2223
2224 }
290130b3 2225 return delete_records('course_modules', 'id', $cm->id);
11b0c469 2226}
2227
2228function delete_mod_from_section($mod, $section) {
11b0c469 2229
e5dfd0f3 2230 if ($section = get_record("course_sections", "id", "$section") ) {
11b0c469 2231
e5dfd0f3 2232 $modarray = explode(",", $section->sequence);
11b0c469 2233
2234 if ($key = array_keys ($modarray, $mod)) {
2235 array_splice($modarray, $key[0], 1);
2236 $newsequence = implode(",", $modarray);
e5dfd0f3 2237 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
11b0c469 2238 } else {
2239 return false;
2240 }
89adb174 2241
11b0c469 2242 }
7977cffd 2243 return false;
11b0c469 2244}
2245
12905134 2246function move_section($course, $section, $move) {
2247/// Moves a whole course section up and down within the course
798b70a1 2248 global $USER;
12905134 2249
2250 if (!$move) {
2251 return true;
2252 }
2253
2254 $sectiondest = $section + $move;
2255
2256 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2257 return false;
2258 }
2259
2260 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2261 return false;
2262 }
2263
2264 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2265 return false;
2266 }
2267
56e34ee4 2268 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
12905134 2269 return false;
2270 }
56e34ee4 2271 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
12905134 2272 return false;
2273 }
798b70a1 2274 // if the focus is on the section that is being moved, then move the focus along
2275 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2276 course_set_display($course->id, $sectiondest);
2277 }
5390cbb7 2278
a987106d 2279 // Check for duplicates and fix order if needed.
5390cbb7 2280 // There is a very rare case that some sections in the same course have the same section id.
a987106d 2281 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2282 $n = 0;
2283 foreach ($sections as $section) {
2284 if ($section->section != $n) {
5390cbb7 2285 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2286 return false;
2287 }
5390cbb7 2288 }
a987106d 2289 $n++;
5390cbb7 2290 }
12905134 2291 return true;
2292}
2293
2294
7977cffd 2295function moveto_module($mod, $section, $beforemod=NULL) {
2296/// All parameters are objects
2297/// Move the module object $mod to the specified $section
2298/// If $beforemod exists then that is the module
2299/// before which $modid should be inserted
2300
2301/// Remove original module from original section
2302
2303 if (! delete_mod_from_section($mod->id, $mod->section)) {
2304 notify("Could not delete module from existing section");
2305 }
2306
2307/// Update module itself if necessary
2308
2309 if ($mod->section != $section->id) {
89adb174 2310 $mod->section = $section->id;
7977cffd 2311 if (!update_record("course_modules", $mod)) {
2312 return false;
2313 }
48e535bc 2314 // if moving to a hidden section then hide module
2315 if (!$section->visible) {
2316 set_coursemodule_visible($mod->id, 0);
2317 }
7977cffd 2318 }
2319
2320/// Add the module into the new section
2321
2322 $mod->course = $section->course;
2323 $mod->section = $section->section; // need relative reference
2324 $mod->coursemodule = $mod->id;
2325
2326 if (! add_mod_to_section($mod, $beforemod)) {
2327 return false;
2328 }
2329
2330 return true;
2331
2332}
2333
24e1eae4 2334function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
810393c8 2335 global $CFG, $USER;
94361e02 2336
3d575e6f 2337 static $str;
37a88449 2338 static $sesskey;
3d575e6f 2339
217a8ee9 2340 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2341 // no permission to edit
2342 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
e2cd3ed0 2343 return false;
217a8ee9 2344 }
2345
3d575e6f 2346 if (!isset($str)) {
90ebdf65 2347 $str->delete = get_string("delete");
2348 $str->move = get_string("move");
2349 $str->moveup = get_string("moveup");
2350 $str->movedown = get_string("movedown");
2351 $str->moveright = get_string("moveright");
2352 $str->moveleft = get_string("moveleft");
2353 $str->update = get_string("update");
2354 $str->duplicate = get_string("duplicate");
2355 $str->hide = get_string("hide");
2356 $str->show = get_string("show");
3d575e6f 2357 $str->clicktochange = get_string("clicktochange");
32d03b7b 2358 $str->forcedmode = get_string("forcedmode");
3d575e6f 2359 $str->groupsnone = get_string("groupsnone");
2360 $str->groupsseparate = get_string("groupsseparate");
2361 $str->groupsvisible = get_string("groupsvisible");
37a88449 2362 $sesskey = sesskey();
1acfbce5 2363 }
94361e02 2364
24e1eae4 2365 if ($section >= 0) {
75f087b6 2366 $section = '&amp;sr='.$section; // Section return
24e1eae4 2367 } else {
2368 $section = '';
2369 }
2370
94361e02 2371 if ($absolute) {
37a88449 2372 $path = $CFG->wwwroot.'/course';
dc0dc7d5 2373 } else {
37a88449 2374 $path = '.';
dc0dc7d5 2375 }
2376
217a8ee9 2377 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2378 if ($mod->visible) {
2379 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2380 '&amp;sesskey='.$sesskey.$section.'"><img'.
2381 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2382 ' alt="'.$str->hide.'" /></a>'."\n";
2383 } else {
2384 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2385 '&amp;sesskey='.$sesskey.$section.'"><img'.
2386 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2387 ' alt="'.$str->show.'" /></a>'."\n";
2388 }
7977cffd 2389 }
3d575e6f 2390 if ($mod->groupmode !== false) {
2391 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 2392 $grouptitle = $str->groupsseparate;
cddbd5d5 2393 $groupclass = 'editing_groupsseparate';
37a88449 2394 $groupimage = $CFG->pixpath.'/t/groups.gif';
2395 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 2396 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 2397 $grouptitle = $str->groupsvisible;
cddbd5d5 2398 $groupclass = 'editing_groupsvisible';
37a88449 2399 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2400 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 2401 } else {
2402 $grouptitle = $str->groupsnone;
90ebdf65 2403 $groupclass = 'editing_groupsnone';
37a88449 2404 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2405 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 2406 }
2407 if ($mod->groupmodelink) {
90ebdf65 2408 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
0d905d9f 2409 '<img src="'.$groupimage.'" class="iconsmall" '.
2410 'alt="'.$grouptitle.'" /></a>';
3d575e6f 2411 } else {
37a88449 2412 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
0d905d9f 2413 ' src="'.$groupimage.'" class="iconsmall" '.
2414 'alt="'.$grouptitle.'" />';
3d575e6f 2415 }
2416 } else {
2417 $groupmode = "";
2418 }
e2cd3ed0 2419
217a8ee9 2420 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2421 if ($moveselect) {
2422 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2423 '&amp;sesskey='.$sesskey.$section.'"><img'.
2424 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2425 ' alt="'.$str->move.'" /></a>'."\n";
2426 } else {
2427 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2428 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2429 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2430 ' alt="'.$str->moveup.'" /></a>'."\n".
2431 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2432 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2433 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2434 ' alt="'.$str->movedown.'" /></a>'."\n";
2435 }
7b44777e 2436 } else {
2437 $move = '';
7977cffd 2438 }
2439
932be046 2440 $leftright = '';
217a8ee9 2441 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
932be046 2442
8047ab1d 2443 if (right_to_left()) { // Exchange arrows on RTL
932be046 2444 $rightarrow = 'left.gif';
2445 $leftarrow = 'right.gif';
2446 } else {
2447 $rightarrow = 'right.gif';
2448 $leftarrow = 'left.gif';
2449 }
2450
217a8ee9 2451 if ($indent > 0) {
2452 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2453 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2454 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
217a8ee9 2455 ' alt="'.$str->moveleft.'" /></a>'."\n";
2456 }
2457 if ($indent >= 0) {
2458 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2459 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2460 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
217a8ee9 2461 ' alt="'.$str->moveright.'" /></a>'."\n";
2462 }
37a88449 2463 }
2464
90ebdf65 2465 return '<span class="commands">'."\n".$leftright.$move.
2466 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
37a88449 2467 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2468 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
90ebdf65 2469 ' alt="'.$str->update.'" /></a>'."\n".
2470 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
37a88449 2471 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2472 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
90ebdf65 2473 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
90845098 2474}
2475
b61efafb 2476/**
264867fd 2477 * given a course object with shortname & fullname, this function will
b61efafb 2478 * truncate the the number of chars allowed and add ... if it was too long
2479 */
2480function course_format_name ($course,$max=100) {
264867fd 2481
6ba65fa0 2482 $str = $course->shortname.': '. $course->fullname;
b61efafb 2483 if (strlen($str) <= $max) {
2484 return $str;
2485 }
2486 else {
2487 return substr($str,0,$max-3).'...';
2488 }
2489}
2490
2491/**
2492 * This function will return true if the given course is a child course at all
2493 */
2494function course_in_meta ($course) {
5f37b628 2495 return record_exists("course_meta","child_course",$course->id);
b61efafb 2496}
2497
48e535bc 2498
2499/**
2500 * Print standard form elements on module setup forms in mod/.../mod.html
2501 */
263017bb 2502function print_standard_coursemodule_settings($form, $features=null) {
da2224f8 2503 if (! $course = get_record('course', 'id', $form->course)) {
2504 error("This course doesn't exist");
2505 }
2506 print_groupmode_setting($form, $course);
263017bb 2507 if (!empty($features->groupings)) {
2508 print_grouping_settings($form, $course);
2509 }
da2224f8 2510 print_visible_setting($form, $course);
48e535bc 2511}
2512
2513/**
2514 * Print groupmode form element on module setup forms in mod/.../mod.html
2515 */
5ebb746b 2516function print_groupmode_setting($form, $course=NULL) {
48e535bc 2517
5ebb746b 2518 if (empty($course)) {
2519 if (! $course = get_record('course', 'id', $form->course)) {
2520 error("This course doesn't exist");
2521 }
2522 }
48e535bc 2523 if ($form->coursemodule) {
2524 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2525 error("This course module doesn't exist");
2526 }
ffc536af 2527 $groupmode = groups_get_activity_groupmode($cm);
48e535bc 2528 } else {
2529 $cm = null;
ffc536af 2530 $groupmode = groups_get_course_groupmode($course);
48e535bc 2531 }
48e535bc 2532 if ($course->groupmode or (!$course->groupmodeforce)) {
2533 echo '<tr valign="top">';
2534 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 2535 echo '<td align="left">';
ffc536af 2536 $choices = array();
48e535bc 2537 $choices[NOGROUPS] = get_string('groupsnone');
2538 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2539 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2540 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2541 helpbutton('groupmode', get_string('groupmode'));
2542 echo '</td></tr>';
2543 }
2544}
2545
263017bb 2546/**
2547 * Print groupmode form element on module setup forms in mod/.../mod.html
2548 */
2549function print_grouping_settings($form, $course=NULL) {
2550
2551 if (empty($course)) {
2552 if (! $course = get_record('course', 'id', $form->course)) {
2553 error("This course doesn't exist");
2554 }
2555 }
2556 if ($form->coursemodule) {
2557 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2558 error("This course module doesn't exist");
2559 }
2560 } else {
2561 $cm = null;
2562 }
2563
2564 $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
2565 if (!empty($groupings)) {
2566 echo '<tr valign="top">';
2567 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2568 echo '<td align="left">';
2569
2570 $groupings;
2571 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
2572
2573 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2574 echo '</td></tr>';
2575
2576 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2577 echo '<tr valign="top">';
2578 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2579 echo '<td align="left">';
2580 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2581 echo '</td></tr>';
2582
2583 }
2584}
2585
48e535bc 2586/**
2587 * Print visibility setting form element on module setup forms in mod/.../mod.html
2588 */
5ebb746b 2589function print_visible_setting($form, $course=NULL) {
1ee55c41 2590 if (empty($course)) {
2591 if (! $course = get_record('course', 'id', $form->course)) {
2592 error("This course doesn't exist");
2593 }
2594 }
48e535bc 2595 if ($form->coursemodule) {
2596 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2597 } else {
2598 $visible = true;
2599 }
2600
2601 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2602 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2603 } else {
2604 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2605 }
2606 if ($hiddensection) {
2607 $visible = false;
2608 }
264867fd 2609
48e535bc 2610 echo '<tr valign="top">';
182311e4 2611 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
7bbe08a2 2612 echo '<td align="left">';
dd97c328 2613 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
48e535bc 2614 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2615 echo '</td></tr>';
264867fd 2616}
48e535bc 2617
0705ff84 2618function update_restricted_mods($course,$mods) {
ddb0a19f 2619
2620/// Delete all the current restricted list
2621 delete_records('course_allowed_modules','course',$course->id);
2622
0705ff84 2623 if (empty($course->restrictmodules)) {
ddb0a19f 2624 return; // We're done
0705ff84 2625 }
ddb0a19f 2626
2627/// Insert the new list of restricted mods
2628 foreach ($mods as $mod) {
2629 if ($mod == 0) {
2630 continue; // this is the 'allow none' option
0705ff84 2631 }
ddb0a19f 2632 $am = new object();
2633 $am->course = $course->id;
2634 $am->module = $mod;
2635 insert_record('course_allowed_modules',$am);
0705ff84 2636 }
2637}
2638
2639/**
2640 * This function will take an int (module id) or a string (module name)
2641 * and return true or false, whether it's allowed in the given course (object)
264867fd 2642 * $mod is not allowed to be an object, as the field for the module id is inconsistent
0705ff84 2643 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2644 */
2645
2646function course_allowed_module($course,$mod) {
ddb0a19f 2647
0705ff84 2648 if (empty($course->restrictmodules)) {
2649 return true;
2650 }
264867fd 2651
ddb0a19f 2652 // Admins and admin-like people who can edit everything can also add anything.
2653 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
51792df0 2654 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
0705ff84 2655 return true;
2656 }
ddb0a19f 2657
0705ff84 2658 if (is_numeric($mod)) {
2659 $modid = $mod;
2660 } else if (is_string($mod)) {
ddb0a19f 2661 $modid = get_field('modules','id','name',$mod);
0705ff84 2662 }
2663 if (empty($modid)) {
2664 return false;
2665 }
ddb0a19f 2666
2667 return (record_exists('course_allowed_modules','course',$course->id,'module',$modid));
0705ff84 2668}
2669
861efb19 2670/***
2671 *** Efficiently moves many courses around while maintaining
2672 *** sortorder in order.
264867fd 2673 ***
861efb19 2674 *** $courseids is an array of course ids
2675 ***
2676 **/
2677
2678function move_courses ($courseids, $categoryid) {
2679
2680 global $CFG;
2681
2682 if (!empty($courseids)) {
264867fd 2683
2684 $courseids = array_reverse($courseids);
861efb19 2685
2686 foreach ($courseids as $courseid) {
264867fd 2687
861efb19 2688 if (! $course = get_record("course", "id", $courseid)) {
2689 notify("Error finding course $courseid");
2690 } else {
2691 // figure out a sortorder that we can use in the destination category
2692 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2693 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2694 if ($sortorder === false) {
2695 // the category is empty
2696 // rather than let the db default to 0
264867fd 2697 // set it to > 100 and avoid extra work in fix_coursesortorder()
861efb19 2698 $sortorder = 200;
2699 } else if ($sortorder < 10) {
2700 fix_course_sortorder($categoryid);
2701 }
2702
2703 $course->category = $categoryid;
2704 $course->sortorder = $sortorder;
2705 $course->fullname = addslashes($course->fullname);
2706 $course->shortname = addslashes($course->shortname);
2707 $course->summary = addslashes($course->summary);
2708 $course->password = addslashes($course->password);
2709 $course->teacher = addslashes($course->teacher);
2710 $course->teachers = addslashes($course->teachers);
2711 $course->student = addslashes($course->student);
2712 $course->students = addslashes($course->students);
264867fd 2713
861efb19 2714 if (!update_record('course', $course)) {
2715 notify("An error occurred - course not moved!");
2716 }
19f601d1 2717
2718 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2719 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2720 context_moved($context, $newparent);
861efb19 2721 }
2722 }
2723 fix_course_sortorder();
264867fd 2724 }
861efb19 2725 return true;
2726}
2727
19f601d1 2728/***
2729 *** Efficiently moves a category - NOTE that this can have
2730 *** a huge impact access-control-wise...
2731 ***
2732 ***
2733 **/
2734function move_category ($category, $newparentcat) {
2735
2736 global $CFG;
2737
1f41940f 2738 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2739
2740 if (empty($newparentcat->id)) {
2741 if (!set_field('course_categories', 'parent', 0, 'id', $category->id)) {
2742 return false;
2743 }
2744 $newparent = get_context_instance(CONTEXT_SYSTEM);
2745 } else {
2746 if (!set_field('course_categories', 'parent', $newparentcat->id, 'id', $category->id)) {
2747 return false;
2748 }
2749 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
19f601d1 2750 }
2751
19f601d1 2752 context_moved($context, $newparent);
2753
2754 // The most effective thing would be to find the common parent,
2755 // until then, do it sitewide...
2756 fix_course_sortorder();
2757
2758
2759 return true;
2760}
2761
ae628043 2762/**
2763 * @param string $format Course format ID e.g. 'weeks'
2764 * @return Name that the course format prefers for sections
2765 */
2766function get_section_name($format) {
2767 $sectionname = get_string("name$format","format_$format");
2768 if($sectionname == "[[name$format]]") {
2769 $sectionname = get_string("name$format");
2770 }
a044c05d 2771 return $sectionname;
ae628043 2772}
2773
2585a68d 2774/**
2775 * Can the current user delete this course?
2776 * @param int $courseid
2777 * @return boolean
2778 *
2779 * Exception here to fix MDL-7796.
2780 *
2781 * FIXME
2782 * Course creators who can manage activities in the course
2783 * shoule be allowed to delete the course. We do it this
2784 * way because we need a quick fix to bring the functionality
2785 * in line with what we had pre-roles. We can't give the
2786 * default course creator role moodle/course:delete at
2787 * CONTEXT_SYSTEM level because this will allow them to
2788 * delete any course in the site. So we hard code this here
2789 * for now.
2790 *
2791 * @author vyshane AT gmail.com
2792 */
2793function can_delete_course($courseid) {
2794
2795 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2796
2797 return ( has_capability('moodle/course:delete', $context)
2798 || (has_capability('moodle/legacy:coursecreator', $context)
2799 && has_capability('moodle/course:manageactivities', $context)) );
2800}
2801
2802
bfefa87e 2803/*
2804 * Create a course and either return a $course object or false
2805 *
2806 * @param object $data - all the data needed for an entry in the 'course' table
2807 */
2808function create_course($data) {
2809 global $CFG, $USER;
2810
2811 // preprocess allowed mods
2812 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2813 unset($data->allowedmods);
ddb0a19f 2814 if ($CFG->restrictmodulesfor == 'all') {
2815 $data->restrictmodules = 1;
2816 } else {
2817 $data->restrictmodules = 0;
bfefa87e 2818 }
2585a68d 2819
bfefa87e 2820 $data->timecreated = time();
2821
2822 // place at beginning of category
2823 fix_course_sortorder();
2824 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2825 if (empty($data->sortorder)) {
2826 $data->sortorder = 100;
2827 }
2828
2829 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2830
2831 $course = get_record('course', 'id', $newcourseid);
2832
2833 // Setup the blocks
2834 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2835 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2836
ddb0a19f 2837 update_restricted_mods($course, $allowedmods);
bfefa87e 2838
2839 $section = new object();
2840 $section->course = $course->id; // Create a default section.
2841 $section->section = 0;
2842 $section->id = insert_record('course_sections', $section);
2843
2844 fix_course_sortorder();
2845
2846 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2847
2848 return $course;
2849 }
2850
2851 return false; // error
2852}
2853
2854
2855/*
2856 * Update a course and return true or false
2857 *
2858 * @param object $data - all the data needed for an entry in the 'course' table
2859 */
2860function update_course($data) {
2861 global $USER, $CFG;
2862
ddb0a19f 2863 // Preprocess allowed mods
bfefa87e 2864 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2865 unset($data->allowedmods);
ddb0a19f 2866
2867 // Normal teachers can't change setting
bfefa87e 2868 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2869 unset($data->restrictmodules);
2870 }
2871
a372aab5 2872 $movecat = false;
bfefa87e 2873 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2874 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2875 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2876 // can not move to new category, keep the old one
2877 unset($data->category);
a372aab5 2878 } elseif ($oldcourse->category != $data->category) {
2879 $movecat = true;
bfefa87e 2880 }
2881
2882 // Update with the new data
2883 if (update_record('course', $data)) {
2884
2885 $course = get_record('course', 'id', $data->id);
2886
0be70104 2887 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
bfefa87e 2888
ddb0a19f 2889 // "Admins" can change allowed mods for a course
bfefa87e 2890 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2891 update_restricted_mods($course, $allowedmods);
2892 }
2893
a372aab5 2894 if ($movecat) {
2895 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2896 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2897 context_moved($context, $newparent);
2898 }
2899
bfefa87e 2900 fix_course_sortorder();
2901
2902 // Test for and remove blocks which aren't appropriate anymore
2903 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2904 blocks_remove_inappropriate($page);
2905
2906 // put custom role names into db
2907 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2908
2909 foreach ($data as $dname => $dvalue) {
2910
2911 // is this the right param?
2912 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2913
2914 if (!strstr($dname, 'role_')) {
2915 continue;
2916 }
2917
2918 $dt = explode('_', $dname);
2919 $roleid = $dt[1];
2920 // make up our mind whether we want to delete, update or insert
2921
2922 if (empty($dvalue)) {
2923
2924 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2925
2926 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2927
87486420 2928 $t->name = $dvalue;
bfefa87e 2929 update_record('role_names', $t);
2930
2931 } else {
2932
2933 $t->contextid = $context->id;
2934 $t->roleid = $roleid;
87486420 2935 $t->name = $dvalue;
bfefa87e 2936 insert_record('role_names', $t);
2937 }
2938
2939 }
2940
2941 return true;
2942
2943 }
2944
2945 return false;
2946}
2585a68d 2947
7f9c4fb9 2948?>