2 // Library of useful functions
5 define('COURSE_MAX_LOG_DISPLAY', 150); // days
6 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
7 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
8 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
9 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
10 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
11 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
12 define('FRONTPAGENEWS', '0');
13 define('FRONTPAGECOURSELIST', '1');
14 define('FRONTPAGECATEGORYNAMES', '2');
15 define('FRONTPAGETOPICONLY', '3');
16 define('FRONTPAGECATEGORYCOMBO', '4');
17 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
18 define('EXCELROWS', 65535);
19 define('FIRSTUSEDEXCELROW', 3);
21 define('MOD_CLASS_ACTIVITY', 0);
22 define('MOD_CLASS_RESOURCE', 1);
25 function make_log_url($module, $url) {
34 return "/course/$url";
38 return "/$module/$url";
48 return "/message/$url";
51 return "/mod/$module/$url";
57 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
58 $modname="", $modid=0, $modaction="", $groupid=0) {
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.
65 /// Setup for group handling.
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?
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);
76 /// If this course doesn't have groups, no groupid can be specified.
77 //else if (!$course->groupmode) {
91 {$CFG->prefix}mnet_log l
99 $where .= "l.hostid = '$hostid'";
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'";
107 $where .= " AND\n l.module = '$modname'";
110 if ('site_errors' === $modid) {
111 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
113 //TODO: This assumes that modids are the same across sites... probably
115 $where .= " AND\n l.cmid = '$modid'";
119 $firstletter = substr($modaction, 0, 1);
120 if (preg_match('/[[: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)) . "%'";
128 $where .= " AND\n l.userid = '$user'";
132 $enddate = $date +
86400;
133 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
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);
142 $result['logs'] = array();
147 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
148 $modname="", $modid=0, $modaction="", $groupid=0) {
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.
153 /// Setup for group handling.
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.
157 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
158 $groupid = get_current_group($course->id
);
160 /// If this course doesn't have groups, no groupid can be specified.
161 else if (!$course->groupmode
) {
167 if ($course->id
!= SITEID ||
$modid != 0) {
168 $joins[] = "l.course='$course->id'";
172 $joins[] = "l.module = '$modname'";
175 if ('site_errors' === $modid) {
176 $joins[] = "( l.action='error' OR l.action='infected' )";
178 $joins[] = "l.cmid = '$modid'";
182 $firstletter = substr($modaction, 0, 1);
183 if (preg_match('/[[: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)) . "%'";
191 /// Getting all members of a group.
192 if ($groupid and !$user) {
193 if ($gusers = groups_get_members($groupid)) {
194 $gusers = array_keys($gusers);
195 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
197 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
201 $joins[] = "l.userid = '$user'";
205 $enddate = $date +
86400;
206 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
209 $selector = implode(' AND ', $joins);
211 $totalcount = 0; // Initialise
213 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
214 $result['totalcount'] = $totalcount;
219 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
220 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
224 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
225 $modname, $modid, $modaction, $groupid)) {
226 notify("No logs found!");
227 print_footer($course);
233 if ($course->id
== SITEID
) {
235 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
236 foreach ($ccc as $cc) {
237 $courses[$cc->id
] = $cc->shortname
;
241 $courses[$course->id
] = $course->shortname
;
244 $totalcount = $logs['totalcount'];
247 $tt = getdate(time());
248 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
250 $strftimedatetime = get_string("strftimedatetime");
252 echo "<div class=\"info\">\n";
253 print_string("displayingrecords", "", $totalcount);
256 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
258 echo '<table class="logtable generalbox boxaligncenter" summary="">'."\n";
259 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
261 if ($course->id
== SITEID
) {
262 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
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";
271 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
272 if (empty($logs['logs'])) {
273 $logs['logs'] = array();
277 foreach ($logs['logs'] as $log) {
279 $row = ($row +
1) %
2;
281 if (isset($ldcache[$log->module
][$log->action
])) {
282 $ld = $ldcache[$log->module
][$log->action
];
284 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
285 $ldcache[$log->module
][$log->action
] = $ld;
287 if ($ld && is_numeric($log->info
)) {
288 // ugly hack to make sure fullname is shown correctly
289 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
290 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
292 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
297 $log->info
= format_string($log->info
);
299 // If $log->url has been trimmed short by the db size restriction
300 // code in add_to_log, keep a note so we don't add a link to a broken url
301 $tl=textlib_get_instance();
302 $brokenurl=($tl->strlen($log->url
)==100 && $tl->substr($log->url
,97)=='...');
304 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
305 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
306 $log->url
= s($log->url
); /// XSS protection and XHTML compatibility - should be in link_to_popup_window() instead!!
308 echo '<tr class="r'.$row.'">';
309 if ($course->id
== SITEID
) {
310 echo "<td class=\"cell c0\">\n";
311 if (empty($log->course
)) {
312 echo get_string('site') . "\n";
314 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>\n";
318 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time
, '%a').
319 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
320 echo "<td class=\"cell c2\">\n";
321 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 440, 700);
323 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
324 echo "<td class=\"cell c3\">\n";
325 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&course={$log->course}\">$fullname</a>\n";
327 echo "<td class=\"cell c4\">\n";
328 $displayaction="$log->module $log->action";
332 link_to_popup_window( make_log_url($log->module
,$log->url
), 'fromloglive',$displayaction, 440, 700);
335 echo "<td class=\"cell c5\">{$log->info}</td>\n";
340 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
344 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
345 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
349 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
350 $modname, $modid, $modaction, $groupid)) {
351 notify("No logs found!");
352 print_footer($course);
356 if ($course->id
== SITEID
) {
358 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
359 foreach ($ccc as $cc) {
360 $courses[$cc->id
] = $cc->shortname
;
365 $totalcount = $logs['totalcount'];
368 $tt = getdate(time());
369 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
371 $strftimedatetime = get_string("strftimedatetime");
373 echo "<div class=\"info\">\n";
374 print_string("displayingrecords", "", $totalcount);
377 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
379 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
381 if ($course->id
== SITEID
) {
382 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
384 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
385 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
386 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
387 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
388 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
391 if (empty($logs['logs'])) {
397 foreach ($logs['logs'] as $log) {
399 $log->info
= $log->coursename
;
400 $row = ($row +
1) %
2;
402 if (isset($ldcache[$log->module
][$log->action
])) {
403 $ld = $ldcache[$log->module
][$log->action
];
405 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
406 $ldcache[$log->module
][$log->action
] = $ld;
408 if (0 && $ld && !empty($log->info
)) {
409 // ugly hack to make sure fullname is shown correctly
410 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
411 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
413 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
418 $log->info
= format_string($log->info
);
420 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
421 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
422 $log->url
= str_replace('&', '&', $log->url
); /// XHTML compatibility
424 echo '<tr class="r'.$row.'">';
425 if ($course->id
== SITEID
) {
426 echo "<td class=\"r$row c0\" >\n";
427 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course
]."</a>\n";
430 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
431 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
432 echo "<td class=\"r$row c2\" >\n";
433 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
435 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
436 echo "<td class=\"r$row c3\" >\n";
437 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
439 echo "<td class=\"r$row c4\">\n";
440 echo $log->action
.': '.$log->module
;
442 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
447 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
451 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
452 $modid, $modaction, $groupid) {
454 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
455 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
457 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
458 $modname, $modid, $modaction, $groupid)) {
464 if ($course->id
== SITEID
) {
466 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
467 foreach ($ccc as $cc) {
468 $courses[$cc->id
] = $cc->shortname
;
472 $courses[$course->id
] = $course->shortname
;
477 $tt = getdate(time());
478 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
480 $strftimedatetime = get_string("strftimedatetime");
482 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
484 header("Content-Type: application/download\n");
485 header("Content-Disposition: attachment; filename=$filename");
486 header("Expires: 0");
487 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
488 header("Pragma: public");
490 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
493 if (empty($logs['logs'])) {
497 foreach ($logs['logs'] as $log) {
498 if (isset($ldcache[$log->module
][$log->action
])) {
499 $ld = $ldcache[$log->module
][$log->action
];
501 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
502 $ldcache[$log->module
][$log->action
] = $ld;
504 if ($ld && !empty($log->info
)) {
505 // ugly hack to make sure fullname is shown correctly
506 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
507 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
509 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
514 $log->info
= format_string($log->info
);
516 $log->url
= strip_tags(urldecode($log->url
)); // Some XSS protection
517 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
518 $log->url
= str_replace('&', '&', $log->url
); // XHTML compatibility
520 $firstField = $courses[$log->course
];
521 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
522 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
523 $text = implode("\t", $row);
530 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
531 $modid, $modaction, $groupid) {
535 require_once("$CFG->libdir/excellib.class.php");
537 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
538 $modname, $modid, $modaction, $groupid)) {
544 if ($course->id
== SITEID
) {
546 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
547 foreach ($ccc as $cc) {
548 $courses[$cc->id
] = $cc->shortname
;
552 $courses[$course->id
] = $course->shortname
;
557 $tt = getdate(time());
558 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
560 $strftimedatetime = get_string("strftimedatetime");
562 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
563 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
566 $workbook = new MoodleExcelWorkbook('-');
567 $workbook->send($filename);
569 $worksheet = array();
570 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
571 get_string('fullname'), get_string('action'), get_string('info'));
573 // Creating worksheets
574 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
575 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
576 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
577 $worksheet[$wsnumber]->set_column(1, 1, 30);
578 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
579 userdate(time(), $strftimedatetime));
581 foreach ($headers as $item) {
582 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
587 if (empty($logs['logs'])) {
592 $formatDate =& $workbook->add_format();
593 $formatDate->set_num_format(get_string('log_excel_date_format'));
595 $row = FIRSTUSEDEXCELROW
;
597 $myxls =& $worksheet[$wsnumber];
598 foreach ($logs['logs'] as $log) {
599 if (isset($ldcache[$log->module
][$log->action
])) {
600 $ld = $ldcache[$log->module
][$log->action
];
602 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
603 $ldcache[$log->module
][$log->action
] = $ld;
605 if ($ld && !empty($log->info
)) {
606 // ugly hack to make sure fullname is shown correctly
607 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
608 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
610 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
615 $log->info
= format_string($log->info
);
616 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
619 if ($row > EXCELROWS
) {
621 $myxls =& $worksheet[$wsnumber];
622 $row = FIRSTUSEDEXCELROW
;
626 $myxls->write($row, 0, $courses[$log->course
], '');
627 // Excel counts from 1/1/1900
628 $excelTime=25569+
$log->time
/(3600*24);
629 $myxls->write($row, 1, $excelTime, $formatDate);
630 $myxls->write($row, 2, $log->ip
, '');
631 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
632 $myxls->write($row, 3, $fullname, '');
633 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
634 $myxls->write($row, 5, $log->info
, '');
643 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
644 $modid, $modaction, $groupid) {
648 require_once("$CFG->libdir/odslib.class.php");
650 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
651 $modname, $modid, $modaction, $groupid)) {
657 if ($course->id
== SITEID
) {
659 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
660 foreach ($ccc as $cc) {
661 $courses[$cc->id
] = $cc->shortname
;
665 $courses[$course->id
] = $course->shortname
;
670 $tt = getdate(time());
671 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
673 $strftimedatetime = get_string("strftimedatetime");
675 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
676 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
679 $workbook = new MoodleODSWorkbook('-');
680 $workbook->send($filename);
682 $worksheet = array();
683 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
684 get_string('fullname'), get_string('action'), get_string('info'));
686 // Creating worksheets
687 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
688 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
689 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
690 $worksheet[$wsnumber]->set_column(1, 1, 30);
691 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
692 userdate(time(), $strftimedatetime));
694 foreach ($headers as $item) {
695 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
700 if (empty($logs['logs'])) {
705 $formatDate =& $workbook->add_format();
706 $formatDate->set_num_format(get_string('log_excel_date_format'));
708 $row = FIRSTUSEDEXCELROW
;
710 $myxls =& $worksheet[$wsnumber];
711 foreach ($logs['logs'] as $log) {
712 if (isset($ldcache[$log->module
][$log->action
])) {
713 $ld = $ldcache[$log->module
][$log->action
];
715 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
716 $ldcache[$log->module
][$log->action
] = $ld;
718 if ($ld && !empty($log->info
)) {
719 // ugly hack to make sure fullname is shown correctly
720 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
721 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
723 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
728 $log->info
= format_string($log->info
);
729 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
732 if ($row > EXCELROWS
) {
734 $myxls =& $worksheet[$wsnumber];
735 $row = FIRSTUSEDEXCELROW
;
739 $myxls->write_string($row, 0, $courses[$log->course
]);
740 $myxls->write_date($row, 1, $log->time
);
741 $myxls->write_string($row, 2, $log->ip
);
742 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
743 $myxls->write_string($row, 3, $fullname);
744 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
745 $myxls->write_string($row, 5, $log->info
);
755 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
757 if (empty($CFG->gdversion
)) {
758 echo "(".get_string("gdneed").")";
760 // MDL-10818, do not display broken graph when user has no permission to view graph
761 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE
, $course->id
)) ||
762 ($course->showreports
and $USER->id
== $userid)) {
763 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
764 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
770 function print_overview($courses) {
774 $htmlarray = array();
775 if ($modules = get_records('modules')) {
776 foreach ($modules as $mod) {
777 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
778 include_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
779 $fname = $mod->name
.'_print_overview';
780 if (function_exists($fname)) {
781 $fname($courses,$htmlarray);
786 foreach ($courses as $course) {
787 print_simple_box_start('center', '100%', '', 5, "coursebox");
789 if (empty($course->visible
)) {
790 $linkcss = 'class="dimmed"';
792 print_heading('<a title="'. format_string($course->fullname
).'" '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>');
793 if (array_key_exists($course->id
,$htmlarray)) {
794 foreach ($htmlarray[$course->id
] as $modname => $html) {
798 print_simple_box_end();
803 function print_recent_activity($course) {
804 // $course is an object
805 // This function trawls through the logs looking for
806 // anything new since the user's last login
808 global $CFG, $USER, $SESSION;
810 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
812 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
814 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD
, -2); // better db caching for guests - 100 seconds
816 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
817 if (!empty($USER->lastcourseaccess
[$course->id
])) {
818 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
819 $timestart = $USER->lastcourseaccess
[$course->id
];
824 echo '<div class="activitydate">';
825 echo get_string('activitysince', '', userdate($timestart));
827 echo '<div class="activityhead">';
829 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
835 /// Firstly, have there been any new enrolments?
837 $users = get_recent_enrolments($course->id
, $timestart);
839 //Accessibility: new users now appear in an <OL> list.
841 echo '<div class="newusers">';
842 print_headline(get_string("newusers").':', 3);
844 echo "<ol class=\"list\">\n";
845 foreach ($users as $user) {
846 $fullname = fullname($user, $viewfullnames);
847 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
849 echo "</ol>\n</div>\n";
852 /// Next, have there been any modifications to the course structure?
854 $modinfo =& get_fast_modinfo($course);
856 $changelist = array();
858 $logs = get_records_select('log', "time > $timestart AND course = $course->id AND
859 module = 'course' AND
860 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
864 $actions = array('add mod', 'update mod', 'delete mod');
865 $newgones = array(); // added and later deleted items
866 foreach ($logs as $key => $log) {
867 if (!in_array($log->action
, $actions)) {
870 $info = split(' ', $log->info
);
872 if ($info[0] == 'label') { // Labels are ignored in recent activity
876 if (count($info) != 2) {
877 debugging("Incorrect log entry info: id = ".$log->id
, DEBUG_DEVELOPER
);
882 $instanceid = $info[1];
884 if ($log->action
== 'delete mod') {
885 // unfortunately we do not know if the mod was visible
886 if (!array_key_exists($log->info
, $newgones)) {
887 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
888 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
891 if (!isset($modinfo->instances
[$modname][$instanceid])) {
892 if ($log->action
== 'add mod') {
893 // do not display added and later deleted activities
894 $newgones[$log->info
] = true;
898 $cm = $modinfo->instances
[$modname][$instanceid];
899 if (!$cm->uservisible
) {
903 if ($log->action
== 'add mod') {
904 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
905 $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>");
907 } else if ($log->action
== 'update mod' and empty($changelist[$log->info
])) {
908 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
909 $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>");
915 if (!empty($changelist)) {
916 print_headline(get_string('courseupdates').':', 3);
918 foreach ($changelist as $changeinfo => $change) {
919 echo '<p class="activity">'.$change['text'].'</p>';
923 /// Now display new things from each module
925 $usedmodules = array();
926 foreach($modinfo->cms
as $cm) {
927 if (isset($usedmodules[$cm->modname
])) {
930 if (!$cm->uservisible
) {
933 $usedmodules[$cm->modname
] = $cm->modname
;
936 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
937 if (file_exists($CFG->dirroot
.'/mod/'.$modname.'/lib.php')) {
938 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
939 $print_recent_activity = $modname.'_print_recent_activity';
940 if (function_exists($print_recent_activity)) {
941 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
942 $content = $print_recent_activity($course, $viewfullnames, $timestart) ||
$content;
945 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
950 echo '<p class="message">'.get_string('nothingnew').'</p>';
955 function get_array_of_activities($courseid) {
956 // For a given course, returns an array of course activity objects
957 // Each item in the array contains he following properties:
958 // cm - course module id
959 // mod - name of the module (eg forum)
960 // section - the number of the section (eg week or topic)
961 // name - the name of the instance
962 // visible - is the instance visible or not
963 // groupingid - grouping id
964 // groupmembersonly - is this instance visible to group members only
965 // extra - contains extra string to include in any link
971 if (!$rawmods = get_course_mods($courseid)) {
972 return $mod; // always return array
975 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
976 foreach ($sections as $section) {
977 if (!empty($section->sequence
)) {
978 $sequence = explode(",", $section->sequence
);
979 foreach ($sequence as $seq) {
980 if (empty($rawmods[$seq])) {
983 $mod[$seq]->id
= $rawmods[$seq]->instance
;
984 $mod[$seq]->cm
= $rawmods[$seq]->id
;
985 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
986 $mod[$seq]->section
= $section->section
;
987 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
988 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
989 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
990 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
991 $mod[$seq]->extra
= "";
993 $modname = $mod[$seq]->mod
;
994 $functionname = $modname."_get_coursemodule_info";
996 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1000 include_once("$CFG->dirroot/mod/$modname/lib.php");
1002 if (function_exists($functionname)) {
1003 if ($info = $functionname($rawmods[$seq])) {
1004 if (!empty($info->extra
)) {
1005 $mod[$seq]->extra
= $info->extra
;
1007 if (!empty($info->icon
)) {
1008 $mod[$seq]->icon
= $info->icon
;
1010 if (!empty($info->name
)) {
1011 $mod[$seq]->name
= urlencode($info->name
);
1015 if (!isset($mod[$seq]->name
)) {
1016 $mod[$seq]->name
= urlencode(get_field($rawmods[$seq]->modname
, "name", "id", $rawmods[$seq]->instance
));
1027 * Returns reference to full info about modules in course (including visibility).
1028 * Cached and as fast as possible (0 or 1 db query).
1029 * @param $course object or 'reset' string to reset caches, modinfo may be updated in db
1030 * @return mixed courseinfo object or nothing if resetting
1032 function &get_fast_modinfo(&$course, $userid=0) {
1035 static $cache = array();
1037 if ($course === 'reset') {
1040 return $nothing; // we must return some reference
1043 if (empty($userid)) {
1044 $userid = $USER->id
;
1047 if (array_key_exists($course->id
, $cache) and $cache[$course->id
]->userid
== $userid) {
1048 return $cache[$course->id
];
1051 if (empty($course->modinfo
)) {
1052 // no modinfo yet - load it
1053 rebuild_course_cache($course->id
);
1054 $course->modinfo
= get_field('course', 'modinfo', 'id', $course->id
);
1057 $modinfo = new object();
1058 $modinfo->courseid
= $course->id
;
1059 $modinfo->userid
= $userid;
1060 $modinfo->sections
= array();
1061 $modinfo->cms
= array();
1062 $modinfo->instances
= array();
1063 $modinfo->groups
= null; // loaded only when really needed - the only one db query
1065 $info = unserialize($course->modinfo
);
1066 if (!is_array($info)) {
1067 // hmm, something is wrong - lets try to fix it
1068 rebuild_course_cache($course->id
);
1069 $course->modinfo
= get_field('course', 'modinfo', 'id', $course->id
);
1070 $info = unserialize($course->modinfo
);
1071 if (!is_array($info)) {
1077 // detect if upgrade required
1078 $first = reset($info);
1079 if (!isset($first->id
)) {
1080 rebuild_course_cache($course->id
);
1081 $course->modinfo
= get_field('course', 'modinfo', 'id', $course->id
);
1082 $info = unserialize($course->modinfo
);
1083 if (!is_array($info)) {
1089 $modlurals = array();
1093 foreach ($info as $mod) {
1094 $cmids[$mod->cm
] = $mod->cm
;
1097 // preload all module contexts with one query
1098 $contexts = get_context_instance(CONTEXT_MODULE
, $cmids);
1101 foreach ($info as $mod) {
1102 if (empty($mod->name
)) {
1103 // something is wrong here
1106 // reconstruct minimalistic $cm
1109 $cm->instance
= $mod->id
;
1110 $cm->course
= $course->id
;
1111 $cm->modname
= $mod->mod
;
1112 $cm->name
= urldecode($mod->name
);
1113 $cm->visible
= $mod->visible
;
1114 $cm->sectionnum
= $mod->section
;
1115 $cm->groupmode
= $mod->groupmode
;
1116 $cm->groupingid
= $mod->groupingid
;
1117 $cm->groupmembersonly
= $mod->groupmembersonly
;
1118 $cm->extra
= isset($mod->extra
) ?
urldecode($mod->extra
) : '';
1119 $cm->icon
= isset($mod->icon
) ?
$mod->icon
: '';
1120 $cm->uservisible
= true;
1122 // preload long names plurals and also check module is installed properly
1123 if (!isset($modlurals[$cm->modname
])) {
1124 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
1127 $modlurals[$cm->modname
] = get_string('modulenameplural', $cm->modname
);
1129 $cm->modplural
= $modlurals[$cm->modname
];
1131 if (!$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', $contexts[$cm->id
], $userid)) {
1132 $cm->uservisible
= false;
1134 } else if (!empty($CFG->enablegroupings
) and !empty($cm->groupmembersonly
)
1135 and !has_capability('moodle/site:accessallgroups', $contexts[$cm->id
], $userid)) {
1136 if (is_null($modinfo->groups
)) {
1137 $modinfo->groups
= groups_get_user_groups($course->id
, $userid);
1139 if (empty($modinfo->groups
[$cm->groupingid
])) {
1140 $cm->uservisible
= false;
1144 if (!isset($modinfo->instances
[$cm->modname
])) {
1145 $modinfo->instances
[$cm->modname
] = array();
1147 $modinfo->instances
[$cm->modname
][$cm->instance
] =& $cm;
1148 $modinfo->cms
[$cm->id
] =& $cm;
1150 // reconstruct sections
1151 if (!isset($modinfo->sections
[$cm->sectionnum
])) {
1152 $modinfo->sections
[$cm->sectionnum
] = array();
1154 $modinfo->sections
[$cm->sectionnum
][] = $cm->id
;
1159 unset($cache[$course->id
]); // prevent potential reference problems when switching users
1160 $cache[$course->id
] = $modinfo;
1162 return $cache[$course->id
];
1166 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1167 // Returns a number of useful structures for course displays
1169 $mods = array(); // course modules indexed by id
1170 $modnames = array(); // all course module names (except resource!)
1171 $modnamesplural= array(); // all course module names (plural form)
1172 $modnamesused = array(); // course module names used
1174 if ($allmods = get_records("modules")) {
1175 foreach ($allmods as $mod) {
1176 if ($mod->visible
) {
1177 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1178 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1181 asort($modnames, SORT_LOCALE_STRING
);
1183 error("No modules are installed!");
1186 if ($rawmods = get_course_mods($courseid)) {
1187 foreach($rawmods as $mod) { // Index the mods
1188 if (empty($modnames[$mod->modname
])) {
1191 $mods[$mod->id
] = $mod;
1192 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1193 if (!$mod->visible
and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1197 if (!groups_course_module_visible($mod)) {
1200 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1202 if ($modnamesused) {
1203 asort($modnamesused, SORT_LOCALE_STRING
);
1209 function get_all_sections($courseid) {
1211 return get_records("course_sections", "course", "$courseid", "section",
1212 "section, id, course, summary, sequence, visible");
1215 function course_set_display($courseid, $display=0) {
1218 if ($display == "all" or empty($display)) {
1222 if (empty($USER->id
) or $USER->username
== 'guest') {
1223 //do not store settings in db for guests
1224 } else if (record_exists("course_display", "userid", $USER->id
, "course", $courseid)) {
1225 set_field("course_display", "display", $display, "userid", $USER->id
, "course", $courseid);
1227 $record = new object();
1228 $record->userid
= $USER->id
;
1229 $record->course
= $courseid;
1230 $record->display
= $display;
1231 if (!insert_record("course_display", $record)) {
1232 notify("Could not save your course display!");
1236 return $USER->display
[$courseid] = $display; // Note: = not ==
1239 function set_section_visible($courseid, $sectionnumber, $visibility) {
1240 /// For a given course section, markes it visible or hidden,
1241 /// and does the same for every activity in that section
1243 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1244 set_field("course_sections", "visible", "$visibility", "id", $section->id
);
1245 if (!empty($section->sequence
)) {
1246 $modules = explode(",", $section->sequence
);
1247 foreach ($modules as $moduleid) {
1248 set_coursemodule_visible($moduleid, $visibility, true);
1251 rebuild_course_cache($courseid);
1256 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1257 /// Prints a section full of activity modules
1260 static $initialised;
1262 static $groupbuttons;
1263 static $groupbuttonslink;
1266 static $strmovehere;
1267 static $strmovefull;
1268 static $strunreadpostsone;
1269 static $usetracking;
1273 if (!isset($initialised)) {
1274 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1275 $groupbuttonslink = (!$course->groupmodeforce
);
1276 $isediting = isediting($course->id
);
1277 $ismoving = $isediting && ismoving($course->id
);
1279 $strmovehere = get_string("movehere");
1280 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1282 include_once($CFG->dirroot
.'/mod/forum/lib.php');
1283 if ($usetracking = forum_tp_can_track_forums()) {
1284 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1286 $initialised = true;
1289 $labelformatoptions = new object();
1290 $labelformatoptions->noclean
= true;
1292 /// Casting $course->modinfo to string prevents one notice when the field is null
1293 $modinfo = get_fast_modinfo($course);
1296 //Acccessibility: replace table with list <ul>, but don't output empty list.
1297 if (!empty($section->sequence
)) {
1299 // Fix bug #5027, don't want style=\"width:$width\".
1300 echo "<ul class=\"section img-text\">\n";
1301 $sectionmods = explode(",", $section->sequence
);
1303 foreach ($sectionmods as $modnumber) {
1304 if (empty($mods[$modnumber])) {
1308 $mod = $mods[$modnumber];
1310 if ($ismoving and $mod->id
== $USER->activitycopy
) {
1311 // do not display moving mod
1315 if (isset($modinfo->cms
[$modnumber])) {
1316 if (!$modinfo->cms
[$modnumber]->uservisible
) {
1317 // visibility shortcut
1321 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1322 // module not installed
1325 if (!coursemodule_visible_for_user($mod)) {
1326 // full visibility check
1331 echo '<li class="activity '.$mod->modname
.'" id="module-'.$modnumber.'">'; // Unique ID
1333 echo '<a title="'.$strmovefull.'"'.
1334 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.$USER->sesskey
.'">'.
1335 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1336 ' alt="'.$strmovehere.'" /></a><br />
1341 print_spacer(12, 20 * $mod->indent
, false);
1345 if (!empty($modinfo->cms
[$modnumber]->extra
)) {
1346 $extra = $modinfo->cms
[$modnumber]->extra
;
1349 if ($mod->modname
== "label") {
1350 if (!$mod->visible
) {
1351 echo "<div class=\"dimmed_text\">";
1353 echo format_text($extra, FORMAT_HTML
, $labelformatoptions);
1354 if (!$mod->visible
) {
1357 if (!empty($CFG->enablegroupings
) && !empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1358 if (!isset($groupings)) {
1359 $groupings = groups_get_all_groupings($course->id
);
1361 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1364 } else { // Normal activity
1365 $instancename = format_string($modinfo->cms
[$modnumber]->name
, true, $course->id
);
1367 if (!empty($modinfo->cms
[$modnumber]->icon
)) {
1368 $icon = "$CFG->pixpath/".$modinfo->cms
[$modnumber]->icon
;
1370 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1373 //Accessibility: for files get description via icon.
1375 if ('resource'==$mod->modname
) {
1376 if (!empty($modinfo->cms
[$modnumber]->icon
)) {
1377 $possaltname = $modinfo->cms
[$modnumber]->icon
;
1379 $mimetype = mimeinfo_from_icon('type', $possaltname);
1380 $altname = get_mimetype_description($mimetype);
1382 $altname = $mod->modfullname
;
1385 $altname = $mod->modfullname
;
1387 // Avoid unnecessary duplication.
1388 if (false!==stripos($instancename, $altname)) {
1391 // File type after name, for alphabetic lists (screen reader).
1393 $altname = get_accesshide(' '.$altname);
1396 $linkcss = $mod->visible ?
"" : " class=\"dimmed\" ";
1397 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1398 ' href="'.$CFG->wwwroot
.'/mod/'.$mod->modname
.'/view.php?id='.$mod->id
.'">'.
1399 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1400 $instancename.$altname.'</span></a>';
1402 if (!empty($CFG->enablegroupings
) && !empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1403 if (!isset($groupings)) {
1404 $groupings = groups_get_all_groupings($course->id
);
1406 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1409 if ($usetracking && $mod->modname
== 'forum') {
1410 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1411 echo '<span class="unread"> <a href="'.$CFG->wwwroot
.'/mod/forum/view.php?id='.$mod->id
.'">';
1413 echo $strunreadpostsone;
1415 print_string('unreadpostsnumber', 'forum', $unread);
1422 // TODO: we must define this as mod property!
1423 if ($groupbuttons and $mod->modname
!= 'label' and $mod->modname
!= 'resource' and $mod->modname
!= 'glossary') {
1424 if (! $mod->groupmodelink
= $groupbuttonslink) {
1425 $mod->groupmode
= $course->groupmode
;
1429 $mod->groupmode
= false;
1431 echo ' ';
1432 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1437 } elseif ($ismoving) {
1438 echo "<ul class=\"section\">\n";
1442 echo '<li><a title="'.$strmovefull.'"'.
1443 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.$USER->sesskey
.'">'.
1444 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1445 ' alt="'.$strmovehere.'" /></a></li>
1448 if (!empty($section->sequence
) ||
$ismoving) {
1449 echo "</ul><!--class='section'-->\n\n";
1454 * Prints the menus to add activities and resources.
1456 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1459 // check to see if user can add menus
1460 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1464 static $resources = false;
1465 static $activities = false;
1467 if ($resources === false) {
1468 $resources = array();
1469 $activities = array();
1471 foreach($modnames as $modname=>$modnamestr) {
1472 if (!course_allowed_module($course, $modname)) {
1476 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1477 if (!file_exists($libfile)) {
1480 include_once($libfile);
1481 $gettypesfunc = $modname.'_get_types';
1482 if (function_exists($gettypesfunc)) {
1483 $types = $gettypesfunc();
1484 foreach($types as $type) {
1485 if (!isset($type->modclass
) or !isset($type->typestr
)) {
1486 debugging('Incorrect activity type in '.$modname);
1489 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1490 $resources[$type->type
] = $type->typestr
;
1492 $activities[$type->type
] = $type->typestr
;
1496 // all mods without type are considered activity
1497 $activities[$modname] = $modnamestr;
1502 $straddactivity = get_string('addactivity');
1503 $straddresource = get_string('addresource');
1505 $output = '<div class="section_add_menus">';
1508 $output .= '<div class="horizontal">';
1511 if (!empty($resources)) {
1512 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1513 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1516 if (!empty($activities)) {
1518 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1519 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1523 $output .= '</div>';
1526 $output .= '</div>';
1536 * Return the course category context for the category with id $categoryid, except
1537 * that if $categoryid is 0, return the system context.
1539 * @param integer $categoryid a category id or 0.
1540 * @return object the corresponding context
1542 function get_category_or_system_context($categoryid) {
1544 return get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1546 return get_context_instance(CONTEXT_SYSTEM
);
1551 * Rebuilds the cached list of course activities stored in the database
1552 * @param int $courseid - id of course to rebuil, empty means all
1553 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1555 function rebuild_course_cache($courseid=0, $clearonly=false) {
1559 $courseselect = empty($courseid) ?
"" : "id = $courseid";
1560 set_field_select('course', 'modinfo', null, $courseselect);
1561 // update cached global COURSE too ;-)
1562 if ($courseid == $COURSE->id
) {
1563 $COURSE->modinfo
= null;
1565 // reset the fast modinfo cache
1567 get_fast_modinfo($reset);
1572 $select = "id = '$courseid'";
1575 @set_time_limit
(0); // this could take a while! MDL-10954
1578 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1579 while($course = rs_fetch_next_record($rs)) {
1580 $modinfo = serialize(get_array_of_activities($course->id
));
1581 if (!set_field("course", "modinfo", $modinfo, "id", $course->id
)) {
1582 notify("Could not cache module information for course '" . format_string($course->fullname
) . "'!");
1584 // update cached global COURSE too ;-)
1585 if ($course->id
== $COURSE->id
) {
1586 $COURSE->modinfo
= $modinfo;
1591 // reset the fast modinfo cache
1593 get_fast_modinfo($reset);
1597 * Gets the child categories of a given coures category. Uses a static cache
1598 * to make repeat calls efficient.
1600 * @param unknown_type $parentid the id of a course category.
1601 * @return array all the child course categories.
1603 function get_child_categories($parentid) {
1604 static $allcategories = null;
1606 // only fill in this variable the first time
1607 if (null == $allcategories) {
1608 $allcategories = array();
1610 $categories = get_categories();
1611 foreach ($categories as $category) {
1612 if (empty($allcategories[$category->parent
])) {
1613 $allcategories[$category->parent
] = array();
1615 $allcategories[$category->parent
][] = $category;
1619 if (empty($allcategories[$parentid])) {
1622 return $allcategories[$parentid];
1627 * This function recursively travels the categories, building up a nice list
1628 * for display. It also makes an array that list all the parents for each
1631 * For example, if you have a tree of categories like:
1632 * Miscellaneous (id = 1)
1633 * Subcategory (id = 2)
1634 * Sub-subcategory (id = 4)
1635 * Other category (id = 3)
1636 * Then after calling this function you will have
1637 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1638 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1639 * 3 => 'Other category');
1640 * $parents = array(2 => array(1), 4 => array(1, 2));
1642 * If you specify $requiredcapability, then only categories where the current
1643 * user has that capability will be added to $list, although all categories
1644 * will still be added to $parents, and if you only have $requiredcapability
1645 * in a child category, not the parent, then the child catgegory will still be
1648 * If you specify the option $excluded, then that category, and all its children,
1649 * are omitted from the tree. This is useful when you are doing something like
1650 * moving categories, where you do not want to allow people to move a category
1651 * to be the child of itself.
1653 * @param array $list For output, accumulates an array categoryid => full category path name
1654 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1655 * @param string $requiredcapability if given, only categories where the current
1656 * user has this capability will be added to $list.
1657 * @param integer $excludeid Omit this category and its children from the lists built.
1658 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1659 * @param string $path For internal use, as part of recursive calls.
1661 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1662 $excludeid = 0, $category = NULL, $path = "") {
1664 // initialize the arrays if needed
1665 if (!is_array($list)) {
1668 if (!is_array($parents)) {
1672 if (empty($category)) {
1673 // Start at the top level.
1674 $category = new stdClass
;
1677 // This is the excluded category, don't include it.
1678 if ($excludeid > 0 && $excludeid == $category->id
) {
1684 $path = $path.' / '.format_string($category->name
);
1686 $path = format_string($category->name
);
1689 // Add this category to $list, if the permissions check out.
1690 if ($requiredcapability) {
1691 ensure_context_subobj_present($category, CONTEXT_COURSECAT
);
1693 if (!$requiredcapability ||
has_capability($requiredcapability, $category->context
)) {
1694 $list[$category->id
] = $path;
1698 // Add all the children recursively, while updating the parents array.
1699 if ($categories = get_child_categories($category->id
)) {
1700 foreach ($categories as $cat) {
1701 if (!empty($category->id
)) {
1702 if (isset($parents[$category->id
])) {
1703 $parents[$cat->id
] = $parents[$category->id
];
1705 $parents[$cat->id
][] = $category->id
;
1707 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
1712 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
1713 /// Recursive function to print out all the categories in a nice format
1714 /// with or without courses included
1717 if (isset($CFG->max_category_depth
) && ($depth >= $CFG->max_category_depth
)) {
1721 if (!$displaylist) {
1722 make_categories_list($displaylist, $parentslist);
1726 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
))) {
1727 print_category_info($category, $depth, $showcourses);
1729 return; // Don't bother printing children of invisible categories
1733 $category->id
= "0";
1736 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
1737 $countcats = count($categories);
1741 foreach ($categories as $cat) {
1743 if ($count == $countcats) {
1746 $up = $first ?
false : true;
1747 $down = $last ?
false : true;
1750 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses);
1755 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1757 function make_categories_options() {
1758 make_categories_list($cats,$parents);
1759 foreach ($cats as $key => $value) {
1760 if (array_key_exists($key,$parents)) {
1761 if ($indent = count($parents[$key])) {
1762 for ($i = 0; $i < $indent; $i++
) {
1763 $cats[$key] = ' '.$cats[$key];
1771 function print_category_info($category, $depth, $showcourses = false) {
1772 /// Prints the category info in indented fashion
1773 /// This function is only used by print_whole_category_list() above
1776 static $strallowguests, $strrequireskey, $strsummary;
1778 if (empty($strsummary)) {
1779 $strallowguests = get_string('allowguests');
1780 $strrequireskey = get_string('requireskey');
1781 $strsummary = get_string('summary');
1784 $catlinkcss = $category->visible ?
'' : ' class="dimmed" ';
1786 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT
;
1787 if ($showcourses and $coursecount) {
1788 $catimage = '<img src="'.$CFG->pixpath
.'/i/course.gif" alt="" />';
1790 $catimage = " ";
1793 echo "\n\n".'<table class="categorylist">';
1795 $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');
1796 if ($showcourses and $coursecount) {
1801 $indent = $depth*30;
1802 $rows = count($courses) +
1;
1803 echo '<td class="category indentation" rowspan="'.$rows.'" valign="top">';
1804 print_spacer(10, $indent);
1808 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1809 echo '<td valign="top" class="category name">';
1810 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1812 echo '<td class="category info"> </td>';
1815 if ($courses && !(isset($CFG->max_category_depth
)&&($depth>=$CFG->max_category_depth
-1))) {
1816 foreach ($courses as $course) {
1817 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1818 echo '<tr><td valign="top"> ';
1819 echo '</td><td valign="top" class="course name">';
1820 echo '<a '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>';
1821 echo '</td><td align="right" valign="top" class="course info">';
1822 if ($course->guest
) {
1823 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1824 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath
.'/i/guest.gif" /></a>';
1826 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1828 if ($course->password
) {
1829 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1830 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath
.'/i/key.gif" /></a>';
1832 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1834 if ($course->summary
) {
1835 link_to_popup_window ('/course/info.php?id='.$course->id
, 'courseinfo',
1836 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath
.'/i/info.gif" />',
1837 400, 500, $strsummary);
1839 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1849 $indent = $depth*20;
1850 echo '<td class="category indentation" valign="top">';
1851 print_spacer(10, $indent);
1855 echo '<td valign="top" class="category name">';
1856 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1858 echo '<td valign="top" class="category number">';
1859 if (count($courses)) {
1860 echo count($courses);
1868 * Prints the turn editing on/off button on course/index.php or course/category.php.
1870 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1871 * @return string HTML of the editing button, or empty string, if this user is not allowed
1874 function update_category_button($categoryid = 0) {
1877 // Check permissions.
1878 $context = get_category_or_system_context($categoryid);
1879 if (!has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context)) {
1883 // Work out the appropriate action.
1884 if (!empty($USER->categoryediting
)) {
1885 $label = get_string('turneditingoff');
1888 $label = get_string('turneditingon');
1892 // Generate the button HTML.
1893 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
1895 $options['id'] = $categoryid;
1896 $page = 'category.php';
1898 $page = 'index.php';
1900 return print_single_button($CFG->wwwroot
. '/course/' . $page, $options,
1901 $label, 'get', '', true);
1904 function print_courses($category) {
1905 /// Category is 0 (for all courses) or an object
1909 if (!is_object($category) && $category==0) {
1910 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1911 if (is_array($categories) && count($categories) == 1) {
1912 $category = array_shift($categories);
1913 $courses = get_courses_wmanagers($category->id
,
1915 array('password','summary','currency'));
1917 $courses = get_courses_wmanagers('all',
1919 array('password','summary','currency'));
1923 $courses = get_courses_wmanagers($category->id
,
1925 array('password','summary','currency'));
1929 echo '<ul class="unlist">';
1930 foreach ($courses as $course) {
1931 if ($course->visible
== 1
1932 ||
has_capability('moodle/course:viewhiddencourses',$course->context
)) {
1934 print_course($course);
1940 print_heading(get_string("nocoursesyet"));
1941 $context = get_context_instance(CONTEXT_SYSTEM
);
1942 if (has_capability('moodle/course:create', $context)) {
1944 $options['category'] = $category->id
;
1945 echo '<div class="addcoursebutton">';
1946 print_single_button($CFG->wwwroot
.'/course/edit.php', $options, get_string("addnewcourse"));
1956 function print_course($course) {
1960 if (isset($course->context
)) {
1961 $context = $course->context
;
1963 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1966 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1968 echo '<div class="coursebox clearfix">';
1969 echo '<div class="info">';
1970 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1971 $linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'.
1972 format_string($course->fullname
).'</a></div>';
1974 /// first find all roles that are supposed to be displayed
1976 if (!empty($CFG->coursemanager
)) {
1977 $managerroles = split(',', $CFG->coursemanager
);
1978 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
1979 $namesarray = array();
1980 if (isset($course->managers
)) {
1981 if (count($course->managers
)) {
1982 $rusers = $course->managers
;
1983 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1985 /// Rename some of the role names if needed
1986 if (isset($context)) {
1987 $aliasnames = get_records('role_names', 'contextid', $context->id
,'','roleid,contextid,name');
1990 // keep a note of users displayed to eliminate duplicates
1991 $usersshown = array();
1992 foreach ($rusers as $ra) {
1994 // if we've already displayed user don't again
1995 if (in_array($ra->user
->id
,$usersshown)) {
1998 $usersshown[] = $ra->user
->id
;
2000 if ($ra->hidden
== 0 ||
$canseehidden) {
2001 $fullname = fullname($ra->user
, $canviewfullnames);
2002 if ($ra->hidden
== 1) {
2003 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
2008 if (isset($aliasnames[$ra->roleid
])) {
2009 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
2012 $namesarray[] = format_string($ra->rolename
)
2013 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$ra->user
->id
.'&course='.SITEID
.'">'
2014 . $fullname . '</a>' . $status;
2019 $rusers = get_role_users($managerroles, $context,
2020 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
2021 if (is_array($rusers) && count($rusers)) {
2022 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2024 /// Rename some of the role names if needed
2025 if (isset($context)) {
2026 $aliasnames = get_records('role_names', 'contextid', $context->id
,'','roleid,contextid,name');
2029 foreach ($rusers as $teacher) {
2030 $fullname = fullname($teacher, $canviewfullnames);
2032 /// Apply role names
2033 if (isset($aliasnames[$teacher->roleid
])) {
2034 $teacher->rolename
= $aliasnames[$teacher->roleid
]->name
;
2037 $namesarray[] = format_string($teacher->rolename
)
2038 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$teacher->id
.'&course='.SITEID
.'">'
2039 . $fullname . '</a>';
2044 if (!empty($namesarray)) {
2045 echo "<ul class=\"teachers\">\n<li>";
2046 echo implode('</li><li>', $namesarray);
2051 require_once("$CFG->dirroot/enrol/enrol.class.php");
2052 $enrol = enrolment_factory
::factory($course->enrol
);
2053 echo $enrol->get_access_icons($course);
2055 echo '</div><div class="summary">';
2057 $options->noclean
= true;
2058 $options->para
= false;
2059 echo format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
);
2065 function print_my_moodle() {
2066 /// Prints custom user information on the home page.
2067 /// Over time this can include all sorts of information
2071 if (empty($USER->id
)) {
2072 error("It shouldn't be possible to see My Moodle without being logged in.");
2075 $courses = get_my_courses($USER->id
, 'visible DESC,sortorder ASC', array('summary'));
2077 $rcourses = array();
2078 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
2079 $rcourses = get_my_remotecourses($USER->id
);
2080 $rhosts = get_my_remotehosts();
2083 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
2085 if (!empty($courses)) {
2086 echo '<ul class="unlist">';
2087 foreach ($courses as $course) {
2088 if ($course->id
== SITEID
) {
2092 print_course($course, "100%");
2099 if (!empty($rcourses)) {
2100 // at the IDP, we know of all the remote courses
2101 foreach ($rcourses as $course) {
2102 print_remote_course($course, "100%");
2104 } elseif (!empty($rhosts)) {
2105 // non-IDP, we know of all the remote servers, but not courses
2106 foreach ($rhosts as $host) {
2107 print_remote_host($host, "100%");
2113 if (count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
2114 echo "<table width=\"100%\"><tr><td align=\"center\">";
2115 print_course_search("", false, "short");
2116 echo "</td><td align=\"center\">";
2117 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2118 echo "</td></tr></table>\n";
2122 if (count_records("course_categories") > 1) {
2123 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
2124 print_whole_category_list();
2125 print_simple_box_end();
2133 function print_course_search($value="", $return=false, $format="plain") {
2140 $id = 'coursesearch';
2146 $strsearchcourses= get_string("searchcourses");
2148 if ($format == 'plain') {
2149 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2150 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2151 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2152 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
2153 $output .= '<input type="submit" value="'.get_string('go').'" />';
2154 $output .= '</fieldset></form>';
2155 } else if ($format == 'short') {
2156 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2157 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2158 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2159 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2160 $output .= '<input type="submit" value="'.get_string('go').'" />';
2161 $output .= '</fieldset></form>';
2162 } else if ($format == 'navbar') {
2163 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2164 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2165 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2166 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2167 $output .= '<input type="submit" value="'.get_string('go').'" />';
2168 $output .= '</fieldset></form>';
2177 function print_remote_course($course, $width="100%") {
2183 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2185 echo '<div class="coursebox remotecoursebox clearfix">';
2186 echo '<div class="info">';
2187 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2188 $linkcss.' href="'.$url.'">'
2189 . format_string($course->fullname
) .'</a><br />'
2190 . format_string($course->hostname
) . ' : '
2191 . format_string($course->cat_name
) . ' : '
2192 . format_string($course->shortname
). '</div>';
2193 echo '</div><div class="summary">';
2195 $options->noclean
= true;
2196 $options->para
= false;
2197 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
2202 function print_remote_host($host, $width="100%") {
2208 echo '<div class="coursebox clearfix">';
2209 echo '<div class="info">';
2210 echo '<div class="name">';
2211 echo '<img src="'.$CFG->pixpath
.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2212 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2213 . s($host['name']).'</a> - ';
2214 echo $host['count'] . ' ' . get_string('courses');
2221 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2223 function add_course_module($mod) {
2225 $mod->added
= time();
2228 return insert_record("course_modules", $mod);
2232 * Returns course section - creates new if does not exist yet.
2233 * @param int $relative section number
2234 * @param int $courseid
2235 * @return object $course_section object
2237 function get_course_section($section, $courseid) {
2238 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2242 $cw->course
= $courseid;
2243 $cw->section
= $section;
2246 $id = insert_record("course_sections", $cw);
2247 return get_record("course_sections", "id", $id);
2250 * Given a full mod object with section and course already defined, adds this module to that section.
2252 * @param object $mod
2253 * @param int $beforemod An existing ID which we will insert the new module before
2254 * @return int The course_sections ID where the mod is inserted
2256 function add_mod_to_section($mod, $beforemod=NULL) {
2258 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2260 $section->sequence
= trim($section->sequence
);
2262 if (empty($section->sequence
)) {
2263 $newsequence = "$mod->coursemodule";
2265 } else if ($beforemod) {
2266 $modarray = explode(",", $section->sequence
);
2268 if ($key = array_keys ($modarray, $beforemod->id
)) {
2269 $insertarray = array($mod->id
, $beforemod->id
);
2270 array_splice($modarray, $key[0], 1, $insertarray);
2271 $newsequence = implode(",", $modarray);
2273 } else { // Just tack it on the end anyway
2274 $newsequence = "$section->sequence,$mod->coursemodule";
2278 $newsequence = "$section->sequence,$mod->coursemodule";
2281 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id
)) {
2282 return $section->id
; // Return course_sections ID that was used.
2287 } else { // Insert a new record
2288 $section->course
= $mod->course
;
2289 $section->section
= $mod->section
;
2290 $section->summary
= "";
2291 $section->sequence
= $mod->coursemodule
;
2292 return insert_record("course_sections", $section);
2296 function set_coursemodule_groupmode($id, $groupmode) {
2297 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2300 function set_coursemodule_groupingid($id, $groupingid) {
2301 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2304 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2305 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2308 function set_coursemodule_idnumber($id, $idnumber) {
2309 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2312 * $prevstateoverrides = true will set the visibility of the course module
2313 * to what is defined in visibleold. This enables us to remember the current
2314 * visibility when making a whole section hidden, so that when we toggle
2315 * that section back to visible, we are able to return the visibility of
2316 * the course module back to what it was originally.
2318 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2319 if (!$cm = get_record('course_modules', 'id', $id)) {
2322 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2325 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2326 foreach($events as $event) {
2334 if ($prevstateoverrides) {
2335 if ($visible == '0') {
2336 // Remember the current visible state so we can toggle this back.
2337 set_field('course_modules', 'visibleold', $cm->visible
, 'id', $id);
2339 // Get the previous saved visible states.
2340 return set_field('course_modules', 'visible', $cm->visibleold
, 'id', $id);
2343 return set_field("course_modules", "visible", $visible, "id", $id);
2347 * Delete a course module and any associated data at the course level (events)
2348 * Until 1.5 this function simply marked a deleted flag ... now it
2349 * deletes it completely.
2352 function delete_course_module($id) {
2354 require_once($CFG->libdir
.'/gradelib.php');
2356 if (!$cm = get_record('course_modules', 'id', $id)) {
2359 $modulename = get_field('modules', 'name', 'id', $cm->module
);
2360 //delete events from calendar
2361 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2362 foreach($events as $event) {
2363 delete_event($event->id
);
2366 //delete grade items, outcome items and grades attached to modules
2367 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2368 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2369 foreach ($grade_items as $grade_item) {
2370 $grade_item->delete('moddelete');
2374 return delete_records('course_modules', 'id', $cm->id
);
2377 function delete_mod_from_section($mod, $section) {
2379 if ($section = get_record("course_sections", "id", "$section") ) {
2381 $modarray = explode(",", $section->sequence
);
2383 if ($key = array_keys ($modarray, $mod)) {
2384 array_splice($modarray, $key[0], 1);
2385 $newsequence = implode(",", $modarray);
2386 return set_field("course_sections", "sequence", $newsequence, "id", $section->id
);
2396 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2398 * @param object $course
2399 * @param int $section
2400 * @param int $move (-1 or 1)
2402 function move_section($course, $section, $move) {
2403 /// Moves a whole course section up and down within the course
2410 $sectiondest = $section +
$move;
2412 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2416 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2420 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2425 $count = abs($sectiondest - $section);
2426 $direction = ($sectiondest - $section) / $count;
2428 for ($i = 0, $ref = $section +
$direction; $i < $count; ++
$i, $ref +
= $direction) {
2429 if (!set_field("course_sections", "section", $ref - $direction, 'course', $course->id
, 'section', $ref)) {
2434 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2438 // if the focus is on the section that is being moved, then move the focus along
2439 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2440 course_set_display($course->id
, $sectiondest);
2443 // Check for duplicates and fix order if needed.
2444 // There is a very rare case that some sections in the same course have the same section id.
2445 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2447 foreach ($sections as $section) {
2448 if ($section->section
!= $n) {
2449 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
2459 * Moves a section within a course, from a position to another.
2460 * Be very careful: $section and $destination refer to section number,
2463 * @param object $course
2464 * @param int $section Section number (not id!!!)
2465 * @param int $destination
2466 * @return boolean Result
2468 function move_section_to($course, $section, $destination) {
2469 /// Moves a whole course section up and down within the course
2472 if (!$destination && $destination != 0) {
2476 if ($destination > $course->numsections
) {
2480 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2481 if (!$sections = get_records_menu('course_sections', 'course',$course->id
, 'section ASC, id ASC', 'id, section')) {
2485 $sections = reorder_sections($sections, $section, $destination);
2487 // Update all sections
2488 foreach ($sections as $id => $position) {
2489 set_field('course_sections', 'section', $position, 'id', $id);
2492 // if the focus is on the section that is being moved, then move the focus along
2493 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2494 course_set_display($course->id
, $destination);
2500 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2501 * an original position number and a target position number, rebuilds the array so that the
2502 * move is made without any duplication of section positions.
2503 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2504 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2506 * @param array $sections
2507 * @param int $origin_position
2508 * @param int $target_position
2511 function reorder_sections($sections, $origin_position, $target_position) {
2512 if (!is_array($sections)) {
2516 // We can't move section position 0
2517 if ($origin_position < 1) {
2518 echo "We can't move section position 0";
2522 // Locate origin section in sections array
2523 if (!$origin_key = array_search($origin_position, $sections)) {
2524 echo "searched position not in sections array";
2525 return false; // searched position not in sections array
2528 // Extract origin section
2529 $origin_section = $sections[$origin_key];
2530 unset($sections[$origin_key]);
2532 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2534 $append_array = array();
2535 foreach ($sections as $id => $position) {
2537 $append_array[$id] = $position;
2538 unset($sections[$id]);
2540 if ($position == $target_position) {
2545 // Append moved section
2546 $sections[$origin_key] = $origin_section;
2548 // Append rest of array (if applicable)
2549 if (!empty($append_array)) {
2550 foreach ($append_array as $id => $position) {
2551 $sections[$id] = $position;
2555 // Renumber positions
2557 foreach ($sections as $id => $p) {
2558 $sections[$id] = $position;
2566 function moveto_module($mod, $section, $beforemod=NULL) {
2567 /// All parameters are objects
2568 /// Move the module object $mod to the specified $section
2569 /// If $beforemod exists then that is the module
2570 /// before which $modid should be inserted
2572 /// Remove original module from original section
2574 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2575 notify("Could not delete module from existing section");
2578 /// Update module itself if necessary
2580 if ($mod->section
!= $section->id
) {
2581 $mod->section
= $section->id
;
2582 if (!update_record("course_modules", $mod)) {
2585 // if moving to a hidden section then hide module
2586 if (!$section->visible
) {
2587 set_coursemodule_visible($mod->id
, 0);
2591 /// Add the module into the new section
2593 $mod->course
= $section->course
;
2594 $mod->section
= $section->section
; // need relative reference
2595 $mod->coursemodule
= $mod->id
;
2597 if (! add_mod_to_section($mod, $beforemod)) {
2605 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2611 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
2612 // no permission to edit
2613 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2618 $str->delete
= get_string("delete");
2619 $str->move
= get_string("move");
2620 $str->moveup
= get_string("moveup");
2621 $str->movedown
= get_string("movedown");
2622 $str->moveright
= get_string("moveright");
2623 $str->moveleft
= get_string("moveleft");
2624 $str->update
= get_string("update");
2625 $str->duplicate
= get_string("duplicate");
2626 $str->hide
= get_string("hide");
2627 $str->show
= get_string("show");
2628 $str->clicktochange
= get_string("clicktochange");
2629 $str->forcedmode
= get_string("forcedmode");
2630 $str->groupsnone
= get_string("groupsnone");
2631 $str->groupsseparate
= get_string("groupsseparate");
2632 $str->groupsvisible
= get_string("groupsvisible");
2633 $sesskey = sesskey();
2636 if ($section >= 0) {
2637 $section = '&sr='.$section; // Section return
2643 $path = $CFG->wwwroot
.'/course';
2648 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2649 if ($mod->visible
) {
2650 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2651 '&sesskey='.$sesskey.$section.'"><img'.
2652 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2653 ' alt="'.$str->hide
.'" /></a>'."\n";
2655 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2656 '&sesskey='.$sesskey.$section.'"><img'.
2657 ' src="'.$CFG->pixpath
.'/t/show.gif" class="iconsmall" '.
2658 ' alt="'.$str->show
.'" /></a>'."\n";
2664 if ($mod->groupmode
!== false) {
2665 if ($mod->groupmode
== SEPARATEGROUPS
) {
2666 $grouptitle = $str->groupsseparate
;
2667 $groupclass = 'editing_groupsseparate';
2668 $groupimage = $CFG->pixpath
.'/t/groups.gif';
2669 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
2670 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
2671 $grouptitle = $str->groupsvisible
;
2672 $groupclass = 'editing_groupsvisible';
2673 $groupimage = $CFG->pixpath
.'/t/groupv.gif';
2674 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
2676 $grouptitle = $str->groupsnone
;
2677 $groupclass = 'editing_groupsnone';
2678 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2679 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
2681 if ($mod->groupmodelink
) {
2682 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
2683 '<img src="'.$groupimage.'" class="iconsmall" '.
2684 'alt="'.$grouptitle.'" /></a>';
2686 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2687 ' src="'.$groupimage.'" class="iconsmall" '.
2688 'alt="'.$grouptitle.'" />';
2694 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2696 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2697 '&sesskey='.$sesskey.$section.'"><img'.
2698 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2699 ' alt="'.$str->move
.'" /></a>'."\n";
2701 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2702 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
2703 ' src="'.$CFG->pixpath
.'/t/up.gif" class="iconsmall" '.
2704 ' alt="'.$str->moveup
.'" /></a>'."\n".
2705 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2706 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2707 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2708 ' alt="'.$str->movedown
.'" /></a>'."\n";
2715 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2717 if (right_to_left()) { // Exchange arrows on RTL
2718 $rightarrow = 'left.gif';
2719 $leftarrow = 'right.gif';
2721 $rightarrow = 'right.gif';
2722 $leftarrow = 'left.gif';
2726 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2727 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2728 ' src="'.$CFG->pixpath
.'/t/'.$leftarrow.'" class="iconsmall" '.
2729 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2732 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2733 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
2734 ' src="'.$CFG->pixpath
.'/t/'.$rightarrow.'" class="iconsmall" '.
2735 ' alt="'.$str->moveright
.'" /></a>'."\n";
2739 return '<span class="commands">'."\n".$leftright.$move.
2740 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
2741 '&sesskey='.$sesskey.$section.'"><img'.
2742 ' src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" '.
2743 ' alt="'.$str->update
.'" /></a>'."\n".
2744 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
2745 '&sesskey='.$sesskey.$section.'"><img'.
2746 ' src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" '.
2747 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2751 * given a course object with shortname & fullname, this function will
2752 * truncate the the number of chars allowed and add ... if it was too long
2754 function course_format_name ($course,$max=100) {
2756 $str = $course->shortname
.': '. $course->fullname
;
2757 if (strlen($str) <= $max) {
2761 return substr($str,0,$max-3).'...';
2766 * This function will return true if the given course is a child course at all
2768 function course_in_meta ($course) {
2769 return record_exists("course_meta","child_course",$course->id
);
2774 * Print standard form elements on module setup forms in mod/.../mod.html
2776 function print_standard_coursemodule_settings($form, $features=null) {
2777 if (! $course = get_record('course', 'id', $form->course
)) {
2778 error("This course doesn't exist");
2780 print_groupmode_setting($form, $course);
2781 if (!empty($features->groupings
)) {
2782 print_grouping_settings($form, $course);
2784 print_visible_setting($form, $course);
2788 * Print groupmode form element on module setup forms in mod/.../mod.html
2790 function print_groupmode_setting($form, $course=NULL) {
2792 if (empty($course)) {
2793 if (! $course = get_record('course', 'id', $form->course
)) {
2794 error("This course doesn't exist");
2797 if ($form->coursemodule
) {
2798 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2799 error("This course module doesn't exist");
2801 $groupmode = groups_get_activity_groupmode($cm);
2804 $groupmode = groups_get_course_groupmode($course);
2806 if ($course->groupmode
or (!$course->groupmodeforce
)) {
2807 echo '<tr valign="top">';
2808 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2809 echo '<td align="left">';
2811 $choices[NOGROUPS
] = get_string('groupsnone');
2812 $choices[SEPARATEGROUPS
] = get_string('groupsseparate');
2813 $choices[VISIBLEGROUPS
] = get_string('groupsvisible');
2814 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce
);
2815 helpbutton('groupmode', get_string('groupmode'));
2821 * Print groupmode form element on module setup forms in mod/.../mod.html
2823 function print_grouping_settings($form, $course=NULL) {
2825 if (empty($course)) {
2826 if (! $course = get_record('course', 'id', $form->course
)) {
2827 error("This course doesn't exist");
2830 if ($form->coursemodule
) {
2831 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2832 error("This course module doesn't exist");
2838 $groupings = get_records_menu('groupings', 'courseid', $course->id
, 'name', 'id, name');
2839 if (!empty($groupings)) {
2840 echo '<tr valign="top">';
2841 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2842 echo '<td align="left">';
2845 $groupingid = isset($cm->groupingid
) ?
$cm->groupingid
: 0;
2847 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2850 $checked = empty($cm->groupmembersonly
) ?
'':'checked="checked"';
2851 echo '<tr valign="top">';
2852 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2853 echo '<td align="left">';
2854 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2861 * Print visibility setting form element on module setup forms in mod/.../mod.html
2863 function print_visible_setting($form, $course=NULL) {
2864 if (empty($course)) {
2865 if (! $course = get_record('course', 'id', $form->course
)) {
2866 error("This course doesn't exist");
2869 if ($form->coursemodule
) {
2870 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule
);
2875 if ($form->mode
== 'add') { // in this case $form->section is the section number, not the id
2876 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section
, 'course', $form->course
);
2878 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2880 if ($hiddensection) {
2884 echo '<tr valign="top">';
2885 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2886 echo '<td align="left">';
2887 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
2888 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2892 function update_restricted_mods($course,$mods) {
2894 /// Delete all the current restricted list
2895 delete_records('course_allowed_modules','course',$course->id
);
2897 if (empty($course->restrictmodules
)) {
2898 return; // We're done
2901 /// Insert the new list of restricted mods
2902 foreach ($mods as $mod) {
2904 continue; // this is the 'allow none' option
2907 $am->course
= $course->id
;
2909 insert_record('course_allowed_modules',$am);
2914 * This function will take an int (module id) or a string (module name)
2915 * and return true or false, whether it's allowed in the given course (object)
2916 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2917 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2920 function course_allowed_module($course,$mod) {
2922 if (empty($course->restrictmodules
)) {
2926 // Admins and admin-like people who can edit everything can also add anything.
2927 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
2928 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
))) {
2932 if (is_numeric($mod)) {
2934 } else if (is_string($mod)) {
2935 $modid = get_field('modules','id','name',$mod);
2937 if (empty($modid)) {
2941 return (record_exists('course_allowed_modules','course',$course->id
,'module',$modid));
2945 * Recursively delete category including all subcategories and courses.
2946 * @param object $ccategory
2947 * @return bool status
2949 function category_delete_full($category, $showfeedback=true) {
2951 require_once($CFG->libdir
.'/gradelib.php');
2952 require_once($CFG->libdir
.'/questionlib.php');
2954 if ($children = get_records('course_categories', 'parent', $category->id
, 'sortorder ASC')) {
2955 foreach ($children as $childcat) {
2956 if (!category_delete_full($childcat, $showfeedback)) {
2957 notify("Error deleting category $childcat->name");
2963 if ($courses = get_records('course', 'category', $category->id
, 'sortorder ASC')) {
2964 foreach ($courses as $course) {
2965 if (!delete_course($course->id
, false)) {
2966 notify("Error deleting course $course->shortname");
2969 notify(get_string('coursedeleted', '', $course->shortname
), 'notifysuccess');
2973 // now delete anything that may depend on course category context
2974 grade_course_category_delete($category->id
, 0, $showfeedback);
2975 if (!question_delete_course_category($category, 0, $showfeedback)) {
2976 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2980 // finally delete the category and it's context
2981 delete_records('course_categories', 'id', $category->id
);
2982 delete_context(CONTEXT_COURSECAT
, $category->id
);
2984 events_trigger('course_category_deleted', $category);
2986 notify(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
2992 * Delete category, but move contents to another category.
2993 * @param object $ccategory
2994 * @param int $newparentid category id
2995 * @return bool status
2997 function category_delete_move($category, $newparentid, $showfeedback=true) {
2999 require_once($CFG->libdir
.'/gradelib.php');
3000 require_once($CFG->libdir
.'/questionlib.php');
3002 if (!$newparentcat = get_record('course_categories', 'id', $newparentid)) {
3006 if ($children = get_records('course_categories', 'parent', $category->id
, 'sortorder ASC')) {
3007 foreach ($children as $childcat) {
3008 if (!move_category($childcat, $newparentcat)) {
3009 notify("Error moving category $childcat->name");
3015 if ($courses = get_records('course', 'category', $category->id
, 'sortorder ASC', 'id')) {
3016 if (!move_courses(array_keys($courses), $newparentid)) {
3017 notify("Error moving courses");
3020 notify(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
3023 // now delete anything that may depend on course category context
3024 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
3025 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3026 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3030 // finally delete the category and it's context
3031 delete_records('course_categories', 'id', $category->id
);
3032 delete_context(CONTEXT_COURSECAT
, $category->id
);
3034 events_trigger('course_category_deleted', $category);
3036 notify(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3042 *** Efficiently moves many courses around while maintaining
3043 *** sortorder in order.
3045 *** $courseids is an array of course ids
3049 function move_courses ($courseids, $categoryid) {
3053 if (!empty($courseids)) {
3055 $courseids = array_reverse($courseids);
3057 foreach ($courseids as $courseid) {
3059 if (! $course = get_record("course", "id", $courseid)) {
3060 notify("Error finding course $courseid");
3062 // figure out a sortorder that we can use in the destination category
3063 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
3064 FROM ' . $CFG->prefix
. 'course WHERE category=' . $categoryid);
3065 if (is_null($sortorder) ||
$sortorder === false) {
3066 // the category is empty
3067 // rather than let the db default to 0
3068 // set it to > 100 and avoid extra work in fix_coursesortorder()
3070 } else if ($sortorder < 10) {
3071 fix_course_sortorder($categoryid);
3074 $course->category
= $categoryid;
3075 $course->sortorder
= $sortorder;
3076 $course->fullname
= addslashes($course->fullname
);
3077 $course->shortname
= addslashes($course->shortname
);
3078 $course->summary
= addslashes($course->summary
);
3079 $course->password
= addslashes($course->password
);
3080 $course->teacher
= addslashes($course->teacher
);
3081 $course->teachers
= addslashes($course->teachers
);
3082 $course->student
= addslashes($course->student
);
3083 $course->students
= addslashes($course->students
);
3085 if (!update_record('course', $course)) {
3086 notify("An error occurred - course not moved!");
3089 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3090 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3091 context_moved($context, $newparent);
3094 fix_course_sortorder();
3100 *** Efficiently moves a category - NOTE that this can have
3101 *** a huge impact access-control-wise...
3105 function move_category ($category, $newparentcat) {
3109 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3111 if (empty($newparentcat->id
)) {
3112 if (!set_field('course_categories', 'parent', 0, 'id', $category->id
)) {
3115 $newparent = get_context_instance(CONTEXT_SYSTEM
);
3117 if (!set_field('course_categories', 'parent', $newparentcat->id
, 'id', $category->id
)) {
3120 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
3123 context_moved($context, $newparent);
3125 // The most effective thing would be to find the common parent,
3126 // until then, do it sitewide...
3127 fix_course_sortorder();
3134 * @param string $format Course format ID e.g. 'weeks'
3135 * @return Name that the course format prefers for sections
3137 function get_section_name($format) {
3138 $sectionname = get_string("name$format","format_$format");
3139 if($sectionname == "[[name$format]]") {
3140 $sectionname = get_string("name$format");
3142 return $sectionname;
3146 * Can the current user delete this course?
3147 * @param int $courseid
3150 * Exception here to fix MDL-7796.
3153 * Course creators who can manage activities in the course
3154 * shoule be allowed to delete the course. We do it this
3155 * way because we need a quick fix to bring the functionality
3156 * in line with what we had pre-roles. We can't give the
3157 * default course creator role moodle/course:delete at
3158 * CONTEXT_SYSTEM level because this will allow them to
3159 * delete any course in the site. So we hard code this here
3162 * @author vyshane AT gmail.com
3164 function can_delete_course($courseid) {
3166 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3168 return ( has_capability('moodle/course:delete', $context)
3169 ||
(has_capability('moodle/legacy:coursecreator', $context)
3170 && has_capability('moodle/course:manageactivities', $context)) );
3174 * Save the Your name for 'Some role' strings.
3176 * @param integer $courseid the id of this course.
3177 * @param array $data the data that came from the course settings form.
3179 function save_local_role_names($courseid, $data) {
3180 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3182 foreach ($data as $fieldname => $value) {
3183 if (!strstr($fieldname, 'role_')) {
3186 list($ignored, $roleid) = explode('_', $fieldname);
3188 // make up our mind whether we want to delete, update or insert
3190 delete_records('role_names', 'contextid', $context->id
, 'roleid', $roleid);
3192 } else if ($rolename = get_record('role_names', 'contextid', $context->id
, 'roleid', $roleid)) {
3193 $rolename->name
= $value;
3194 update_record('role_names', $rolename);
3197 $rolename = new stdClass
;
3198 $rolename->contextid
= $context->id
;
3199 $rolename->roleid
= $roleid;
3200 $rolename->name
= $value;
3201 insert_record('role_names', $rolename, false);
3207 * Create a course and either return a $course object or false
3209 * @param object $data - all the data needed for an entry in the 'course' table
3211 function create_course($data) {
3214 // preprocess allowed mods
3215 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
3216 unset($data->allowedmods
);
3217 if ($CFG->restrictmodulesfor
== 'all') {
3218 $data->restrictmodules
= 1;
3220 $data->restrictmodules
= 0;
3223 $data->timecreated
= time();
3225 // place at beginning of category
3226 fix_course_sortorder();
3227 $data->sortorder
= get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
3228 if (empty($data->sortorder
)) {
3229 $data->sortorder
= 100;
3232 if ($newcourseid = insert_record('course', $data)) { // Set up new course
3234 $course = get_record('course', 'id', $newcourseid);
3237 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
3238 blocks_repopulate_page($page); // Return value not checked because you can always edit later
3240 update_restricted_mods($course, $allowedmods);
3242 $section = new object();
3243 $section->course
= $course->id
; // Create a default section.
3244 $section->section
= 0;
3245 $section->id
= insert_record('course_sections', $section);
3247 fix_course_sortorder();
3249 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3251 // Save any custom role names.
3252 save_local_role_names($course->id
, $data);
3255 events_trigger('course_created', $course);
3260 return false; // error
3264 * Update a course and return true or false
3266 * @param object $data - all the data needed for an entry in the 'course' table
3268 function update_course($data) {
3271 // Preprocess allowed mods
3272 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
3273 unset($data->allowedmods
);
3275 // Normal teachers can't change setting
3276 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3277 unset($data->restrictmodules
);
3281 $oldcourse = get_record('course', 'id', $data->id
); // should not fail, already tested above
3282 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $oldcourse->category
))
3283 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $data->category
))) {
3284 // can not move to new category, keep the old one
3285 unset($data->category
);
3286 } elseif ($oldcourse->category
!= $data->category
) {
3290 // Update with the new data
3291 if (update_record('course', $data)) {
3293 $course = get_record('course', 'id', $data->id
);
3295 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3297 // "Admins" can change allowed mods for a course
3298 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3299 update_restricted_mods($course, $allowedmods);
3303 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3304 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3305 context_moved($context, $newparent);
3308 fix_course_sortorder();
3310 // Test for and remove blocks which aren't appropriate anymore
3311 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
3312 blocks_remove_inappropriate($page);
3314 // Save any custom role names.
3315 save_local_role_names($course->id
, $data);
3318 events_trigger('course_updated', $course);