MDL-13274, MDL-13215 - improved modedit shared forms, label supports groupmembersonly...
[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 }
1331
dd97c328 1332 } else { // Normal activity
1333 $instancename = format_string($modinfo->cms[$modnumber]->name, true, $course->id);
c9f6251e 1334
dd97c328 1335 if (!empty($modinfo->cms[$modnumber]->icon)) {
1336 $icon = "$CFG->pixpath/".$modinfo->cms[$modnumber]->icon;
1337 } else {
1338 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1339 }
e0b033d5 1340
dd97c328 1341 //Accessibility: for files get description via icon.
1342 $altname = '';
1343 if ('resource'==$mod->modname) {
1344 if (!empty($modinfo->cms[$modnumber]->icon)) {
1345 $possaltname = $modinfo->cms[$modnumber]->icon;
6285f8a8 1346
dd97c328 1347 $mimetype = mimeinfo_from_icon('type', $possaltname);
1348 $altname = get_mimetype_description($mimetype);
6285f8a8 1349 } else {
1350 $altname = $mod->modfullname;
1351 }
dd97c328 1352 } else {
1353 $altname = $mod->modfullname;
1354 }
1355 // Avoid unnecessary duplication.
1356 if (false!==stripos($instancename, $altname)) {
1357 $altname = '';
1358 }
1359 // File type after name, for alphabetic lists (screen reader).
1360 if ($altname) {
1361 $altname = get_accesshide(' '.$altname);
1362 }
6285f8a8 1363
dd97c328 1364 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1365 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1366 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1367 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1368 $instancename.$altname.'</span></a>';
806ebc15 1369
dd97c328 1370 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1371 if (!isset($groupings)) {
1372 $groupings = groups_get_all_groupings($course->id);
acf000b0 1373 }
dd97c328 1374 echo " <span class=\"groupinglabel\"> - ".format_string($groupings[$mod->groupingid]->name).'</span>';
c9f6251e 1375 }
dd97c328 1376 }
1377 if ($usetracking && $mod->modname == 'forum') {
1378 if ($usetracking and !isset($untracked[$mod->instance])) {
1379 $groupid = groups_get_activity_group($mod);
1380 $unread = forum_tp_count_forum_unread_posts($USER->id, $mod->instance, $groupid);
1381 if ($unread) {
1382 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1383 if ($unread == 1) {
1384 echo $strunreadpostsone;
1385 } else {
1386 print_string('unreadpostsnumber', 'forum', $unread);
d0388ebe 1387 }
dd97c328 1388 echo '</a> </span>';
54669989 1389 }
f37da850 1390 }
dd97c328 1391 }
f37da850 1392
dd97c328 1393 if ($isediting) {
1394 // TODO: we must define this as mod property!
1395 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1396 if (! $mod->groupmodelink = $groupbuttonslink) {
1397 $mod->groupmode = $course->groupmode;
3d575e6f 1398 }
dd97c328 1399
1400 } else {
1401 $mod->groupmode = false;
c9f6251e 1402 }
dd97c328 1403 echo '&nbsp;&nbsp;';
1404 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
94361e02 1405 }
dd97c328 1406 echo "</li>\n";
94361e02 1407 }
dd97c328 1408
f2d660dc 1409 } elseif ($ismoving) {
1410 echo "<ul class=\"section\">\n";
264867fd 1411 }
dd97c328 1412
7977cffd 1413 if ($ismoving) {
64fdc686 1414 echo '<li><a title="'.$strmovefull.'"'.
8b92f5bb 1415 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
446390fb 1416 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
c6a55371 1417 ' alt="'.$strmovehere.'" /></a></li>
1c919752 1418 ';
7977cffd 1419 }
c6a55371 1420 if (!empty($section->sequence) || $ismoving) {
1421 echo "</ul><!--class='section'-->\n\n";
1422 }
a7ad3ea6 1423}
1424
89bfeee0 1425/**
1426 * Prints the menus to add activities and resources.
1427 */
cb57e6f4 1428function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
89bfeee0 1429 global $CFG;
e0161bff 1430
217a8ee9 1431 // check to see if user can add menus
1432 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
e2cd3ed0 1433 return false;
217a8ee9 1434 }
1435
89bfeee0 1436 static $resources = false;
1437 static $activities = false;
e0161bff 1438
89bfeee0 1439 if ($resources === false) {
1440 $resources = array();
1441 $activities = array();
6da4b261 1442
89bfeee0 1443 foreach($modnames as $modname=>$modnamestr) {
1444 if (!course_allowed_module($course, $modname)) {
1445 continue;
1446 }
6da4b261 1447
ffd58dd6 1448 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1449 if (!file_exists($libfile)) {
1450 continue;
1451 }
1452 include_once($libfile);
89bfeee0 1453 $gettypesfunc = $modname.'_get_types';
1454 if (function_exists($gettypesfunc)) {
1455 $types = $gettypesfunc();
1456 foreach($types as $type) {
65bcf17b 1457 if (!isset($type->modclass) or !isset($type->typestr)) {
1458 debugging('Incorrect ativity type in '.$modname);
1459 continue;
1460 }
89bfeee0 1461 if ($type->modclass == MOD_CLASS_RESOURCE) {
1462 $resources[$type->type] = $type->typestr;
1463 } else {
1464 $activities[$type->type] = $type->typestr;
1465 }
1466 }
1467 } else {
1468 // all mods without type are considered activity
1469 $activities[$modname] = $modnamestr;
1470 }
0705ff84 1471 }
e0161bff 1472 }
1473
89bfeee0 1474 $straddactivity = get_string('addactivity');
1475 $straddresource = get_string('addresource');
1476
4f24b3e3 1477 $output = '<div class="section_add_menus">';
1478
1479 if (!$vertical) {
1480 $output .= '<div class="horizontal">';
1481 }
89bfeee0 1482
1483 if (!empty($resources)) {
1484 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
0705ff84 1485 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1486 }
cb57e6f4 1487
89bfeee0 1488 if (!empty($activities)) {
1489 $output .= ' ';
1490 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1491 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
0705ff84 1492 }
1493
4f24b3e3 1494 if (!$vertical) {
d33d0cda 1495 $output .= '</div>';
1496 }
1497
cb57e6f4 1498 $output .= '</div>';
1499
1500 if ($return) {
1501 return $output;
1502 } else {
1503 echo $output;
1504 }
e0161bff 1505}
1506
f36cbf1d 1507/**
1508 * Rebuilds the cached list of course activities stored in the database
1509 * @param int $courseid - id of course to rebuil, empty means all
1510 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1511 */
1512function rebuild_course_cache($courseid=0, $clearonly=false) {
dd97c328 1513 global $COURSE;
f36cbf1d 1514
1515 if ($clearonly) {
1516 $courseselect = empty($courseid) ? "" : "id = $courseid";
1517 set_field_select('course', 'modinfo', null, $courseselect);
1518 // update cached global COURSE too ;-)
1519 if ($courseid == $COURSE->id) {
1520 $COURSE->modinfo = null;
1521 }
1522 // reset the fast modinfo cache
1523 $reset = 'reset';
1524 get_fast_modinfo($reset);
1525 return;
1526 }
5867bfb5 1527
1528 if ($courseid) {
1529 $select = "id = '$courseid'";
1530 } else {
1531 $select = "";
6cf890e3 1532 @set_time_limit(0); // this could take a while! MDL-10954
5867bfb5 1533 }
1534
f36cbf1d 1535 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1536 while($course = rs_fetch_next_record($rs)) {
5867bfb5 1537 $modinfo = serialize(get_array_of_activities($course->id));
1538 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
6ba65fa0 1539 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
5867bfb5 1540 }
dd97c328 1541 // update cached global COURSE too ;-)
1542 if ($course->id == $COURSE->id) {
1543 $COURSE->modinfo = $modinfo;
1544 }
5867bfb5 1545 }
f36cbf1d 1546 rs_close($rs);
5867bfb5 1547 }
dd97c328 1548 // reset the fast modinfo cache
65a00c97 1549 $reset = 'reset';
1550 get_fast_modinfo($reset);
5867bfb5 1551}
1552
9bb19e58 1553function get_child_categories($parent) {
1554/// Returns an array of the children categories for the given category
1555/// ID by caching all of the categories in a static hash
1556
1557 static $allcategories = null;
1558
1559 // only fill in this variable the first time
1560 if (null == $allcategories) {
1561 $allcategories = array();
1562
1563 $categories = get_categories();
1564 foreach ($categories as $category) {
1565 if (empty($allcategories[$category->parent])) {
1566 $allcategories[$category->parent] = array();
1567 }
1568 $allcategories[$category->parent][] = $category;
1569 }
1570 }
1571
1572 if (empty($allcategories[$parent])) {
1573 return array();
1574 } else {
1575 return $allcategories[$parent];
1576 }
1577}
1578
c2cb4545 1579
1580function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
89adb174 1581/// Given an empty array, this function recursively travels the
c2cb4545 1582/// categories, building up a nice list for display. It also makes
1583/// an array that list all the parents for each category.
1584
9d866ae0 1585 // initialize the arrays if needed
1586 if (!is_array($list)) {
264867fd 1587 $list = array();
9d866ae0 1588 }
1589 if (!is_array($parents)) {
264867fd 1590 $parents = array();
9d866ae0 1591 }
1592
c2cb4545 1593 if ($category) {
1594 if ($path) {
6ba65fa0 1595 $path = $path.' / '.format_string($category->name);
c2cb4545 1596 } else {
6ba65fa0 1597 $path = format_string($category->name);
c2cb4545 1598 }
1599 $list[$category->id] = $path;
1600 } else {
1601 $category->id = 0;
1602 }
1603
9bb19e58 1604 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1605 foreach ($categories as $cat) {
1606 if (!empty($category->id)) {
3bd4de22 1607 if (isset($parents[$category->id])) {
2832badf 1608 $parents[$cat->id] = $parents[$category->id];
1609 }
c2cb4545 1610 $parents[$cat->id][] = $category->id;
1611 }
89adb174 1612 make_categories_list($list, $parents, $cat, $path);
c2cb4545 1613 }
1614 }
1615}
1616
1617
d157bd5b 1618function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
89adb174 1619/// Recursive function to print out all the categories in a nice format
c2cb4545 1620/// with or without courses included
9ff5310a 1621 global $CFG;
e05bcf2f 1622
1623 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1624 return;
9ff5310a 1625 }
c2cb4545 1626
1627 if (!$displaylist) {
e92fe848 1628 make_categories_list($displaylist, $parentslist);
c2cb4545 1629 }
1630
1631 if ($category) {
ec7a8b79 1632 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6f24e48e 1633 print_category_info($category, $depth, $files);
c2cb4545 1634 } else {
1635 return; // Don't bother printing children of invisible categories
1636 }
89adb174 1637
c2cb4545 1638 } else {
c2cb4545 1639 $category->id = "0";
1640 }
1641
9bb19e58 1642 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
c2cb4545 1643 $countcats = count($categories);
1644 $count = 0;
1645 $first = true;
1646 $last = false;
1647 foreach ($categories as $cat) {
1648 $count++;
1649 if ($count == $countcats) {
1650 $last = true;
1651 }
1652 $up = $first ? false : true;
1653 $down = $last ? false : true;
1654 $first = false;
1655
6f24e48e 1656 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
c2cb4545 1657 }
1658 }
c2cb4545 1659}
1660
0705ff84 1661// this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1662
1663function make_categories_options() {
1664 make_categories_list($cats,$parents);
1665 foreach ($cats as $key => $value) {
1666 if (array_key_exists($key,$parents)) {
1667 if ($indent = count($parents[$key])) {
1668 for ($i = 0; $i < $indent; $i++) {
1669 $cats[$key] = '&nbsp;'.$cats[$key];
1670 }
1671 }
1672 }
1673 }
1674 return $cats;
1675}
c2cb4545 1676
6f24e48e 1677function print_category_info($category, $depth, $files = false) {
d2b6ba70 1678/// Prints the category info in indented fashion
1679/// This function is only used by print_whole_category_list() above
c2cb4545 1680
1681 global $CFG;
b48f834c 1682 static $strallowguests, $strrequireskey, $strsummary;
c2cb4545 1683
b48f834c 1684 if (empty($strsummary)) {
e05bcf2f 1685 $strallowguests = get_string('allowguests');
1686 $strrequireskey = get_string('requireskey');
1687 $strsummary = get_string('summary');
b48f834c 1688 }
ba2e5d73 1689
e05bcf2f 1690 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
d5f26b07 1691
6f24e48e 1692 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1693 if ($files and $coursecount) {
fcf9577a 1694 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
b48f834c 1695 } else {
7b0b5c14 1696 $catimage = "&nbsp;";
8ef9cb56 1697 }
b48f834c 1698
fcf9577a 1699 echo "\n\n".'<table class="categorylist">';
d2b6ba70 1700
7ffcbfe1 1701 $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 1702 if ($files and $coursecount) {
b48f834c 1703
978abb42 1704 echo '<tr>';
b48f834c 1705
1706 if ($depth) {
1707 $indent = $depth*30;
1708 $rows = count($courses) + 1;
1c919752 1709 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
b48f834c 1710 print_spacer(10, $indent);
e05bcf2f 1711 echo '</td>';
b48f834c 1712 }
89adb174 1713
9deaeaa1 1714 echo '<td valign="top" class="category image">'.$catimage.'</td>';
fcf9577a 1715 echo '<td valign="top" class="category name">';
6ba65fa0 1716 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1717 echo '</td>';
290130b3 1718 echo '<td class="category info">&nbsp;</td>';
e05bcf2f 1719 echo '</tr>';
b48f834c 1720
9ff5310a 1721 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
c2cb4545 1722 foreach ($courses as $course) {
e05bcf2f 1723 $linkcss = $course->visible ? '' : ' class="dimmed" ';
fcf9577a 1724 echo '<tr><td valign="top">&nbsp;';
1725 echo '</td><td valign="top" class="course name">';
6ba65fa0 1726 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
fcf9577a 1727 echo '</td><td align="right" valign="top" class="course info">';
c2cb4545 1728 if ($course->guest ) {
e05bcf2f 1729 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1730 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
ebe8ddc1 1731 } else {
fcf9577a 1732 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1733 }
c2cb4545 1734 if ($course->password) {
e05bcf2f 1735 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
fcf9577a 1736 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
ebe8ddc1 1737 } else {
fcf9577a 1738 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
b48f834c 1739 }
1740 if ($course->summary) {
e05bcf2f 1741 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
fcf9577a 1742 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
b48f834c 1743 400, 500, $strsummary);
ebe8ddc1 1744 } else {
fcf9577a 1745 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
0c656181 1746 }
e05bcf2f 1747 echo '</td></tr>';
0c656181 1748 }
ba2e5d73 1749 }
d2b6ba70 1750 } else {
b48f834c 1751
e0140f24 1752 echo '<tr>';
1753
b48f834c 1754 if ($depth) {
1755 $indent = $depth*20;
e05bcf2f 1756 echo '<td valign="top" width="'.$indent.'">';
b48f834c 1757 print_spacer(10, $indent);
e05bcf2f 1758 echo '</td>';
d2b6ba70 1759 }
89adb174 1760
fcf9577a 1761 echo '<td valign="top" class="category name">';
6ba65fa0 1762 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
e05bcf2f 1763 echo '</td>';
290130b3 1764 echo '<td valign="top" class="category number">';
7ffcbfe1 1765 if (count($courses)) {
1766 echo count($courses);
e05bcf2f 1767 }
1768 echo '</td></tr>';
c2cb4545 1769 }
e05bcf2f 1770 echo '</table>';
c2cb4545 1771}
1772
c2cb4545 1773
e0b033d5 1774
6c54240a 1775function print_courses($category) {
c2cb4545 1776/// Category is 0 (for all courses) or an object
1777
810393c8 1778 global $CFG;
c2cb4545 1779
4dde1463 1780 if (!is_object($category) && $category==0) {
9bb19e58 1781 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
4dde1463 1782 if (is_array($categories) && count($categories) == 1) {
90c2ca2e 1783 $category = array_shift($categories);
4dde1463 1784 $courses = get_courses_wmanagers($category->id,
1785 'c.sortorder ASC',
1786 array('password','summary','currency'));
90c2ca2e 1787 } else {
4dde1463 1788 $courses = get_courses_wmanagers('all',
1789 'c.sortorder ASC',
1790 array('password','summary','currency'));
90c2ca2e 1791 }
1792 unset($categories);
607809b3 1793 } else {
4dde1463 1794 $courses = get_courses_wmanagers($category->id,
1795 'c.sortorder ASC',
1796 array('password','summary','currency'));
c2cb4545 1797 }
1798
49cd4d79 1799 if ($courses) {
8fee6c60 1800 echo '<ul class="unlist">';
c2cb4545 1801 foreach ($courses as $course) {
4dde1463 1802 if ($course->visible == 1
003bbcc8 1803 || has_capability('moodle/course:viewhiddencourses',$course->context)) {
8fee6c60 1804 echo '<li>';
4dde1463 1805 print_course($course);
8fee6c60 1806 echo "</li>\n";
4dde1463 1807 }
c2cb4545 1808 }
8fee6c60 1809 echo "</ul>\n";
c2cb4545 1810 } else {
f9667a5a 1811 print_heading(get_string("nocoursesyet"));
954fdb42 1812 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1813 if (has_capability('moodle/course:create', $context)) {
255d1033 1814 $options = array();
1815 $options['category'] = $category->id;
6b7425d2 1816 echo '<div class="addcoursebutton">';
255d1033 1817 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1818 echo '</div>';
1819 }
c2cb4545 1820 }
86dd62a7 1821
1822
1823
c2cb4545 1824}
1825
1826
35d0244a 1827function print_course($course) {
c2cb4545 1828
861efb19 1829 global $CFG, $USER;
c2cb4545 1830
4dde1463 1831 if (isset($course->context)) {
1832 $context = $course->context;
1833 } else {
1834 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1835 }
146bbb8f 1836
88768091 1837 $linkcss = $course->visible ? '' : ' class="dimmed" ';
22288704 1838
7cd266e9 1839 echo '<div class="coursebox clearfix">';
afba7be1 1840 echo '<div class="info">';
7f9c4fb9 1841 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
e5e81e78 1842 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
6ba65fa0 1843 format_string($course->fullname).'</a></div>';
b06334e8 1844
d42c64ba 1845 /// first find all roles that are supposed to be displayed
4dde1463 1846
6b4d8c4d 1847 if (!empty($CFG->coursemanager)) {
1848 $managerroles = split(',', $CFG->coursemanager);
3bf13d05 1849 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
4dde1463 1850 $namesarray = array();
1851 if (isset($course->managers)) {
1852 if (count($course->managers)) {
1853 $rusers = $course->managers;
1854 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
b682cee9 1855
1856 /// Rename some of the role names if needed
1857 if (isset($context)) {
1858 $aliasnames = get_records('role_names', 'contextid', $context->id,'','roleid,contextid,text');
1859 }
1860
4dde1463 1861 foreach ($rusers as $ra) {
1862 if ($ra->hidden == 0 || $canseehidden) {
1863 $fullname = fullname($ra->user, $canviewfullnames);
b682cee9 1864
1865 if (isset($aliasnames[$ra->roleid])) {
1866 $ra->rolename = $aliasnames[$ra->roleid]->text;
1867 }
1868
4dde1463 1869 $namesarray[] = format_string($ra->rolename)
1870 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
1871 . $fullname . '</a>';
1872 }
1873 }
1874 }
1875 } else {
6b4d8c4d 1876 $rusers = get_role_users($managerroles, $context,
4dde1463 1877 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1878 if (is_array($rusers) && count($rusers)) {
1879 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1880 foreach ($rusers as $teacher) {
1881 $fullname = fullname($teacher, $canviewfullnames);
1882 $namesarray[] = format_string($teacher->rolename)
1883 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
1884 . $fullname . '</a>';
1885 }
431cad0d 1886 }
c2cb4545 1887 }
431cad0d 1888
d42c64ba 1889 if (!empty($namesarray)) {
88768091 1890 echo "<ul class=\"teachers\">\n<li>";
1891 echo implode('</li><li>', $namesarray);
1892 echo "</li></ul>";
1893 }
c2cb4545 1894 }
d42c64ba 1895
88768091 1896 require_once("$CFG->dirroot/enrol/enrol.class.php");
1897 $enrol = enrolment_factory::factory($course->enrol);
146bbb8f 1898 echo $enrol->get_access_icons($course);
c2cb4545 1899
afba7be1 1900 echo '</div><div class="summary">';
9f39c190 1901 $options = NULL;
1902 $options->noclean = true;
34b5847a 1903 $options->para = false;
9f39c190 1904 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
afba7be1 1905 echo '</div>';
1906 echo '</div>';
c2cb4545 1907}
1908
1909
1910function print_my_moodle() {
1911/// Prints custom user information on the home page.
1912/// Over time this can include all sorts of information
1913
1914 global $USER, $CFG;
1915
86a1ba04 1916 if (empty($USER->id)) {
c2cb4545 1917 error("It shouldn't be possible to see My Moodle without being logged in.");
1918 }
1919
5b9e50ca 1920 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
86dd62a7 1921 $rhosts = array();
1922 $rcourses = array();
36e6379e 1923 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
86dd62a7 1924 $rcourses = get_my_remotecourses($USER->id);
643b67b8 1925 $rhosts = get_my_remotehosts();
86dd62a7 1926 }
1927
1928 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1929
1930 if (!empty($courses)) {
8fee6c60 1931 echo '<ul class="unlist">';
86dd62a7 1932 foreach ($courses as $course) {
1933 if ($course->id == SITEID) {
1934 continue;
1935 }
8fee6c60 1936 echo '<li>';
86dd62a7 1937 print_course($course, "100%");
8fee6c60 1938 echo "</li>\n";
86dd62a7 1939 }
8fee6c60 1940 echo "</ul>\n";
86dd62a7 1941 }
1942
1943 // MNET
1944 if (!empty($rcourses)) {
1945 // at the IDP, we know of all the remote courses
1946 foreach ($rcourses as $course) {
1947 print_remote_course($course, "100%");
1948 }
1949 } elseif (!empty($rhosts)) {
1950 // non-IDP, we know of all the remote servers, but not courses
1951 foreach ($rhosts as $host) {
643b67b8 1952 print_remote_host($host, "100%");
c81696e5 1953 }
c2cb4545 1954 }
86dd62a7 1955 unset($course);
1956 unset($host);
38a10939 1957
7f989948 1958 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1959 echo "<table width=\"100%\"><tr><td align=\"center\">";
1960 print_course_search("", false, "short");
1961 echo "</td><td align=\"center\">";
1962 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
1963 echo "</td></tr></table>\n";
1964 }
86dd62a7 1965
26330001 1966 } else {
1967 if (count_records("course_categories") > 1) {
cb29b020 1968 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
26330001 1969 print_whole_category_list();
1970 print_simple_box_end();
1971 } else {
35d0244a 1972 print_courses(0);
26330001 1973 }
607809b3 1974 }
2b8cef80 1975}
1976
11b0c469 1977
a8b56716 1978function print_course_search($value="", $return=false, $format="plain") {
38a10939 1979
1980 global $CFG;
1e0fb105 1981 static $count = 0;
1982
1983 $count++;
1984
1985 $id = 'coursesearch';
1986
1987 if ($count > 1) {
1988 $id .= $count;
1989 }
38a10939 1990
1991 $strsearchcourses= get_string("searchcourses");
1992
1c919752 1993 if ($format == 'plain') {
1e0fb105 1994 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 1995 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 1996 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
8fee6c60 1997 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
e42f4d92 1998 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 1999 $output .= '</fieldset></form>';
1c919752 2000 } else if ($format == 'short') {
1e0fb105 2001 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
fcf9577a 2002 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2003 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
8fee6c60 2004 $output .= '<input type="text" id="coursesearchbox" size="12" name="search" value="'.s($value, true).'" />';
e42f4d92 2005 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2006 $output .= '</fieldset></form>';
1c919752 2007 } else if ($format == 'navbar') {
fcf9577a 2008 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2009 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
e42f4d92 2010 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
8fee6c60 2011 $output .= '<input type="text" id="coursesearchbox" size="20" name="search" value="'.s($value, true).'" />';
e42f4d92 2012 $output .= '<input type="submit" value="'.get_string('go').'" />';
fcf9577a 2013 $output .= '</fieldset></form>';
a8b56716 2014 }
2015
2016 if ($return) {
2017 return $output;
2018 }
2019 echo $output;
38a10939 2020}
11b0c469 2021
86dd62a7 2022function print_remote_course($course, $width="100%") {
2023
2024 global $CFG, $USER;
2025
2026 $linkcss = '';
2027
2028 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2029
7cd266e9 2030 echo '<div class="coursebox remotecoursebox clearfix">';
86dd62a7 2031 echo '<div class="info">';
2032 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2033 $linkcss.' href="'.$url.'">'
6ba65fa0 2034 . format_string($course->fullname) .'</a><br />'
2035 . format_string($course->hostname) . ' : '
2036 . format_string($course->cat_name) . ' : '
2037 . format_string($course->shortname). '</div>';
86dd62a7 2038 echo '</div><div class="summary">';
2039 $options = NULL;
2040 $options->noclean = true;
2041 $options->para = false;
2042 echo format_text($course->summary, FORMAT_MOODLE, $options);
2043 echo '</div>';
2044 echo '</div>';
86dd62a7 2045}
2046
643b67b8 2047function print_remote_host($host, $width="100%") {
2048
2049 global $CFG, $USER;
2050
2051 $linkcss = '';
2052
7cd266e9 2053 echo '<div class="coursebox clearfix">';
643b67b8 2054 echo '<div class="info">';
2055 echo '<div class="name">';
2056 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2057 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2058 . s($host['name']).'</a> - ';
1fd80ad3 2059 echo $host['count'] . ' ' . get_string('courses');
643b67b8 2060 echo '</div>';
2061 echo '</div>';
caa90d56 2062 echo '</div>';
643b67b8 2063}
2064
86dd62a7 2065
11b0c469 2066/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2067
2068function add_course_module($mod) {
11b0c469 2069
e5dfd0f3 2070 $mod->added = time();
53f4ad2c 2071 unset($mod->id);
11b0c469 2072
e5dfd0f3 2073 return insert_record("course_modules", $mod);
11b0c469 2074}
2075
97928ddf 2076/**
2077 * Returns course section - creates new if does not exist yet.
2078 * @param int $relative section number
2079 * @param int $courseid
2080 * @return object $course_section object
2081 */
2082function get_course_section($section, $courseid) {
2083 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2084 return $cw;
2085 }
2086 $cw = new object();
2087 $cw->course = $courseid;
2088 $cw->section = $section;
2089 $cw->summary = "";
2090 $cw->sequence = "";
2091 $id = insert_record("course_sections", $cw);
2092 return get_record("course_sections", "id", $id);
2093}
ece966f0 2094/**
2095 * Given a full mod object with section and course already defined, adds this module to that section.
2096 *
2097 * @param object $mod
2098 * @param int $beforemod An existing ID which we will insert the new module before
2099 * @return int The course_sections ID where the mod is inserted
2100 */
7977cffd 2101function add_mod_to_section($mod, $beforemod=NULL) {
11b0c469 2102
9fa49e22 2103 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
7977cffd 2104
2105 $section->sequence = trim($section->sequence);
2106
2107 if (empty($section->sequence)) {
11b0c469 2108 $newsequence = "$mod->coursemodule";
7977cffd 2109
2110 } else if ($beforemod) {
2111 $modarray = explode(",", $section->sequence);
2112
2113 if ($key = array_keys ($modarray, $beforemod->id)) {
2114 $insertarray = array($mod->id, $beforemod->id);
2115 array_splice($modarray, $key[0], 1, $insertarray);
2116 $newsequence = implode(",", $modarray);
2117
2118 } else { // Just tack it on the end anyway
2119 $newsequence = "$section->sequence,$mod->coursemodule";
2120 }
2121
2122 } else {
2123 $newsequence = "$section->sequence,$mod->coursemodule";
11b0c469 2124 }
89adb174 2125
e5dfd0f3 2126 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2127 return $section->id; // Return course_sections ID that was used.
11b0c469 2128 } else {
e5dfd0f3 2129 return 0;
11b0c469 2130 }
89adb174 2131
11b0c469 2132 } else { // Insert a new record
e5dfd0f3 2133 $section->course = $mod->course;
2134 $section->section = $mod->section;
2135 $section->summary = "";
2136 $section->sequence = $mod->coursemodule;
2137 return insert_record("course_sections", $section);
11b0c469 2138 }
2139}
2140
48e535bc 2141function set_coursemodule_groupmode($id, $groupmode) {
3d575e6f 2142 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2143}
2144
24f41672 2145function set_coursemodule_groupingid($id, $groupingid) {
2146 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2147}
2148
2149function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2150 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2151}
2152
177d4abf 2153function set_coursemodule_idnumber($id, $idnumber) {
2154 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2155}
02f66c42 2156/**
2157* $prevstateoverrides = true will set the visibility of the course module
2158* to what is defined in visibleold. This enables us to remember the current
2159* visibility when making a whole section hidden, so that when we toggle
2160* that section back to visible, we are able to return the visibility of
2161* the course module back to what it was originally.
2162*/
2163function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
978abb42 2164 if (!$cm = get_record('course_modules', 'id', $id)) {
2165 return false;
2166 }
2167 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2168 return false;
2169 }
dcd338ff 2170 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2171 foreach($events as $event) {
48e535bc 2172 if ($visible) {
2173 show_event($event);
2174 } else {
2175 hide_event($event);
2176 }
dcd338ff 2177 }
2178 }
02f66c42 2179 if ($prevstateoverrides) {
2180 if ($visible == '0') {
2181 // Remember the current visible state so we can toggle this back.
2182 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2183 } else {
2184 // Get the previous saved visible states.
2185 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2186 }
2187 }
48e535bc 2188 return set_field("course_modules", "visible", $visible, "id", $id);
1acfbce5 2189}
2190
290130b3 2191/*
2192 * Delete a course module and any associated data at the course level (events)
264867fd 2193 * Until 1.5 this function simply marked a deleted flag ... now it
290130b3 2194 * deletes it completely.
2195 *
2196 */
48e535bc 2197function delete_course_module($id) {
f615fbab 2198 global $CFG;
2199 require_once($CFG->libdir.'/gradelib.php');
2200
290130b3 2201 if (!$cm = get_record('course_modules', 'id', $id)) {
2202 return true;
2203 }
dcd338ff 2204 $modulename = get_field('modules', 'name', 'id', $cm->module);
f615fbab 2205 //delete events from calendar
dcd338ff 2206 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2207 foreach($events as $event) {
0ea03696 2208 delete_event($event->id);
dcd338ff 2209 }
2210 }
f615fbab 2211 //delete grade items, outcome items and grades attached to modules
2212 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2213 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2214 foreach ($grade_items as $grade_item) {
2215 $grade_item->delete('moddelete');
2216 }
2217
2218 }
290130b3 2219 return delete_records('course_modules', 'id', $cm->id);
11b0c469 2220}
2221
2222function delete_mod_from_section($mod, $section) {
11b0c469 2223
e5dfd0f3 2224 if ($section = get_record("course_sections", "id", "$section") ) {
11b0c469 2225
e5dfd0f3 2226 $modarray = explode(",", $section->sequence);
11b0c469 2227
2228 if ($key = array_keys ($modarray, $mod)) {
2229 array_splice($modarray, $key[0], 1);
2230 $newsequence = implode(",", $modarray);
e5dfd0f3 2231 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
11b0c469 2232 } else {
2233 return false;
2234 }
89adb174 2235
11b0c469 2236 }
7977cffd 2237 return false;
11b0c469 2238}
2239
12905134 2240function move_section($course, $section, $move) {
2241/// Moves a whole course section up and down within the course
798b70a1 2242 global $USER;
12905134 2243
2244 if (!$move) {
2245 return true;
2246 }
2247
2248 $sectiondest = $section + $move;
2249
2250 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2251 return false;
2252 }
2253
2254 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2255 return false;
2256 }
2257
2258 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2259 return false;
2260 }
2261
56e34ee4 2262 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
12905134 2263 return false;
2264 }
56e34ee4 2265 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id)) {
12905134 2266 return false;
2267 }
798b70a1 2268 // if the focus is on the section that is being moved, then move the focus along
2269 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2270 course_set_display($course->id, $sectiondest);
2271 }
5390cbb7 2272
a987106d 2273 // Check for duplicates and fix order if needed.
5390cbb7 2274 // There is a very rare case that some sections in the same course have the same section id.
a987106d 2275 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2276 $n = 0;
2277 foreach ($sections as $section) {
2278 if ($section->section != $n) {
5390cbb7 2279 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2280 return false;
2281 }
5390cbb7 2282 }
a987106d 2283 $n++;
5390cbb7 2284 }
12905134 2285 return true;
2286}
2287
2288
7977cffd 2289function moveto_module($mod, $section, $beforemod=NULL) {
2290/// All parameters are objects
2291/// Move the module object $mod to the specified $section
2292/// If $beforemod exists then that is the module
2293/// before which $modid should be inserted
2294
2295/// Remove original module from original section
2296
2297 if (! delete_mod_from_section($mod->id, $mod->section)) {
2298 notify("Could not delete module from existing section");
2299 }
2300
2301/// Update module itself if necessary
2302
2303 if ($mod->section != $section->id) {
89adb174 2304 $mod->section = $section->id;
7977cffd 2305 if (!update_record("course_modules", $mod)) {
2306 return false;
2307 }
48e535bc 2308 // if moving to a hidden section then hide module
2309 if (!$section->visible) {
2310 set_coursemodule_visible($mod->id, 0);
2311 }
7977cffd 2312 }
2313
2314/// Add the module into the new section
2315
2316 $mod->course = $section->course;
2317 $mod->section = $section->section; // need relative reference
2318 $mod->coursemodule = $mod->id;
2319
2320 if (! add_mod_to_section($mod, $beforemod)) {
2321 return false;
2322 }
2323
2324 return true;
2325
2326}
2327
24e1eae4 2328function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
810393c8 2329 global $CFG, $USER;
94361e02 2330
3d575e6f 2331 static $str;
37a88449 2332 static $sesskey;
3d575e6f 2333
217a8ee9 2334 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2335 // no permission to edit
2336 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
e2cd3ed0 2337 return false;
217a8ee9 2338 }
2339
3d575e6f 2340 if (!isset($str)) {
90ebdf65 2341 $str->delete = get_string("delete");
2342 $str->move = get_string("move");
2343 $str->moveup = get_string("moveup");
2344 $str->movedown = get_string("movedown");
2345 $str->moveright = get_string("moveright");
2346 $str->moveleft = get_string("moveleft");
2347 $str->update = get_string("update");
2348 $str->duplicate = get_string("duplicate");
2349 $str->hide = get_string("hide");
2350 $str->show = get_string("show");
3d575e6f 2351 $str->clicktochange = get_string("clicktochange");
32d03b7b 2352 $str->forcedmode = get_string("forcedmode");
3d575e6f 2353 $str->groupsnone = get_string("groupsnone");
2354 $str->groupsseparate = get_string("groupsseparate");
2355 $str->groupsvisible = get_string("groupsvisible");
37a88449 2356 $sesskey = sesskey();
1acfbce5 2357 }
94361e02 2358
24e1eae4 2359 if ($section >= 0) {
75f087b6 2360 $section = '&amp;sr='.$section; // Section return
24e1eae4 2361 } else {
2362 $section = '';
2363 }
2364
94361e02 2365 if ($absolute) {
37a88449 2366 $path = $CFG->wwwroot.'/course';
dc0dc7d5 2367 } else {
37a88449 2368 $path = '.';
dc0dc7d5 2369 }
2370
217a8ee9 2371 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2372 if ($mod->visible) {
2373 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2374 '&amp;sesskey='.$sesskey.$section.'"><img'.
2375 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2376 ' alt="'.$str->hide.'" /></a>'."\n";
2377 } else {
2378 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2379 '&amp;sesskey='.$sesskey.$section.'"><img'.
2380 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2381 ' alt="'.$str->show.'" /></a>'."\n";
2382 }
7977cffd 2383 }
3d575e6f 2384 if ($mod->groupmode !== false) {
2385 if ($mod->groupmode == SEPARATEGROUPS) {
32d03b7b 2386 $grouptitle = $str->groupsseparate;
cddbd5d5 2387 $groupclass = 'editing_groupsseparate';
37a88449 2388 $groupimage = $CFG->pixpath.'/t/groups.gif';
2389 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
3d575e6f 2390 } else if ($mod->groupmode == VISIBLEGROUPS) {
32d03b7b 2391 $grouptitle = $str->groupsvisible;
cddbd5d5 2392 $groupclass = 'editing_groupsvisible';
37a88449 2393 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2394 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
32d03b7b 2395 } else {
2396 $grouptitle = $str->groupsnone;
90ebdf65 2397 $groupclass = 'editing_groupsnone';
37a88449 2398 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2399 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
32d03b7b 2400 }
2401 if ($mod->groupmodelink) {
90ebdf65 2402 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
0d905d9f 2403 '<img src="'.$groupimage.'" class="iconsmall" '.
2404 'alt="'.$grouptitle.'" /></a>';
3d575e6f 2405 } else {
37a88449 2406 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
0d905d9f 2407 ' src="'.$groupimage.'" class="iconsmall" '.
2408 'alt="'.$grouptitle.'" />';
3d575e6f 2409 }
2410 } else {
2411 $groupmode = "";
2412 }
e2cd3ed0 2413
217a8ee9 2414 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2415 if ($moveselect) {
2416 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2417 '&amp;sesskey='.$sesskey.$section.'"><img'.
2418 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2419 ' alt="'.$str->move.'" /></a>'."\n";
2420 } else {
2421 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2422 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2423 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2424 ' alt="'.$str->moveup.'" /></a>'."\n".
2425 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2426 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2427 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2428 ' alt="'.$str->movedown.'" /></a>'."\n";
2429 }
7b44777e 2430 } else {
2431 $move = '';
7977cffd 2432 }
2433
932be046 2434 $leftright = '';
217a8ee9 2435 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
932be046 2436
8047ab1d 2437 if (right_to_left()) { // Exchange arrows on RTL
932be046 2438 $rightarrow = 'left.gif';
2439 $leftarrow = 'right.gif';
2440 } else {
2441 $rightarrow = 'right.gif';
2442 $leftarrow = 'left.gif';
2443 }
2444
217a8ee9 2445 if ($indent > 0) {
2446 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2447 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2448 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
217a8ee9 2449 ' alt="'.$str->moveleft.'" /></a>'."\n";
2450 }
2451 if ($indent >= 0) {
2452 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2453 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
932be046 2454 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
217a8ee9 2455 ' alt="'.$str->moveright.'" /></a>'."\n";
2456 }
37a88449 2457 }
2458
90ebdf65 2459 return '<span class="commands">'."\n".$leftright.$move.
2460 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
37a88449 2461 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2462 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
90ebdf65 2463 ' alt="'.$str->update.'" /></a>'."\n".
2464 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
37a88449 2465 '&amp;sesskey='.$sesskey.$section.'"><img'.
0d905d9f 2466 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
90ebdf65 2467 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
90845098 2468}
2469
b61efafb 2470/**
264867fd 2471 * given a course object with shortname & fullname, this function will
b61efafb 2472 * truncate the the number of chars allowed and add ... if it was too long
2473 */
2474function course_format_name ($course,$max=100) {
264867fd 2475
6ba65fa0 2476 $str = $course->shortname.': '. $course->fullname;
b61efafb 2477 if (strlen($str) <= $max) {
2478 return $str;
2479 }
2480 else {
2481 return substr($str,0,$max-3).'...';
2482 }
2483}
2484
2485/**
2486 * This function will return true if the given course is a child course at all
2487 */
2488function course_in_meta ($course) {
5f37b628 2489 return record_exists("course_meta","child_course",$course->id);
b61efafb 2490}
2491
48e535bc 2492
2493/**
2494 * Print standard form elements on module setup forms in mod/.../mod.html
2495 */
263017bb 2496function print_standard_coursemodule_settings($form, $features=null) {
da2224f8 2497 if (! $course = get_record('course', 'id', $form->course)) {
2498 error("This course doesn't exist");
2499 }
2500 print_groupmode_setting($form, $course);
263017bb 2501 if (!empty($features->groupings)) {
2502 print_grouping_settings($form, $course);
2503 }
da2224f8 2504 print_visible_setting($form, $course);
48e535bc 2505}
2506
2507/**
2508 * Print groupmode form element on module setup forms in mod/.../mod.html
2509 */
5ebb746b 2510function print_groupmode_setting($form, $course=NULL) {
48e535bc 2511
5ebb746b 2512 if (empty($course)) {
2513 if (! $course = get_record('course', 'id', $form->course)) {
2514 error("This course doesn't exist");
2515 }
2516 }
48e535bc 2517 if ($form->coursemodule) {
2518 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2519 error("This course module doesn't exist");
2520 }
ffc536af 2521 $groupmode = groups_get_activity_groupmode($cm);
48e535bc 2522 } else {
2523 $cm = null;
ffc536af 2524 $groupmode = groups_get_course_groupmode($course);
48e535bc 2525 }
48e535bc 2526 if ($course->groupmode or (!$course->groupmodeforce)) {
2527 echo '<tr valign="top">';
2528 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
7bbe08a2 2529 echo '<td align="left">';
ffc536af 2530 $choices = array();
48e535bc 2531 $choices[NOGROUPS] = get_string('groupsnone');
2532 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2533 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2534 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2535 helpbutton('groupmode', get_string('groupmode'));
2536 echo '</td></tr>';
2537 }
2538}
2539
263017bb 2540/**
2541 * Print groupmode form element on module setup forms in mod/.../mod.html
2542 */
2543function print_grouping_settings($form, $course=NULL) {
2544
2545 if (empty($course)) {
2546 if (! $course = get_record('course', 'id', $form->course)) {
2547 error("This course doesn't exist");
2548 }
2549 }
2550 if ($form->coursemodule) {
2551 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2552 error("This course module doesn't exist");
2553 }
2554 } else {
2555 $cm = null;
2556 }
2557
2558 $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
2559 if (!empty($groupings)) {
2560 echo '<tr valign="top">';
2561 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2562 echo '<td align="left">';
2563
2564 $groupings;
2565 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
2566
2567 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2568 echo '</td></tr>';
2569
2570 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2571 echo '<tr valign="top">';
2572 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2573 echo '<td align="left">';
2574 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2575 echo '</td></tr>';
2576
2577 }
2578}
2579
48e535bc 2580/**
2581 * Print visibility setting form element on module setup forms in mod/.../mod.html
2582 */
5ebb746b 2583function print_visible_setting($form, $course=NULL) {
1ee55c41 2584 if (empty($course)) {
2585 if (! $course = get_record('course', 'id', $form->course)) {
2586 error("This course doesn't exist");
2587 }
2588 }
48e535bc 2589 if ($form->coursemodule) {
2590 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2591 } else {
2592 $visible = true;
2593 }
2594
2595 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2596 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2597 } else {
2598 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2599 }
2600 if ($hiddensection) {
2601 $visible = false;
2602 }
264867fd 2603
48e535bc 2604 echo '<tr valign="top">';
182311e4 2605 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
7bbe08a2 2606 echo '<td align="left">';
dd97c328 2607 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
48e535bc 2608 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2609 echo '</td></tr>';
264867fd 2610}
48e535bc 2611
0705ff84 2612function update_restricted_mods($course,$mods) {
2613 delete_records("course_allowed_modules","course",$course->id);
2614 if (empty($course->restrictmodules)) {
2615 return;
2616 }
2617 else {
2618 foreach ($mods as $mod) {
dd97c328 2619 if ($mod == 0) {
0705ff84 2620 continue; // this is the 'allow none' option
dd97c328 2621 }
2622 $am = new object();
0705ff84 2623 $am->course = $course->id;
2624 $am->module = $mod;
2625 insert_record("course_allowed_modules",$am);
2626 }
2627 }
2628}
2629
2630/**
2631 * This function will take an int (module id) or a string (module name)
2632 * and return true or false, whether it's allowed in the given course (object)
264867fd 2633 * $mod is not allowed to be an object, as the field for the module id is inconsistent
0705ff84 2634 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2635 */
2636
2637function course_allowed_module($course,$mod) {
2638 if (empty($course->restrictmodules)) {
2639 return true;
2640 }
264867fd 2641
51792df0 2642 // i am not sure this capability is correct
2643 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
0705ff84 2644 return true;
2645 }
2646 if (is_numeric($mod)) {
2647 $modid = $mod;
2648 } else if (is_string($mod)) {
cb77cf12 2649 if ($mod = get_field("modules","id","name",$mod))
0705ff84 2650 $modid = $mod;
2651 }
2652 if (empty($modid)) {
2653 return false;
2654 }
2655 return (record_exists("course_allowed_modules","course",$course->id,"module",$modid));
2656}
2657
861efb19 2658/***
2659 *** Efficiently moves many courses around while maintaining
2660 *** sortorder in order.
264867fd 2661 ***
861efb19 2662 *** $courseids is an array of course ids
2663 ***
2664 **/
2665
2666function move_courses ($courseids, $categoryid) {
2667
2668 global $CFG;
2669
2670 if (!empty($courseids)) {
264867fd 2671
2672 $courseids = array_reverse($courseids);
861efb19 2673
2674 foreach ($courseids as $courseid) {
264867fd 2675
861efb19 2676 if (! $course = get_record("course", "id", $courseid)) {
2677 notify("Error finding course $courseid");
2678 } else {
2679 // figure out a sortorder that we can use in the destination category
2680 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2681 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2682 if ($sortorder === false) {
2683 // the category is empty
2684 // rather than let the db default to 0
264867fd 2685 // set it to > 100 and avoid extra work in fix_coursesortorder()
861efb19 2686 $sortorder = 200;
2687 } else if ($sortorder < 10) {
2688 fix_course_sortorder($categoryid);
2689 }
2690
2691 $course->category = $categoryid;
2692 $course->sortorder = $sortorder;
2693 $course->fullname = addslashes($course->fullname);
2694 $course->shortname = addslashes($course->shortname);
2695 $course->summary = addslashes($course->summary);
2696 $course->password = addslashes($course->password);
2697 $course->teacher = addslashes($course->teacher);
2698 $course->teachers = addslashes($course->teachers);
2699 $course->student = addslashes($course->student);
2700 $course->students = addslashes($course->students);
264867fd 2701
861efb19 2702 if (!update_record('course', $course)) {
2703 notify("An error occurred - course not moved!");
2704 }
19f601d1 2705
2706 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2707 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2708 context_moved($context, $newparent);
861efb19 2709 }
2710 }
2711 fix_course_sortorder();
264867fd 2712 }
861efb19 2713 return true;
2714}
2715
19f601d1 2716/***
2717 *** Efficiently moves a category - NOTE that this can have
2718 *** a huge impact access-control-wise...
2719 ***
2720 ***
2721 **/
2722function move_category ($category, $newparentcat) {
2723
2724 global $CFG;
2725
1f41940f 2726 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2727
2728 if (empty($newparentcat->id)) {
2729 if (!set_field('course_categories', 'parent', 0, 'id', $category->id)) {
2730 return false;
2731 }
2732 $newparent = get_context_instance(CONTEXT_SYSTEM);
2733 } else {
2734 if (!set_field('course_categories', 'parent', $newparentcat->id, 'id', $category->id)) {
2735 return false;
2736 }
2737 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
19f601d1 2738 }
2739
19f601d1 2740 context_moved($context, $newparent);
2741
2742 // The most effective thing would be to find the common parent,
2743 // until then, do it sitewide...
2744 fix_course_sortorder();
2745
2746
2747 return true;
2748}
2749
ae628043 2750/**
2751 * @param string $format Course format ID e.g. 'weeks'
2752 * @return Name that the course format prefers for sections
2753 */
2754function get_section_name($format) {
2755 $sectionname = get_string("name$format","format_$format");
2756 if($sectionname == "[[name$format]]") {
2757 $sectionname = get_string("name$format");
2758 }
a044c05d 2759 return $sectionname;
ae628043 2760}
2761
2585a68d 2762/**
2763 * Can the current user delete this course?
2764 * @param int $courseid
2765 * @return boolean
2766 *
2767 * Exception here to fix MDL-7796.
2768 *
2769 * FIXME
2770 * Course creators who can manage activities in the course
2771 * shoule be allowed to delete the course. We do it this
2772 * way because we need a quick fix to bring the functionality
2773 * in line with what we had pre-roles. We can't give the
2774 * default course creator role moodle/course:delete at
2775 * CONTEXT_SYSTEM level because this will allow them to
2776 * delete any course in the site. So we hard code this here
2777 * for now.
2778 *
2779 * @author vyshane AT gmail.com
2780 */
2781function can_delete_course($courseid) {
2782
2783 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2784
2785 return ( has_capability('moodle/course:delete', $context)
2786 || (has_capability('moodle/legacy:coursecreator', $context)
2787 && has_capability('moodle/course:manageactivities', $context)) );
2788}
2789
2790
bfefa87e 2791/*
2792 * Create a course and either return a $course object or false
2793 *
2794 * @param object $data - all the data needed for an entry in the 'course' table
2795 */
2796function create_course($data) {
2797 global $CFG, $USER;
2798
2799 // preprocess allowed mods
2800 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2801 unset($data->allowedmods);
2802 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2803 if ($CFG->restrictmodulesfor == 'all') {
2804 $data->restrictmodules = 1;
2805 } else {
2806 $data->restrictmodules = 0;
2807 }
2808 }
2585a68d 2809
bfefa87e 2810 $data->timecreated = time();
2811
2812 // place at beginning of category
2813 fix_course_sortorder();
2814 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2815 if (empty($data->sortorder)) {
2816 $data->sortorder = 100;
2817 }
2818
2819 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2820
2821 $course = get_record('course', 'id', $newcourseid);
2822
2823 // Setup the blocks
2824 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2825 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2826
2827 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2828 update_restricted_mods($course, $allowedmods);
2829 }
2830
2831 $section = new object();
2832 $section->course = $course->id; // Create a default section.
2833 $section->section = 0;
2834 $section->id = insert_record('course_sections', $section);
2835
2836 fix_course_sortorder();
2837
2838 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2839
2840 return $course;
2841 }
2842
2843 return false; // error
2844}
2845
2846
2847/*
2848 * Update a course and return true or false
2849 *
2850 * @param object $data - all the data needed for an entry in the 'course' table
2851 */
2852function update_course($data) {
2853 global $USER, $CFG;
2854
2855 // preprocess allowed mods
2856 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
2857 unset($data->allowedmods);
2858 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2859 unset($data->restrictmodules);
2860 }
2861
a372aab5 2862 $movecat = false;
bfefa87e 2863 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
2864 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
2865 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
2866 // can not move to new category, keep the old one
2867 unset($data->category);
a372aab5 2868 } elseif ($oldcourse->category != $data->category) {
2869 $movecat = true;
bfefa87e 2870 }
2871
2872 // Update with the new data
2873 if (update_record('course', $data)) {
2874
2875 $course = get_record('course', 'id', $data->id);
2876
0be70104 2877 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
bfefa87e 2878
2879 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
2880 update_restricted_mods($course, $allowedmods);
2881 }
2882
a372aab5 2883 if ($movecat) {
2884 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2885 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2886 context_moved($context, $newparent);
2887 }
2888
bfefa87e 2889 fix_course_sortorder();
2890
2891 // Test for and remove blocks which aren't appropriate anymore
2892 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
2893 blocks_remove_inappropriate($page);
2894
2895 // put custom role names into db
2896 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2897
2898 foreach ($data as $dname => $dvalue) {
2899
2900 // is this the right param?
2901 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
2902
2903 if (!strstr($dname, 'role_')) {
2904 continue;
2905 }
2906
2907 $dt = explode('_', $dname);
2908 $roleid = $dt[1];
2909 // make up our mind whether we want to delete, update or insert
2910
2911 if (empty($dvalue)) {
2912
2913 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
2914
2915 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
2916
2917 $t->text = $dvalue;
2918 update_record('role_names', $t);
2919
2920 } else {
2921
2922 $t->contextid = $context->id;
2923 $t->roleid = $roleid;
2924 $t->text = $dvalue;
2925 insert_record('role_names', $t);
2926 }
2927
2928 }
2929
2930 return true;
2931
2932 }
2933
2934 return false;
2935}
2585a68d 2936
7f9c4fb9 2937?>