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 genearlbox 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('moodle/site:viewreports', 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);
1344 $extra = $modinfo->cms
[$modnumber]->extra
;
1346 if ($mod->modname
== "label") {
1347 if (!$mod->visible
) {
1348 echo "<span class=\"dimmed_text\">";
1350 echo format_text($extra, FORMAT_HTML
, $labelformatoptions);
1351 if (!$mod->visible
) {
1354 if (!empty($CFG->enablegroupings
) && !empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1355 if (!isset($groupings)) {
1356 $groupings = groups_get_all_groupings($course->id
);
1358 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1361 } else { // Normal activity
1362 $instancename = format_string($modinfo->cms
[$modnumber]->name
, true, $course->id
);
1364 if (!empty($modinfo->cms
[$modnumber]->icon
)) {
1365 $icon = "$CFG->pixpath/".$modinfo->cms
[$modnumber]->icon
;
1367 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1370 //Accessibility: for files get description via icon.
1372 if ('resource'==$mod->modname
) {
1373 if (!empty($modinfo->cms
[$modnumber]->icon
)) {
1374 $possaltname = $modinfo->cms
[$modnumber]->icon
;
1376 $mimetype = mimeinfo_from_icon('type', $possaltname);
1377 $altname = get_mimetype_description($mimetype);
1379 $altname = $mod->modfullname
;
1382 $altname = $mod->modfullname
;
1384 // Avoid unnecessary duplication.
1385 if (false!==stripos($instancename, $altname)) {
1388 // File type after name, for alphabetic lists (screen reader).
1390 $altname = get_accesshide(' '.$altname);
1393 $linkcss = $mod->visible ?
"" : " class=\"dimmed\" ";
1394 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1395 ' href="'.$CFG->wwwroot
.'/mod/'.$mod->modname
.'/view.php?id='.$mod->id
.'">'.
1396 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1397 $instancename.$altname.'</span></a>';
1399 if (!empty($CFG->enablegroupings
) && !empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1400 if (!isset($groupings)) {
1401 $groupings = groups_get_all_groupings($course->id
);
1403 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1406 if ($usetracking && $mod->modname
== 'forum') {
1407 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1408 echo '<span class="unread"> <a href="'.$CFG->wwwroot
.'/mod/forum/view.php?id='.$mod->id
.'">';
1410 echo $strunreadpostsone;
1412 print_string('unreadpostsnumber', 'forum', $unread);
1419 // TODO: we must define this as mod property!
1420 if ($groupbuttons and $mod->modname
!= 'label' and $mod->modname
!= 'resource' and $mod->modname
!= 'glossary') {
1421 if (! $mod->groupmodelink
= $groupbuttonslink) {
1422 $mod->groupmode
= $course->groupmode
;
1426 $mod->groupmode
= false;
1428 echo ' ';
1429 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1434 } elseif ($ismoving) {
1435 echo "<ul class=\"section\">\n";
1439 echo '<li><a title="'.$strmovefull.'"'.
1440 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.$USER->sesskey
.'">'.
1441 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1442 ' alt="'.$strmovehere.'" /></a></li>
1445 if (!empty($section->sequence
) ||
$ismoving) {
1446 echo "</ul><!--class='section'-->\n\n";
1451 * Prints the menus to add activities and resources.
1453 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1456 // check to see if user can add menus
1457 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1461 static $resources = false;
1462 static $activities = false;
1464 if ($resources === false) {
1465 $resources = array();
1466 $activities = array();
1468 foreach($modnames as $modname=>$modnamestr) {
1469 if (!course_allowed_module($course, $modname)) {
1473 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1474 if (!file_exists($libfile)) {
1477 include_once($libfile);
1478 $gettypesfunc = $modname.'_get_types';
1479 if (function_exists($gettypesfunc)) {
1480 $types = $gettypesfunc();
1481 foreach($types as $type) {
1482 if (!isset($type->modclass
) or !isset($type->typestr
)) {
1483 debugging('Incorrect activity type in '.$modname);
1486 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1487 $resources[$type->type
] = $type->typestr
;
1489 $activities[$type->type
] = $type->typestr
;
1493 // all mods without type are considered activity
1494 $activities[$modname] = $modnamestr;
1499 $straddactivity = get_string('addactivity');
1500 $straddresource = get_string('addresource');
1502 $output = '<div class="section_add_menus">';
1505 $output .= '<div class="horizontal">';
1508 if (!empty($resources)) {
1509 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1510 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1513 if (!empty($activities)) {
1515 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1516 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1520 $output .= '</div>';
1523 $output .= '</div>';
1533 * Rebuilds the cached list of course activities stored in the database
1534 * @param int $courseid - id of course to rebuil, empty means all
1535 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1537 function rebuild_course_cache($courseid=0, $clearonly=false) {
1541 $courseselect = empty($courseid) ?
"" : "id = $courseid";
1542 set_field_select('course', 'modinfo', null, $courseselect);
1543 // update cached global COURSE too ;-)
1544 if ($courseid == $COURSE->id
) {
1545 $COURSE->modinfo
= null;
1547 // reset the fast modinfo cache
1549 get_fast_modinfo($reset);
1554 $select = "id = '$courseid'";
1557 @set_time_limit
(0); // this could take a while! MDL-10954
1560 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1561 while($course = rs_fetch_next_record($rs)) {
1562 $modinfo = serialize(get_array_of_activities($course->id
));
1563 if (!set_field("course", "modinfo", $modinfo, "id", $course->id
)) {
1564 notify("Could not cache module information for course '" . format_string($course->fullname
) . "'!");
1566 // update cached global COURSE too ;-)
1567 if ($course->id
== $COURSE->id
) {
1568 $COURSE->modinfo
= $modinfo;
1573 // reset the fast modinfo cache
1575 get_fast_modinfo($reset);
1578 function get_child_categories($parent) {
1579 /// Returns an array of the children categories for the given category
1580 /// ID by caching all of the categories in a static hash
1582 static $allcategories = null;
1584 // only fill in this variable the first time
1585 if (null == $allcategories) {
1586 $allcategories = array();
1588 $categories = get_categories();
1589 foreach ($categories as $category) {
1590 if (empty($allcategories[$category->parent
])) {
1591 $allcategories[$category->parent
] = array();
1593 $allcategories[$category->parent
][] = $category;
1597 if (empty($allcategories[$parent])) {
1600 return $allcategories[$parent];
1605 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1606 /// Given an empty array, this function recursively travels the
1607 /// categories, building up a nice list for display. It also makes
1608 /// an array that list all the parents for each category.
1610 // initialize the arrays if needed
1611 if (!is_array($list)) {
1614 if (!is_array($parents)) {
1620 $path = $path.' / '.format_string($category->name
);
1622 $path = format_string($category->name
);
1624 $list[$category->id
] = $path;
1629 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
1630 foreach ($categories as $cat) {
1631 if (!empty($category->id
)) {
1632 if (isset($parents[$category->id
])) {
1633 $parents[$cat->id
] = $parents[$category->id
];
1635 $parents[$cat->id
][] = $category->id
;
1637 make_categories_list($list, $parents, $cat, $path);
1643 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1644 /// Recursive function to print out all the categories in a nice format
1645 /// with or without courses included
1648 if (isset($CFG->max_category_depth
) && ($depth >= $CFG->max_category_depth
)) {
1652 if (!$displaylist) {
1653 make_categories_list($displaylist, $parentslist);
1657 if ($category->visible
or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
))) {
1658 print_category_info($category, $depth, $files);
1660 return; // Don't bother printing children of invisible categories
1664 $category->id
= "0";
1667 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
1668 $countcats = count($categories);
1672 foreach ($categories as $cat) {
1674 if ($count == $countcats) {
1677 $up = $first ?
false : true;
1678 $down = $last ?
false : true;
1681 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $files);
1686 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1688 function make_categories_options() {
1689 make_categories_list($cats,$parents);
1690 foreach ($cats as $key => $value) {
1691 if (array_key_exists($key,$parents)) {
1692 if ($indent = count($parents[$key])) {
1693 for ($i = 0; $i < $indent; $i++
) {
1694 $cats[$key] = ' '.$cats[$key];
1702 function print_category_info($category, $depth, $files = false) {
1703 /// Prints the category info in indented fashion
1704 /// This function is only used by print_whole_category_list() above
1707 static $strallowguests, $strrequireskey, $strsummary;
1709 if (empty($strsummary)) {
1710 $strallowguests = get_string('allowguests');
1711 $strrequireskey = get_string('requireskey');
1712 $strsummary = get_string('summary');
1715 $catlinkcss = $category->visible ?
'' : ' class="dimmed" ';
1717 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT
;
1718 if ($files and $coursecount) {
1719 $catimage = '<img src="'.$CFG->pixpath
.'/i/course.gif" alt="" />';
1721 $catimage = " ";
1724 echo "\n\n".'<table class="categorylist">';
1726 $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');
1727 if ($files and $coursecount) {
1732 $indent = $depth*30;
1733 $rows = count($courses) +
1;
1734 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1735 print_spacer(10, $indent);
1739 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1740 echo '<td valign="top" class="category name">';
1741 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1743 echo '<td class="category info"> </td>';
1746 if ($courses && !(isset($CFG->max_category_depth
)&&($depth>=$CFG->max_category_depth
-1))) {
1747 foreach ($courses as $course) {
1748 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1749 echo '<tr><td valign="top"> ';
1750 echo '</td><td valign="top" class="course name">';
1751 echo '<a '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>';
1752 echo '</td><td align="right" valign="top" class="course info">';
1753 if ($course->guest
) {
1754 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1755 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath
.'/i/guest.gif" /></a>';
1757 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1759 if ($course->password
) {
1760 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1761 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath
.'/i/key.gif" /></a>';
1763 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1765 if ($course->summary
) {
1766 link_to_popup_window ('/course/info.php?id='.$course->id
, 'courseinfo',
1767 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath
.'/i/info.gif" />',
1768 400, 500, $strsummary);
1770 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1780 $indent = $depth*20;
1781 echo '<td valign="top" width="'.$indent.'">';
1782 print_spacer(10, $indent);
1786 echo '<td valign="top" class="category name">';
1787 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1789 echo '<td valign="top" class="category number">';
1790 if (count($courses)) {
1791 echo count($courses);
1800 function print_courses($category) {
1801 /// Category is 0 (for all courses) or an object
1805 if (!is_object($category) && $category==0) {
1806 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1807 if (is_array($categories) && count($categories) == 1) {
1808 $category = array_shift($categories);
1809 $courses = get_courses_wmanagers($category->id
,
1811 array('password','summary','currency'));
1813 $courses = get_courses_wmanagers('all',
1815 array('password','summary','currency'));
1819 $courses = get_courses_wmanagers($category->id
,
1821 array('password','summary','currency'));
1825 echo '<ul class="unlist">';
1826 foreach ($courses as $course) {
1827 if ($course->visible
== 1
1828 ||
has_capability('moodle/course:viewhiddencourses',$course->context
)) {
1830 print_course($course);
1836 print_heading(get_string("nocoursesyet"));
1837 $context = get_context_instance(CONTEXT_SYSTEM
);
1838 if (has_capability('moodle/course:create', $context)) {
1840 $options['category'] = $category->id
;
1841 echo '<div class="addcoursebutton">';
1842 print_single_button($CFG->wwwroot
.'/course/edit.php', $options, get_string("addnewcourse"));
1852 function print_course($course) {
1856 if (isset($course->context
)) {
1857 $context = $course->context
;
1859 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1862 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1864 echo '<div class="coursebox clearfix">';
1865 echo '<div class="info">';
1866 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1867 $linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'.
1868 format_string($course->fullname
).'</a></div>';
1870 /// first find all roles that are supposed to be displayed
1872 if (!empty($CFG->coursemanager
)) {
1873 $managerroles = split(',', $CFG->coursemanager
);
1874 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
1875 $namesarray = array();
1876 if (isset($course->managers
)) {
1877 if (count($course->managers
)) {
1878 $rusers = $course->managers
;
1879 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1881 /// Rename some of the role names if needed
1882 if (isset($context)) {
1883 $aliasnames = get_records('role_names', 'contextid', $context->id
,'','roleid,contextid,name');
1886 // keep a note of users displayed to eliminate duplicates
1887 $usersshown = array();
1888 foreach ($rusers as $ra) {
1890 // if we've already displayed user don't again
1891 if (in_array($ra->user
->id
,$usersshown)) {
1894 $usersshown[] = $ra->user
->id
;
1896 if ($ra->hidden
== 0 ||
$canseehidden) {
1897 $fullname = fullname($ra->user
, $canviewfullnames);
1898 if ($ra->hidden
== 1) {
1899 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
1904 if (isset($aliasnames[$ra->roleid
])) {
1905 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
1908 $namesarray[] = format_string($ra->rolename
)
1909 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$ra->user
->id
.'&course='.SITEID
.'">'
1910 . $fullname . '</a>' . $status;
1915 $rusers = get_role_users($managerroles, $context,
1916 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1917 if (is_array($rusers) && count($rusers)) {
1918 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1919 foreach ($rusers as $teacher) {
1920 $fullname = fullname($teacher, $canviewfullnames);
1921 $namesarray[] = format_string($teacher->rolename
)
1922 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$teacher->id
.'&course='.SITEID
.'">'
1923 . $fullname . '</a>';
1928 if (!empty($namesarray)) {
1929 echo "<ul class=\"teachers\">\n<li>";
1930 echo implode('</li><li>', $namesarray);
1935 require_once("$CFG->dirroot/enrol/enrol.class.php");
1936 $enrol = enrolment_factory
::factory($course->enrol
);
1937 echo $enrol->get_access_icons($course);
1939 echo '</div><div class="summary">';
1941 $options->noclean
= true;
1942 $options->para
= false;
1943 echo format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
);
1949 function print_my_moodle() {
1950 /// Prints custom user information on the home page.
1951 /// Over time this can include all sorts of information
1955 if (empty($USER->id
)) {
1956 error("It shouldn't be possible to see My Moodle without being logged in.");
1959 $courses = get_my_courses($USER->id
, 'visible DESC,sortorder ASC', array('summary'));
1961 $rcourses = array();
1962 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
1963 $rcourses = get_my_remotecourses($USER->id
);
1964 $rhosts = get_my_remotehosts();
1967 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
1969 if (!empty($courses)) {
1970 echo '<ul class="unlist">';
1971 foreach ($courses as $course) {
1972 if ($course->id
== SITEID
) {
1976 print_course($course, "100%");
1983 if (!empty($rcourses)) {
1984 // at the IDP, we know of all the remote courses
1985 foreach ($rcourses as $course) {
1986 print_remote_course($course, "100%");
1988 } elseif (!empty($rhosts)) {
1989 // non-IDP, we know of all the remote servers, but not courses
1990 foreach ($rhosts as $host) {
1991 print_remote_host($host, "100%");
1997 if (count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
1998 echo "<table width=\"100%\"><tr><td align=\"center\">";
1999 print_course_search("", false, "short");
2000 echo "</td><td align=\"center\">";
2001 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2002 echo "</td></tr></table>\n";
2006 if (count_records("course_categories") > 1) {
2007 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
2008 print_whole_category_list();
2009 print_simple_box_end();
2017 function print_course_search($value="", $return=false, $format="plain") {
2024 $id = 'coursesearch';
2030 $strsearchcourses= get_string("searchcourses");
2032 if ($format == 'plain') {
2033 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2034 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2035 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2036 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
2037 $output .= '<input type="submit" value="'.get_string('go').'" />';
2038 $output .= '</fieldset></form>';
2039 } else if ($format == 'short') {
2040 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2041 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2042 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2043 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2044 $output .= '<input type="submit" value="'.get_string('go').'" />';
2045 $output .= '</fieldset></form>';
2046 } else if ($format == 'navbar') {
2047 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2048 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2049 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2050 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2051 $output .= '<input type="submit" value="'.get_string('go').'" />';
2052 $output .= '</fieldset></form>';
2061 function print_remote_course($course, $width="100%") {
2067 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2069 echo '<div class="coursebox remotecoursebox clearfix">';
2070 echo '<div class="info">';
2071 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2072 $linkcss.' href="'.$url.'">'
2073 . format_string($course->fullname
) .'</a><br />'
2074 . format_string($course->hostname
) . ' : '
2075 . format_string($course->cat_name
) . ' : '
2076 . format_string($course->shortname
). '</div>';
2077 echo '</div><div class="summary">';
2079 $options->noclean
= true;
2080 $options->para
= false;
2081 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
2086 function print_remote_host($host, $width="100%") {
2092 echo '<div class="coursebox clearfix">';
2093 echo '<div class="info">';
2094 echo '<div class="name">';
2095 echo '<img src="'.$CFG->pixpath
.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2096 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2097 . s($host['name']).'</a> - ';
2098 echo $host['count'] . ' ' . get_string('courses');
2105 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2107 function add_course_module($mod) {
2109 $mod->added
= time();
2112 return insert_record("course_modules", $mod);
2116 * Returns course section - creates new if does not exist yet.
2117 * @param int $relative section number
2118 * @param int $courseid
2119 * @return object $course_section object
2121 function get_course_section($section, $courseid) {
2122 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2126 $cw->course
= $courseid;
2127 $cw->section
= $section;
2130 $id = insert_record("course_sections", $cw);
2131 return get_record("course_sections", "id", $id);
2134 * Given a full mod object with section and course already defined, adds this module to that section.
2136 * @param object $mod
2137 * @param int $beforemod An existing ID which we will insert the new module before
2138 * @return int The course_sections ID where the mod is inserted
2140 function add_mod_to_section($mod, $beforemod=NULL) {
2142 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2144 $section->sequence
= trim($section->sequence
);
2146 if (empty($section->sequence
)) {
2147 $newsequence = "$mod->coursemodule";
2149 } else if ($beforemod) {
2150 $modarray = explode(",", $section->sequence
);
2152 if ($key = array_keys ($modarray, $beforemod->id
)) {
2153 $insertarray = array($mod->id
, $beforemod->id
);
2154 array_splice($modarray, $key[0], 1, $insertarray);
2155 $newsequence = implode(",", $modarray);
2157 } else { // Just tack it on the end anyway
2158 $newsequence = "$section->sequence,$mod->coursemodule";
2162 $newsequence = "$section->sequence,$mod->coursemodule";
2165 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id
)) {
2166 return $section->id
; // Return course_sections ID that was used.
2171 } else { // Insert a new record
2172 $section->course
= $mod->course
;
2173 $section->section
= $mod->section
;
2174 $section->summary
= "";
2175 $section->sequence
= $mod->coursemodule
;
2176 return insert_record("course_sections", $section);
2180 function set_coursemodule_groupmode($id, $groupmode) {
2181 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2184 function set_coursemodule_groupingid($id, $groupingid) {
2185 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2188 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2189 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2192 function set_coursemodule_idnumber($id, $idnumber) {
2193 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2196 * $prevstateoverrides = true will set the visibility of the course module
2197 * to what is defined in visibleold. This enables us to remember the current
2198 * visibility when making a whole section hidden, so that when we toggle
2199 * that section back to visible, we are able to return the visibility of
2200 * the course module back to what it was originally.
2202 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2203 if (!$cm = get_record('course_modules', 'id', $id)) {
2206 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2209 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2210 foreach($events as $event) {
2218 if ($prevstateoverrides) {
2219 if ($visible == '0') {
2220 // Remember the current visible state so we can toggle this back.
2221 set_field('course_modules', 'visibleold', $cm->visible
, 'id', $id);
2223 // Get the previous saved visible states.
2224 return set_field('course_modules', 'visible', $cm->visibleold
, 'id', $id);
2227 return set_field("course_modules", "visible", $visible, "id", $id);
2231 * Delete a course module and any associated data at the course level (events)
2232 * Until 1.5 this function simply marked a deleted flag ... now it
2233 * deletes it completely.
2236 function delete_course_module($id) {
2238 require_once($CFG->libdir
.'/gradelib.php');
2240 if (!$cm = get_record('course_modules', 'id', $id)) {
2243 $modulename = get_field('modules', 'name', 'id', $cm->module
);
2244 //delete events from calendar
2245 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2246 foreach($events as $event) {
2247 delete_event($event->id
);
2250 //delete grade items, outcome items and grades attached to modules
2251 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2252 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2253 foreach ($grade_items as $grade_item) {
2254 $grade_item->delete('moddelete');
2258 return delete_records('course_modules', 'id', $cm->id
);
2261 function delete_mod_from_section($mod, $section) {
2263 if ($section = get_record("course_sections", "id", "$section") ) {
2265 $modarray = explode(",", $section->sequence
);
2267 if ($key = array_keys ($modarray, $mod)) {
2268 array_splice($modarray, $key[0], 1);
2269 $newsequence = implode(",", $modarray);
2270 return set_field("course_sections", "sequence", $newsequence, "id", $section->id
);
2279 function move_section($course, $section, $move) {
2280 /// Moves a whole course section up and down within the course
2287 $sectiondest = $section +
$move;
2289 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2293 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2297 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2301 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2304 if (!set_field("course_sections", "section", $section, "id", $sectiondestrecord->id
)) {
2307 // if the focus is on the section that is being moved, then move the focus along
2308 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2309 course_set_display($course->id
, $sectiondest);
2312 // Check for duplicates and fix order if needed.
2313 // There is a very rare case that some sections in the same course have the same section id.
2314 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2316 foreach ($sections as $section) {
2317 if ($section->section
!= $n) {
2318 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
2328 function moveto_module($mod, $section, $beforemod=NULL) {
2329 /// All parameters are objects
2330 /// Move the module object $mod to the specified $section
2331 /// If $beforemod exists then that is the module
2332 /// before which $modid should be inserted
2334 /// Remove original module from original section
2336 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2337 notify("Could not delete module from existing section");
2340 /// Update module itself if necessary
2342 if ($mod->section
!= $section->id
) {
2343 $mod->section
= $section->id
;
2344 if (!update_record("course_modules", $mod)) {
2347 // if moving to a hidden section then hide module
2348 if (!$section->visible
) {
2349 set_coursemodule_visible($mod->id
, 0);
2353 /// Add the module into the new section
2355 $mod->course
= $section->course
;
2356 $mod->section
= $section->section
; // need relative reference
2357 $mod->coursemodule
= $mod->id
;
2359 if (! add_mod_to_section($mod, $beforemod)) {
2367 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2373 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
2374 // no permission to edit
2375 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2380 $str->delete
= get_string("delete");
2381 $str->move
= get_string("move");
2382 $str->moveup
= get_string("moveup");
2383 $str->movedown
= get_string("movedown");
2384 $str->moveright
= get_string("moveright");
2385 $str->moveleft
= get_string("moveleft");
2386 $str->update
= get_string("update");
2387 $str->duplicate
= get_string("duplicate");
2388 $str->hide
= get_string("hide");
2389 $str->show
= get_string("show");
2390 $str->clicktochange
= get_string("clicktochange");
2391 $str->forcedmode
= get_string("forcedmode");
2392 $str->groupsnone
= get_string("groupsnone");
2393 $str->groupsseparate
= get_string("groupsseparate");
2394 $str->groupsvisible
= get_string("groupsvisible");
2395 $sesskey = sesskey();
2398 if ($section >= 0) {
2399 $section = '&sr='.$section; // Section return
2405 $path = $CFG->wwwroot
.'/course';
2410 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2411 if ($mod->visible
) {
2412 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2413 '&sesskey='.$sesskey.$section.'"><img'.
2414 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2415 ' alt="'.$str->hide
.'" /></a>'."\n";
2417 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2418 '&sesskey='.$sesskey.$section.'"><img'.
2419 ' src="'.$CFG->pixpath
.'/t/show.gif" class="iconsmall" '.
2420 ' alt="'.$str->show
.'" /></a>'."\n";
2426 if ($mod->groupmode
!== false) {
2427 if ($mod->groupmode
== SEPARATEGROUPS
) {
2428 $grouptitle = $str->groupsseparate
;
2429 $groupclass = 'editing_groupsseparate';
2430 $groupimage = $CFG->pixpath
.'/t/groups.gif';
2431 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
2432 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
2433 $grouptitle = $str->groupsvisible
;
2434 $groupclass = 'editing_groupsvisible';
2435 $groupimage = $CFG->pixpath
.'/t/groupv.gif';
2436 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
2438 $grouptitle = $str->groupsnone
;
2439 $groupclass = 'editing_groupsnone';
2440 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2441 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
2443 if ($mod->groupmodelink
) {
2444 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
2445 '<img src="'.$groupimage.'" class="iconsmall" '.
2446 'alt="'.$grouptitle.'" /></a>';
2448 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2449 ' src="'.$groupimage.'" class="iconsmall" '.
2450 'alt="'.$grouptitle.'" />';
2456 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2458 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2459 '&sesskey='.$sesskey.$section.'"><img'.
2460 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2461 ' alt="'.$str->move
.'" /></a>'."\n";
2463 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2464 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
2465 ' src="'.$CFG->pixpath
.'/t/up.gif" class="iconsmall" '.
2466 ' alt="'.$str->moveup
.'" /></a>'."\n".
2467 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2468 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2469 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2470 ' alt="'.$str->movedown
.'" /></a>'."\n";
2477 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2479 if (right_to_left()) { // Exchange arrows on RTL
2480 $rightarrow = 'left.gif';
2481 $leftarrow = 'right.gif';
2483 $rightarrow = 'right.gif';
2484 $leftarrow = 'left.gif';
2488 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2489 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2490 ' src="'.$CFG->pixpath
.'/t/'.$leftarrow.'" class="iconsmall" '.
2491 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2494 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2495 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
2496 ' src="'.$CFG->pixpath
.'/t/'.$rightarrow.'" class="iconsmall" '.
2497 ' alt="'.$str->moveright
.'" /></a>'."\n";
2501 return '<span class="commands">'."\n".$leftright.$move.
2502 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
2503 '&sesskey='.$sesskey.$section.'"><img'.
2504 ' src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" '.
2505 ' alt="'.$str->update
.'" /></a>'."\n".
2506 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
2507 '&sesskey='.$sesskey.$section.'"><img'.
2508 ' src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" '.
2509 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2513 * given a course object with shortname & fullname, this function will
2514 * truncate the the number of chars allowed and add ... if it was too long
2516 function course_format_name ($course,$max=100) {
2518 $str = $course->shortname
.': '. $course->fullname
;
2519 if (strlen($str) <= $max) {
2523 return substr($str,0,$max-3).'...';
2528 * This function will return true if the given course is a child course at all
2530 function course_in_meta ($course) {
2531 return record_exists("course_meta","child_course",$course->id
);
2536 * Print standard form elements on module setup forms in mod/.../mod.html
2538 function print_standard_coursemodule_settings($form, $features=null) {
2539 if (! $course = get_record('course', 'id', $form->course
)) {
2540 error("This course doesn't exist");
2542 print_groupmode_setting($form, $course);
2543 if (!empty($features->groupings
)) {
2544 print_grouping_settings($form, $course);
2546 print_visible_setting($form, $course);
2550 * Print groupmode form element on module setup forms in mod/.../mod.html
2552 function print_groupmode_setting($form, $course=NULL) {
2554 if (empty($course)) {
2555 if (! $course = get_record('course', 'id', $form->course
)) {
2556 error("This course doesn't exist");
2559 if ($form->coursemodule
) {
2560 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2561 error("This course module doesn't exist");
2563 $groupmode = groups_get_activity_groupmode($cm);
2566 $groupmode = groups_get_course_groupmode($course);
2568 if ($course->groupmode
or (!$course->groupmodeforce
)) {
2569 echo '<tr valign="top">';
2570 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2571 echo '<td align="left">';
2573 $choices[NOGROUPS
] = get_string('groupsnone');
2574 $choices[SEPARATEGROUPS
] = get_string('groupsseparate');
2575 $choices[VISIBLEGROUPS
] = get_string('groupsvisible');
2576 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce
);
2577 helpbutton('groupmode', get_string('groupmode'));
2583 * Print groupmode form element on module setup forms in mod/.../mod.html
2585 function print_grouping_settings($form, $course=NULL) {
2587 if (empty($course)) {
2588 if (! $course = get_record('course', 'id', $form->course
)) {
2589 error("This course doesn't exist");
2592 if ($form->coursemodule
) {
2593 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2594 error("This course module doesn't exist");
2600 $groupings = get_records_menu('groupings', 'courseid', $course->id
, 'name', 'id, name');
2601 if (!empty($groupings)) {
2602 echo '<tr valign="top">';
2603 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2604 echo '<td align="left">';
2607 $groupingid = isset($cm->groupingid
) ?
$cm->groupingid
: 0;
2609 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2612 $checked = empty($cm->groupmembersonly
) ?
'':'checked="checked"';
2613 echo '<tr valign="top">';
2614 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2615 echo '<td align="left">';
2616 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2623 * Print visibility setting form element on module setup forms in mod/.../mod.html
2625 function print_visible_setting($form, $course=NULL) {
2626 if (empty($course)) {
2627 if (! $course = get_record('course', 'id', $form->course
)) {
2628 error("This course doesn't exist");
2631 if ($form->coursemodule
) {
2632 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule
);
2637 if ($form->mode
== 'add') { // in this case $form->section is the section number, not the id
2638 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section
, 'course', $form->course
);
2640 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2642 if ($hiddensection) {
2646 echo '<tr valign="top">';
2647 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2648 echo '<td align="left">';
2649 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
2650 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2654 function update_restricted_mods($course,$mods) {
2656 /// Delete all the current restricted list
2657 delete_records('course_allowed_modules','course',$course->id
);
2659 if (empty($course->restrictmodules
)) {
2660 return; // We're done
2663 /// Insert the new list of restricted mods
2664 foreach ($mods as $mod) {
2666 continue; // this is the 'allow none' option
2669 $am->course
= $course->id
;
2671 insert_record('course_allowed_modules',$am);
2676 * This function will take an int (module id) or a string (module name)
2677 * and return true or false, whether it's allowed in the given course (object)
2678 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2679 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2682 function course_allowed_module($course,$mod) {
2684 if (empty($course->restrictmodules
)) {
2688 // Admins and admin-like people who can edit everything can also add anything.
2689 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
2690 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
))) {
2694 if (is_numeric($mod)) {
2696 } else if (is_string($mod)) {
2697 $modid = get_field('modules','id','name',$mod);
2699 if (empty($modid)) {
2703 return (record_exists('course_allowed_modules','course',$course->id
,'module',$modid));
2707 * Recursively delete category including all subcategories and courses.
2708 * @param object $ccategory
2709 * @return bool status
2711 function category_delete_full($category, $showfeedback=true) {
2713 require_once($CFG->libdir
.'/gradelib.php');
2714 require_once($CFG->libdir
.'/questionlib.php');
2716 if ($children = get_records('course_categories', 'parent', $category->id
, 'sortorder ASC')) {
2717 foreach ($children as $childcat) {
2718 if (!category_delete_full($childcat, $showfeedback)) {
2719 notify("Error deleting category $childcat->name");
2725 if ($courses = get_records('course', 'category', $category->id
, 'sortorder ASC')) {
2726 foreach ($courses as $course) {
2727 if (!delete_course($course->id
, false)) {
2728 notify("Error deleting course $course->shortname");
2731 notify(get_string('coursedeleted', '', $course->shortname
), 'notifysuccess');
2735 // now delete anything that may depend on course category context
2736 grade_course_category_delete($category->id
, 0, $showfeedback);
2737 if (!question_delete_course_category($category, 0, $showfeedback)) {
2738 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2742 // finally delete the category and it's context
2743 delete_records('course_categories', 'id', $category->id
);
2744 delete_context(CONTEXT_COURSECAT
, $category->id
);
2746 events_trigger('category_deleted', $category);
2748 notify(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
2754 * Delete category, but move contents to another category.
2755 * @param object $ccategory
2756 * @param int $newparentid category id
2757 * @return bool status
2759 function category_delete_move($category, $newparentid, $showfeedback=true) {
2761 require_once($CFG->libdir
.'/gradelib.php');
2762 require_once($CFG->libdir
.'/questionlib.php');
2764 if (!$newparentcat = get_record('course_categories', 'id', $newparentid)) {
2768 if ($children = get_records('course_categories', 'parent', $category->id
, 'sortorder ASC')) {
2769 foreach ($children as $childcat) {
2770 if (!move_category($childcat, $newparentcat)) {
2771 notify("Error moving category $childcat->name");
2777 if ($courses = get_records('course', 'category', $category->id
, 'sortorder ASC', 'id')) {
2778 if (!move_courses(array_keys($courses), $newparentid)) {
2779 notify("Error moving courses");
2782 notify(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
2785 // now delete anything that may depend on course category context
2786 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
2787 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
2788 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2792 // finally delete the category and it's context
2793 delete_records('course_categories', 'id', $category->id
);
2794 delete_context(CONTEXT_COURSECAT
, $category->id
);
2796 events_trigger('category_deleted', $category);
2798 notify(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
2804 *** Efficiently moves many courses around while maintaining
2805 *** sortorder in order.
2807 *** $courseids is an array of course ids
2811 function move_courses ($courseids, $categoryid) {
2815 if (!empty($courseids)) {
2817 $courseids = array_reverse($courseids);
2819 foreach ($courseids as $courseid) {
2821 if (! $course = get_record("course", "id", $courseid)) {
2822 notify("Error finding course $courseid");
2824 // figure out a sortorder that we can use in the destination category
2825 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2826 FROM ' . $CFG->prefix
. 'course WHERE category=' . $categoryid);
2827 if (is_null($sortorder) ||
$sortorder === false) {
2828 // the category is empty
2829 // rather than let the db default to 0
2830 // set it to > 100 and avoid extra work in fix_coursesortorder()
2832 } else if ($sortorder < 10) {
2833 fix_course_sortorder($categoryid);
2836 $course->category
= $categoryid;
2837 $course->sortorder
= $sortorder;
2838 $course->fullname
= addslashes($course->fullname
);
2839 $course->shortname
= addslashes($course->shortname
);
2840 $course->summary
= addslashes($course->summary
);
2841 $course->password
= addslashes($course->password
);
2842 $course->teacher
= addslashes($course->teacher
);
2843 $course->teachers
= addslashes($course->teachers
);
2844 $course->student
= addslashes($course->student
);
2845 $course->students
= addslashes($course->students
);
2847 if (!update_record('course', $course)) {
2848 notify("An error occurred - course not moved!");
2851 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2852 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
2853 context_moved($context, $newparent);
2856 fix_course_sortorder();
2862 *** Efficiently moves a category - NOTE that this can have
2863 *** a huge impact access-control-wise...
2867 function move_category ($category, $newparentcat) {
2871 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
2873 if (empty($newparentcat->id
)) {
2874 if (!set_field('course_categories', 'parent', 0, 'id', $category->id
)) {
2877 $newparent = get_context_instance(CONTEXT_SYSTEM
);
2879 if (!set_field('course_categories', 'parent', $newparentcat->id
, 'id', $category->id
)) {
2882 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
2885 context_moved($context, $newparent);
2887 // The most effective thing would be to find the common parent,
2888 // until then, do it sitewide...
2889 fix_course_sortorder();
2896 * @param string $format Course format ID e.g. 'weeks'
2897 * @return Name that the course format prefers for sections
2899 function get_section_name($format) {
2900 $sectionname = get_string("name$format","format_$format");
2901 if($sectionname == "[[name$format]]") {
2902 $sectionname = get_string("name$format");
2904 return $sectionname;
2908 * Can the current user delete this course?
2909 * @param int $courseid
2912 * Exception here to fix MDL-7796.
2915 * Course creators who can manage activities in the course
2916 * shoule be allowed to delete the course. We do it this
2917 * way because we need a quick fix to bring the functionality
2918 * in line with what we had pre-roles. We can't give the
2919 * default course creator role moodle/course:delete at
2920 * CONTEXT_SYSTEM level because this will allow them to
2921 * delete any course in the site. So we hard code this here
2924 * @author vyshane AT gmail.com
2926 function can_delete_course($courseid) {
2928 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
2930 return ( has_capability('moodle/course:delete', $context)
2931 ||
(has_capability('moodle/legacy:coursecreator', $context)
2932 && has_capability('moodle/course:manageactivities', $context)) );
2937 * Create a course and either return a $course object or false
2939 * @param object $data - all the data needed for an entry in the 'course' table
2941 function create_course($data) {
2944 // preprocess allowed mods
2945 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2946 unset($data->allowedmods
);
2947 if ($CFG->restrictmodulesfor
== 'all') {
2948 $data->restrictmodules
= 1;
2950 $data->restrictmodules
= 0;
2953 $data->timecreated
= time();
2955 // place at beginning of category
2956 fix_course_sortorder();
2957 $data->sortorder
= get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
2958 if (empty($data->sortorder
)) {
2959 $data->sortorder
= 100;
2962 if ($newcourseid = insert_record('course', $data)) { // Set up new course
2964 $course = get_record('course', 'id', $newcourseid);
2967 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
2968 blocks_repopulate_page($page); // Return value not checked because you can always edit later
2970 update_restricted_mods($course, $allowedmods);
2972 $section = new object();
2973 $section->course
= $course->id
; // Create a default section.
2974 $section->section
= 0;
2975 $section->id
= insert_record('course_sections', $section);
2977 fix_course_sortorder();
2979 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
2984 return false; // error
2989 * Update a course and return true or false
2991 * @param object $data - all the data needed for an entry in the 'course' table
2993 function update_course($data) {
2996 // Preprocess allowed mods
2997 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
2998 unset($data->allowedmods
);
3000 // Normal teachers can't change setting
3001 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3002 unset($data->restrictmodules
);
3006 $oldcourse = get_record('course', 'id', $data->id
); // should not fail, already tested above
3007 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $oldcourse->category
))
3008 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $data->category
))) {
3009 // can not move to new category, keep the old one
3010 unset($data->category
);
3011 } elseif ($oldcourse->category
!= $data->category
) {
3015 // Update with the new data
3016 if (update_record('course', $data)) {
3018 $course = get_record('course', 'id', $data->id
);
3020 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3022 // "Admins" can change allowed mods for a course
3023 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3024 update_restricted_mods($course, $allowedmods);
3028 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3029 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3030 context_moved($context, $newparent);
3033 fix_course_sortorder();
3035 // Test for and remove blocks which aren't appropriate anymore
3036 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
3037 blocks_remove_inappropriate($page);
3039 // put custom role names into db
3040 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3042 foreach ($data as $dname => $dvalue) {
3044 // is this the right param?
3045 $dvalue = clean_param($dvalue, PARAM_NOTAGS
);
3047 if (!strstr($dname, 'role_')) {
3051 $dt = explode('_', $dname);
3053 // make up our mind whether we want to delete, update or insert
3055 if (empty($dvalue)) {
3057 delete_records('role_names', 'contextid', $context->id
, 'roleid', $roleid);
3059 } else if ($t = get_record('role_names', 'contextid', $context->id
, 'roleid', $roleid)) {
3062 update_record('role_names', $t);
3066 $t->contextid
= $context->id
;
3067 $t->roleid
= $roleid;
3069 insert_record('role_names', $t);