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