3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') ||
die;
29 require_once($CFG->libdir
.'/completionlib.php');
30 require_once($CFG->libdir
.'/filelib.php');
32 define('COURSE_MAX_LOG_DISPLAY', 150); // days
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
36 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
37 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
38 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
39 define('FRONTPAGENEWS', '0');
40 define('FRONTPAGECOURSELIST', '1');
41 define('FRONTPAGECATEGORYNAMES', '2');
42 define('FRONTPAGETOPICONLY', '3');
43 define('FRONTPAGECATEGORYCOMBO', '4');
44 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
45 define('EXCELROWS', 65535);
46 define('FIRSTUSEDEXCELROW', 3);
48 define('MOD_CLASS_ACTIVITY', 0);
49 define('MOD_CLASS_RESOURCE', 1);
51 function make_log_url($module, $url) {
60 if (strpos($url, '../') === 0) {
61 $url = ltrim($url, '.');
63 $url = "/course/$url";
68 $url = "/$module/$url";
81 $url = "/message/$url";
93 $url = "/mod/$module/$url";
97 //now let's sanitise urls - there might be some ugly nasties:-(
98 $parts = explode('?', $url);
99 $script = array_shift($parts);
100 if (strpos($script, 'http') === 0) {
101 $script = clean_param($script, PARAM_URL
);
103 $script = clean_param($script, PARAM_PATH
);
108 $query = implode('', $parts);
109 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
110 $parts = explode('&', $query);
111 $eq = urlencode('=');
112 foreach ($parts as $key=>$part) {
113 $part = urlencode(urldecode($part));
114 $part = str_replace($eq, '=', $part);
115 $parts[$key] = $part;
117 $query = '?'.implode('&', $parts);
120 return $script.$query;
124 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
125 $modname="", $modid=0, $modaction="", $groupid=0) {
128 // It is assumed that $date is the GMT time of midnight for that day,
129 // and so the next 86400 seconds worth of logs are printed.
131 /// Setup for group handling.
133 // TODO: I don't understand group/context/etc. enough to be able to do
134 // something interesting with it here
135 // What is the context of a remote course?
137 /// If the group mode is separate, and this user does not have editing privileges,
138 /// then only the user's group can be viewed.
139 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
140 // $groupid = get_current_group($course->id);
142 /// If this course doesn't have groups, no groupid can be specified.
143 //else if (!$course->groupmode) {
151 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
153 LEFT JOIN {user} u ON l.userid = u.id
157 $where .= "l.hostid = :hostid";
158 $params['hostid'] = $hostid;
160 // TODO: Is 1 really a magic number referring to the sitename?
161 if ($course != SITEID ||
$modid != 0) {
162 $where .= " AND l.course=:courseid";
163 $params['courseid'] = $course;
167 $where .= " AND l.module = :modname";
168 $params['modname'] = $modname;
171 if ('site_errors' === $modid) {
172 $where .= " AND ( l.action='error' OR l.action='infected' )";
174 //TODO: This assumes that modids are the same across sites... probably
176 $where .= " AND l.cmid = :modid";
177 $params['modid'] = $modid;
181 $firstletter = substr($modaction, 0, 1);
182 if ($firstletter == '-') {
183 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
184 $params['modaction'] = '%'.substr($modaction, 1).'%';
186 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
187 $params['modaction'] = '%'.$modaction.'%';
192 $where .= " AND l.userid = :user";
193 $params['user'] = $user;
197 $enddate = $date +
86400;
198 $where .= " AND l.time > :date AND l.time < :enddate";
199 $params['date'] = $date;
200 $params['enddate'] = $enddate;
204 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
205 if(!empty($result['totalcount'])) {
206 $where .= " ORDER BY $order";
207 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
209 $result['logs'] = array();
214 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
215 $modname="", $modid=0, $modaction="", $groupid=0) {
216 global $DB, $SESSION, $USER;
217 // It is assumed that $date is the GMT time of midnight for that day,
218 // and so the next 86400 seconds worth of logs are printed.
220 /// Setup for group handling.
222 /// If the group mode is separate, and this user does not have editing privileges,
223 /// then only the user's group can be viewed.
224 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
225 if (isset($SESSION->currentgroup
[$course->id
])) {
226 $groupid = $SESSION->currentgroup
[$course->id
];
228 $groupid = groups_get_all_groups($course->id
, $USER->id
);
229 if (is_array($groupid)) {
230 $groupid = array_shift(array_keys($groupid));
231 $SESSION->currentgroup
[$course->id
] = $groupid;
237 /// If this course doesn't have groups, no groupid can be specified.
238 else if (!$course->groupmode
) {
245 if ($course->id
!= SITEID ||
$modid != 0) {
246 $joins[] = "l.course = :courseid";
247 $params['courseid'] = $course->id
;
251 $joins[] = "l.module = :modname";
252 $params['modname'] = $modname;
255 if ('site_errors' === $modid) {
256 $joins[] = "( l.action='error' OR l.action='infected' )";
258 $joins[] = "l.cmid = :modid";
259 $params['modid'] = $modid;
263 $firstletter = substr($modaction, 0, 1);
264 if ($firstletter == '-') {
265 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
266 $params['modaction'] = '%'.substr($modaction, 1).'%';
268 $joins[] = $DB->sql_like('l.action', ':modaction', false);
269 $params['modaction'] = '%'.$modaction.'%';
274 /// Getting all members of a group.
275 if ($groupid and !$user) {
276 if ($gusers = groups_get_members($groupid)) {
277 $gusers = array_keys($gusers);
278 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
280 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
284 $joins[] = "l.userid = :userid";
285 $params['userid'] = $user;
289 $enddate = $date +
86400;
290 $joins[] = "l.time > :date AND l.time < :enddate";
291 $params['date'] = $date;
292 $params['enddate'] = $enddate;
295 $selector = implode(' AND ', $joins);
297 $totalcount = 0; // Initialise
299 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
300 $result['totalcount'] = $totalcount;
305 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
306 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
308 global $CFG, $DB, $OUTPUT;
310 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
311 $modname, $modid, $modaction, $groupid)) {
312 echo $OUTPUT->notification("No logs found!");
313 echo $OUTPUT->footer();
319 if ($course->id
== SITEID
) {
321 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
322 foreach ($ccc as $cc) {
323 $courses[$cc->id
] = $cc->shortname
;
327 $courses[$course->id
] = $course->shortname
;
330 $totalcount = $logs['totalcount'];
333 $tt = getdate(time());
334 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
336 $strftimedatetime = get_string("strftimedatetime");
338 echo "<div class=\"info\">\n";
339 print_string("displayingrecords", "", $totalcount);
342 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
344 $table = new html_table();
345 $table->classes
= array('logtable','generalbox');
346 $table->align
= array('right', 'left', 'left');
347 $table->head
= array(
349 get_string('ip_address'),
350 get_string('fullnameuser'),
351 get_string('action'),
354 $table->data
= array();
356 if ($course->id
== SITEID
) {
357 array_unshift($table->align
, 'left');
358 array_unshift($table->head
, get_string('course'));
361 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
362 if (empty($logs['logs'])) {
363 $logs['logs'] = array();
366 foreach ($logs['logs'] as $log) {
368 if (isset($ldcache[$log->module
][$log->action
])) {
369 $ld = $ldcache[$log->module
][$log->action
];
371 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
372 $ldcache[$log->module
][$log->action
] = $ld;
374 if ($ld && is_numeric($log->info
)) {
375 // ugly hack to make sure fullname is shown correctly
376 if ($ld->mtable
== 'user' && $ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname')) {
377 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
379 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
384 $log->info
= format_string($log->info
);
386 // If $log->url has been trimmed short by the db size restriction
387 // code in add_to_log, keep a note so we don't add a link to a broken url
388 $tl=textlib_get_instance();
389 $brokenurl=($tl->strlen($log->url
)==100 && $tl->substr($log->url
,97)=='...');
392 if ($course->id
== SITEID
) {
393 if (empty($log->course
)) {
394 $row[] = get_string('site');
396 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>";
400 $row[] = userdate($log->time
, '%a').' '.userdate($log->time
, $strftimedatetime);
402 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
403 $row[] = $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
405 $row[] = html_writer
::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
))));
407 $displayaction="$log->module $log->action";
409 $row[] = $displayaction;
411 $link = make_log_url($log->module
,$log->url
);
412 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
415 $table->data
[] = $row;
418 echo html_writer
::table($table);
419 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
423 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
424 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
426 global $CFG, $DB, $OUTPUT;
428 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
429 $modname, $modid, $modaction, $groupid)) {
430 echo $OUTPUT->notification("No logs found!");
431 echo $OUTPUT->footer();
435 if ($course->id
== SITEID
) {
437 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
438 foreach ($ccc as $cc) {
439 $courses[$cc->id
] = $cc->shortname
;
444 $totalcount = $logs['totalcount'];
447 $tt = getdate(time());
448 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
450 $strftimedatetime = get_string("strftimedatetime");
452 echo "<div class=\"info\">\n";
453 print_string("displayingrecords", "", $totalcount);
456 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
458 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
460 if ($course->id
== SITEID
) {
461 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
463 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
464 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
465 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
466 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
467 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
470 if (empty($logs['logs'])) {
476 foreach ($logs['logs'] as $log) {
478 $log->info
= $log->coursename
;
479 $row = ($row +
1) %
2;
481 if (isset($ldcache[$log->module
][$log->action
])) {
482 $ld = $ldcache[$log->module
][$log->action
];
484 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
485 $ldcache[$log->module
][$log->action
] = $ld;
487 if (0 && $ld && !empty($log->info
)) {
488 // ugly hack to make sure fullname is shown correctly
489 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
490 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
492 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
497 $log->info
= format_string($log->info
);
499 echo '<tr class="r'.$row.'">';
500 if ($course->id
== SITEID
) {
501 $courseshortname = format_string($courses[$log->course
], true, array('context' => get_context_instance(CONTEXT_COURSE
, SITEID
)));
502 echo "<td class=\"r$row c0\" >\n";
503 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
506 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
507 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
508 echo "<td class=\"r$row c2\" >\n";
509 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
510 echo $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
512 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
513 echo "<td class=\"r$row c3\" >\n";
514 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
516 echo "<td class=\"r$row c4\">\n";
517 echo $log->action
.': '.$log->module
;
519 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
524 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
528 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
529 $modid, $modaction, $groupid) {
532 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
533 get_string('fullnameuser')."\t".get_string('action')."\t".get_string('info');
535 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
536 $modname, $modid, $modaction, $groupid)) {
542 if ($course->id
== SITEID
) {
544 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
545 foreach ($ccc as $cc) {
546 $courses[$cc->id
] = $cc->shortname
;
550 $courses[$course->id
] = $course->shortname
;
555 $tt = getdate(time());
556 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
558 $strftimedatetime = get_string("strftimedatetime");
560 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
562 header("Content-Type: application/download\n");
563 header("Content-Disposition: attachment; filename=$filename");
564 header("Expires: 0");
565 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
566 header("Pragma: public");
568 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
571 if (empty($logs['logs'])) {
575 foreach ($logs['logs'] as $log) {
576 if (isset($ldcache[$log->module
][$log->action
])) {
577 $ld = $ldcache[$log->module
][$log->action
];
579 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
580 $ldcache[$log->module
][$log->action
] = $ld;
582 if ($ld && !empty($log->info
)) {
583 // ugly hack to make sure fullname is shown correctly
584 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
585 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
587 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
592 $log->info
= format_string($log->info
);
593 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
595 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
596 $firstField = format_string($courses[$log->course
], true, array('context' => $coursecontext));
597 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
598 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
599 $text = implode("\t", $row);
606 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
607 $modid, $modaction, $groupid) {
611 require_once("$CFG->libdir/excellib.class.php");
613 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
614 $modname, $modid, $modaction, $groupid)) {
620 if ($course->id
== SITEID
) {
622 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
623 foreach ($ccc as $cc) {
624 $courses[$cc->id
] = $cc->shortname
;
628 $courses[$course->id
] = $course->shortname
;
633 $tt = getdate(time());
634 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
636 $strftimedatetime = get_string("strftimedatetime");
638 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
639 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
642 $workbook = new MoodleExcelWorkbook('-');
643 $workbook->send($filename);
645 $worksheet = array();
646 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
647 get_string('fullnameuser'), get_string('action'), get_string('info'));
649 // Creating worksheets
650 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
651 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
652 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
653 $worksheet[$wsnumber]->set_column(1, 1, 30);
654 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
655 userdate(time(), $strftimedatetime));
657 foreach ($headers as $item) {
658 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
663 if (empty($logs['logs'])) {
668 $formatDate =& $workbook->add_format();
669 $formatDate->set_num_format(get_string('log_excel_date_format'));
671 $row = FIRSTUSEDEXCELROW
;
673 $myxls =& $worksheet[$wsnumber];
674 foreach ($logs['logs'] as $log) {
675 if (isset($ldcache[$log->module
][$log->action
])) {
676 $ld = $ldcache[$log->module
][$log->action
];
678 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
679 $ldcache[$log->module
][$log->action
] = $ld;
681 if ($ld && !empty($log->info
)) {
682 // ugly hack to make sure fullname is shown correctly
683 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
684 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
686 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
691 $log->info
= format_string($log->info
);
692 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
695 if ($row > EXCELROWS
) {
697 $myxls =& $worksheet[$wsnumber];
698 $row = FIRSTUSEDEXCELROW
;
702 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
704 $myxls->write($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)), '');
705 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
706 $myxls->write($row, 2, $log->ip
, '');
707 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
708 $myxls->write($row, 3, $fullname, '');
709 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
710 $myxls->write($row, 5, $log->info
, '');
719 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
720 $modid, $modaction, $groupid) {
724 require_once("$CFG->libdir/odslib.class.php");
726 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
727 $modname, $modid, $modaction, $groupid)) {
733 if ($course->id
== SITEID
) {
735 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
736 foreach ($ccc as $cc) {
737 $courses[$cc->id
] = $cc->shortname
;
741 $courses[$course->id
] = $course->shortname
;
746 $tt = getdate(time());
747 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
749 $strftimedatetime = get_string("strftimedatetime");
751 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
752 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
755 $workbook = new MoodleODSWorkbook('-');
756 $workbook->send($filename);
758 $worksheet = array();
759 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
760 get_string('fullnameuser'), get_string('action'), get_string('info'));
762 // Creating worksheets
763 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
764 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
765 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
766 $worksheet[$wsnumber]->set_column(1, 1, 30);
767 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
768 userdate(time(), $strftimedatetime));
770 foreach ($headers as $item) {
771 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
776 if (empty($logs['logs'])) {
781 $formatDate =& $workbook->add_format();
782 $formatDate->set_num_format(get_string('log_excel_date_format'));
784 $row = FIRSTUSEDEXCELROW
;
786 $myxls =& $worksheet[$wsnumber];
787 foreach ($logs['logs'] as $log) {
788 if (isset($ldcache[$log->module
][$log->action
])) {
789 $ld = $ldcache[$log->module
][$log->action
];
791 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
792 $ldcache[$log->module
][$log->action
] = $ld;
794 if ($ld && !empty($log->info
)) {
795 // ugly hack to make sure fullname is shown correctly
796 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
797 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
799 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
804 $log->info
= format_string($log->info
);
805 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
808 if ($row > EXCELROWS
) {
810 $myxls =& $worksheet[$wsnumber];
811 $row = FIRSTUSEDEXCELROW
;
815 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
817 $myxls->write_string($row, 0, format_string($courses[$log->course
], true, array('context' => $context)));
818 $myxls->write_date($row, 1, $log->time
);
819 $myxls->write_string($row, 2, $log->ip
);
820 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
821 $myxls->write_string($row, 3, $fullname);
822 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
823 $myxls->write_string($row, 5, $log->info
);
833 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
835 if (empty($CFG->gdversion
)) {
836 echo "(".get_string("gdneed").")";
838 // MDL-10818, do not display broken graph when user has no permission to view graph
839 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE
, $course->id
)) ||
840 ($course->showreports
and $USER->id
== $userid)) {
841 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
842 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
848 function print_overview($courses, array $remote_courses=array()) {
849 global $CFG, $USER, $DB, $OUTPUT;
851 $htmlarray = array();
852 if ($modules = $DB->get_records('modules')) {
853 foreach ($modules as $mod) {
854 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
855 include_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
856 $fname = $mod->name
.'_print_overview';
857 if (function_exists($fname)) {
858 $fname($courses,$htmlarray);
863 foreach ($courses as $course) {
864 $fullname = format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
865 echo $OUTPUT->box_start('coursebox');
866 $attributes = array('title' => s($fullname));
867 if (empty($course->visible
)) {
868 $attributes['class'] = 'dimmed';
870 echo $OUTPUT->heading(html_writer
::link(
871 new moodle_url('/course/view.php', array('id' => $course->id
)), $fullname, $attributes), 3);
872 if (array_key_exists($course->id
,$htmlarray)) {
873 foreach ($htmlarray[$course->id
] as $modname => $html) {
877 echo $OUTPUT->box_end();
880 if (!empty($remote_courses)) {
881 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
883 foreach ($remote_courses as $course) {
884 echo $OUTPUT->box_start('coursebox');
885 $attributes = array('title' => s($course->fullname
));
886 echo $OUTPUT->heading(html_writer
::link(
887 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid
, 'wantsurl' => '/course/view.php?id='.$course->remoteid
)),
888 format_string($course->shortname
),
889 $attributes) . ' (' . format_string($course->hostname
) . ')', 3);
890 echo $OUTPUT->box_end();
896 * This function trawls through the logs looking for
897 * anything new since the user's last login
899 function print_recent_activity($course) {
900 // $course is an object
901 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
903 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
905 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
907 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD
, -2); // better db caching for guests - 100 seconds
909 if (!isguestuser()) {
910 if (!empty($USER->lastcourseaccess
[$course->id
])) {
911 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
912 $timestart = $USER->lastcourseaccess
[$course->id
];
917 echo '<div class="activitydate">';
918 echo get_string('activitysince', '', userdate($timestart));
920 echo '<div class="activityhead">';
922 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
928 /// Firstly, have there been any new enrolments?
930 $users = get_recent_enrolments($course->id
, $timestart);
932 //Accessibility: new users now appear in an <OL> list.
934 echo '<div class="newusers">';
935 echo $OUTPUT->heading(get_string("newusers").':', 3);
937 echo "<ol class=\"list\">\n";
938 foreach ($users as $user) {
939 $fullname = fullname($user, $viewfullnames);
940 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
942 echo "</ol>\n</div>\n";
945 /// Next, have there been any modifications to the course structure?
947 $modinfo =& get_fast_modinfo($course);
949 $changelist = array();
951 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
952 module = 'course' AND
953 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
954 array($timestart, $course->id
), "id ASC");
957 $actions = array('add mod', 'update mod', 'delete mod');
958 $newgones = array(); // added and later deleted items
959 foreach ($logs as $key => $log) {
960 if (!in_array($log->action
, $actions)) {
963 $info = explode(' ', $log->info
);
965 // note: in most cases I replaced hardcoding of label with use of
966 // $cm->has_view() but it was not possible to do this here because
967 // we don't necessarily have the $cm for it
968 if ($info[0] == 'label') { // Labels are ignored in recent activity
972 if (count($info) != 2) {
973 debugging("Incorrect log entry info: id = ".$log->id
, DEBUG_DEVELOPER
);
978 $instanceid = $info[1];
980 if ($log->action
== 'delete mod') {
981 // unfortunately we do not know if the mod was visible
982 if (!array_key_exists($log->info
, $newgones)) {
983 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
984 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
987 if (!isset($modinfo->instances
[$modname][$instanceid])) {
988 if ($log->action
== 'add mod') {
989 // do not display added and later deleted activities
990 $newgones[$log->info
] = true;
994 $cm = $modinfo->instances
[$modname][$instanceid];
995 if (!$cm->uservisible
) {
999 if ($log->action
== 'add mod') {
1000 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1001 $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>");
1003 } else if ($log->action
== 'update mod' and empty($changelist[$log->info
])) {
1004 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1005 $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>");
1011 if (!empty($changelist)) {
1012 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1014 foreach ($changelist as $changeinfo => $change) {
1015 echo '<p class="activity">'.$change['text'].'</p>';
1019 /// Now display new things from each module
1021 $usedmodules = array();
1022 foreach($modinfo->cms
as $cm) {
1023 if (isset($usedmodules[$cm->modname
])) {
1026 if (!$cm->uservisible
) {
1029 $usedmodules[$cm->modname
] = $cm->modname
;
1032 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1033 if (file_exists($CFG->dirroot
.'/mod/'.$modname.'/lib.php')) {
1034 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
1035 $print_recent_activity = $modname.'_print_recent_activity';
1036 if (function_exists($print_recent_activity)) {
1037 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1038 $content = $print_recent_activity($course, $viewfullnames, $timestart) ||
$content;
1041 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1046 echo '<p class="message">'.get_string('nothingnew').'</p>';
1051 * For a given course, returns an array of course activity objects
1052 * Each item in the array contains he following properties:
1054 function get_array_of_activities($courseid) {
1055 // cm - course module id
1056 // mod - name of the module (eg forum)
1057 // section - the number of the section (eg week or topic)
1058 // name - the name of the instance
1059 // visible - is the instance visible or not
1060 // groupingid - grouping id
1061 // groupmembersonly - is this instance visible to group members only
1062 // extra - contains extra string to include in any link
1064 if(!empty($CFG->enableavailability
)) {
1065 require_once($CFG->libdir
.'/conditionlib.php');
1068 $course = $DB->get_record('course', array('id'=>$courseid));
1070 if (empty($course)) {
1071 throw new moodle_exception('courseidnotfound');
1076 $rawmods = get_course_mods($courseid);
1077 if (empty($rawmods)) {
1078 return $mod; // always return array
1081 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1082 foreach ($sections as $section) {
1083 if (!empty($section->sequence
)) {
1084 $sequence = explode(",", $section->sequence
);
1085 foreach ($sequence as $seq) {
1086 if (empty($rawmods[$seq])) {
1089 $mod[$seq]->id
= $rawmods[$seq]->instance
;
1090 $mod[$seq]->cm
= $rawmods[$seq]->id
;
1091 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
1093 // Oh dear. Inconsistent names left here for backward compatibility.
1094 $mod[$seq]->section
= $section->section
;
1095 $mod[$seq]->sectionid
= $rawmods[$seq]->section
;
1097 $mod[$seq]->module
= $rawmods[$seq]->module
;
1098 $mod[$seq]->added
= $rawmods[$seq]->added
;
1099 $mod[$seq]->score
= $rawmods[$seq]->score
;
1100 $mod[$seq]->idnumber
= $rawmods[$seq]->idnumber
;
1101 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
1102 $mod[$seq]->visibleold
= $rawmods[$seq]->visibleold
;
1103 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
1104 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
1105 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
1106 $mod[$seq]->indent
= $rawmods[$seq]->indent
;
1107 $mod[$seq]->completion
= $rawmods[$seq]->completion
;
1108 $mod[$seq]->extra
= "";
1109 $mod[$seq]->completiongradeitemnumber
=
1110 $rawmods[$seq]->completiongradeitemnumber
;
1111 $mod[$seq]->completionview
= $rawmods[$seq]->completionview
;
1112 $mod[$seq]->completionexpected
= $rawmods[$seq]->completionexpected
;
1113 $mod[$seq]->availablefrom
= $rawmods[$seq]->availablefrom
;
1114 $mod[$seq]->availableuntil
= $rawmods[$seq]->availableuntil
;
1115 $mod[$seq]->showavailability
= $rawmods[$seq]->showavailability
;
1116 if (!empty($CFG->enableavailability
)) {
1117 condition_info
::fill_availability_conditions($rawmods[$seq]);
1118 $mod[$seq]->conditionscompletion
= $rawmods[$seq]->conditionscompletion
;
1119 $mod[$seq]->conditionsgrade
= $rawmods[$seq]->conditionsgrade
;
1122 $modname = $mod[$seq]->mod
;
1123 $functionname = $modname."_get_coursemodule_info";
1125 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1129 include_once("$CFG->dirroot/mod/$modname/lib.php");
1131 if (function_exists($functionname)) {
1132 if ($info = $functionname($rawmods[$seq])) {
1133 if (!empty($info->icon
)) {
1134 $mod[$seq]->icon
= $info->icon
;
1136 if (!empty($info->iconcomponent
)) {
1137 $mod[$seq]->iconcomponent
= $info->iconcomponent
;
1139 if (!empty($info->name
)) {
1140 $mod[$seq]->name
= $info->name
;
1142 if ($info instanceof cached_cm_info
) {
1143 // When using cached_cm_info you can include three new fields
1144 // that aren't available for legacy code
1145 if (!empty($info->content
)) {
1146 $mod[$seq]->content
= $info->content
;
1148 if (!empty($info->extraclasses
)) {
1149 $mod[$seq]->extraclasses
= $info->extraclasses
;
1151 if (!empty($info->onclick
)) {
1152 $mod[$seq]->onclick
= $info->onclick
;
1154 if (!empty($info->customdata
)) {
1155 $mod[$seq]->customdata
= $info->customdata
;
1158 // When using a stdclass, the (horrible) deprecated ->extra field
1159 // is available for BC
1160 if (!empty($info->extra
)) {
1161 $mod[$seq]->extra
= $info->extra
;
1166 if (!isset($mod[$seq]->name
)) {
1167 $mod[$seq]->name
= $DB->get_field($rawmods[$seq]->modname
, "name", array("id"=>$rawmods[$seq]->instance
));
1170 // Minimise the database size by unsetting default options when they are
1171 // 'empty'. This list corresponds to code in the cm_info constructor.
1172 foreach(array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1173 'indent', 'completion', 'extra', 'extraclasses', 'onclick', 'content',
1174 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1175 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1176 'completionview', 'completionexpected', 'score') as $property) {
1177 if (property_exists($mod[$seq], $property) &&
1178 empty($mod[$seq]->{$property})) {
1179 unset($mod[$seq]->{$property});
1182 // Special case: this value is usually set to null, but may be 0
1183 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1184 is_null($mod[$seq]->completiongradeitemnumber
)) {
1185 unset($mod[$seq]->completiongradeitemnumber
);
1196 * Returns a number of useful structures for course displays
1198 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1199 global $CFG, $DB, $COURSE;
1201 $mods = array(); // course modules indexed by id
1202 $modnames = array(); // all course module names (except resource!)
1203 $modnamesplural= array(); // all course module names (plural form)
1204 $modnamesused = array(); // course module names used
1206 if ($allmods = $DB->get_records("modules")) {
1207 foreach ($allmods as $mod) {
1208 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1211 if ($mod->visible
) {
1212 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1213 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1216 textlib_get_instance()->asort($modnames);
1218 print_error("nomodules", 'debug');
1221 $course = ($courseid==$COURSE->id
) ?
$COURSE : $DB->get_record('course',array('id'=>$courseid));
1222 $modinfo = get_fast_modinfo($course);
1224 if ($rawmods=$modinfo->cms
) {
1225 foreach($rawmods as $mod) { // Index the mods
1226 if (empty($modnames[$mod->modname
])) {
1229 $mods[$mod->id
] = $mod;
1230 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1231 if (!$mod->visible
and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1235 if (!groups_course_module_visible($mod)) {
1238 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1240 if ($modnamesused) {
1241 textlib_get_instance()->asort($modnamesused);
1247 * Returns an array of sections for the requested course id
1249 * This function stores the sections against the course id within a staticvar encase
1250 * of subsequent requests. This is used all over + in some standard libs and course
1251 * format callbacks so subsequent requests are a reality.
1253 * @staticvar array $coursesections
1254 * @param int $courseid
1255 * @return array Array of sections
1257 function get_all_sections($courseid) {
1259 static $coursesections = array();
1260 if (!array_key_exists($courseid, $coursesections)) {
1261 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1262 "section, id, course, name, summary, summaryformat, sequence, visible");
1264 return $coursesections[$courseid];
1268 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1269 * It also sets the $USER->display cache to array($courseid=>return value)
1271 * @param int $courseid The course id
1272 * @return int Course section to display, 0 means all
1274 function course_get_display($courseid) {
1277 if (!isloggedin() or isguestuser()) {
1278 //do not get settings in db for guests
1279 return 0; //return the implicit setting
1282 if (!isset($USER->display
[$courseid])) {
1283 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id
, 'course'=>$courseid))) {
1284 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1286 //use display cache for one course only - we need to keep session small
1287 $USER->display
= array($courseid => $display);
1290 return $USER->display
[$courseid];
1294 * Show one section only or all sections.
1296 * @param int $courseid The course id
1297 * @param mixed $display show only this section, 0 or 'all' means show all sections
1298 * @return int Course section to display, 0 means all
1300 function course_set_display($courseid, $display) {
1303 if ($display === 'all' or empty($display)) {
1307 if (!isloggedin() or isguestuser()) {
1308 //do not store settings in db for guests
1312 if ($display == 0) {
1313 //show all, do not store anything in database
1314 $DB->delete_records('course_display', array('userid' => $USER->id
, 'course' => $courseid));
1317 if ($DB->record_exists('course_display', array('userid' => $USER->id
, 'course' => $courseid))) {
1318 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id
, 'course' => $courseid));
1320 $record = new stdClass();
1321 $record->userid
= $USER->id
;
1322 $record->course
= $courseid;
1323 $record->display
= $display;
1324 $DB->insert_record('course_display', $record);
1328 //use display cache for one course only - we need to keep session small
1329 $USER->display
= array($courseid => $display);
1335 * For a given course section, marks it visible or hidden,
1336 * and does the same for every activity in that section
1338 function set_section_visible($courseid, $sectionnumber, $visibility) {
1341 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1342 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id
));
1343 if (!empty($section->sequence
)) {
1344 $modules = explode(",", $section->sequence
);
1345 foreach ($modules as $moduleid) {
1346 set_coursemodule_visible($moduleid, $visibility, true);
1349 rebuild_course_cache($courseid);
1354 * Obtains shared data that is used in print_section when displaying a
1355 * course-module entry.
1357 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1359 * This data is also used in other areas of the code.
1360 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1361 * @param object $course Moodle course object
1362 * @return array An array with the following values in this order:
1363 * $content (optional extra content for after link),
1364 * $instancename (text of link)
1366 function get_print_section_cm_text(cm_info
$cm, $course) {
1369 // Get course context
1370 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1372 // Get content from modinfo if specified. Content displays either
1373 // in addition to the standard link (below), or replaces it if
1374 // the link is turned off by setting ->url to null.
1375 if (($content = $cm->get_content()) !== '') {
1376 $labelformatoptions = new stdClass();
1377 $labelformatoptions->noclean
= true;
1378 $labelformatoptions->overflowdiv
= true;
1379 $labelformatoptions->context
= $coursecontext;
1380 $content = format_text($content, FORMAT_HTML
, $labelformatoptions);
1385 $stringoptions = new stdClass
;
1386 $stringoptions->context
= $coursecontext;
1387 $instancename = format_string($cm->name
, true, $stringoptions);
1388 return array($content, $instancename);
1392 * Prints a section full of activity modules
1394 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1395 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1397 static $initialised;
1399 static $groupbuttons;
1400 static $groupbuttonslink;
1403 static $strmovehere;
1404 static $strmovefull;
1405 static $strunreadpostsone;
1407 static $modulenames;
1409 if (!isset($initialised)) {
1410 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1411 $groupbuttonslink = (!$course->groupmodeforce
);
1412 $isediting = $PAGE->user_is_editing();
1413 $ismoving = $isediting && ismoving($course->id
);
1415 $strmovehere = get_string("movehere");
1416 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1418 $modulenames = array();
1419 $initialised = true;
1422 $tl = textlib_get_instance();
1424 $modinfo = get_fast_modinfo($course);
1425 $completioninfo = new completion_info($course);
1427 //Accessibility: replace table with list <ul>, but don't output empty list.
1428 if (!empty($section->sequence
)) {
1430 // Fix bug #5027, don't want style=\"width:$width\".
1431 echo "<ul class=\"section img-text\">\n";
1432 $sectionmods = explode(",", $section->sequence
);
1434 foreach ($sectionmods as $modnumber) {
1435 if (empty($mods[$modnumber])) {
1442 $mod = $mods[$modnumber];
1444 if ($ismoving and $mod->id
== $USER->activitycopy
) {
1445 // do not display moving mod
1449 if (isset($modinfo->cms
[$modnumber])) {
1450 // We can continue (because it will not be displayed at all)
1452 // 1) The activity is not visible to users
1454 // 2a) The 'showavailability' option is not set (if that is set,
1455 // we need to display the activity so we can show
1456 // availability info)
1458 // 2b) The 'availableinfo' is empty, i.e. the activity was
1459 // hidden in a way that leaves no info, such as using the
1461 if (!$modinfo->cms
[$modnumber]->uservisible
&&
1462 (empty($modinfo->cms
[$modnumber]->showavailability
) ||
1463 empty($modinfo->cms
[$modnumber]->availableinfo
))) {
1464 // visibility shortcut
1468 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1469 // module not installed
1472 if (!coursemodule_visible_for_user($mod) &&
1473 empty($mod->showavailability
)) {
1474 // full visibility check
1479 if (!isset($modulenames[$mod->modname
])) {
1480 $modulenames[$mod->modname
] = get_string('modulename', $mod->modname
);
1482 $modulename = $modulenames[$mod->modname
];
1484 // In some cases the activity is visible to user, but it is
1485 // dimmed. This is done if viewhiddenactivities is true and if:
1486 // 1. the activity is not visible, or
1487 // 2. the activity has dates set which do not include current, or
1488 // 3. the activity has any other conditions set (regardless of whether
1489 // current user meets them)
1490 $canviewhidden = has_capability(
1491 'moodle/course:viewhiddenactivities',
1492 get_context_instance(CONTEXT_MODULE
, $mod->id
));
1493 $accessiblebutdim = false;
1494 if ($canviewhidden) {
1495 $accessiblebutdim = !$mod->visible
;
1496 if (!empty($CFG->enableavailability
)) {
1497 $accessiblebutdim = $accessiblebutdim ||
1498 $mod->availablefrom
> time() ||
1499 ($mod->availableuntil
&& $mod->availableuntil
< time()) ||
1500 count($mod->conditionsgrade
) > 0 ||
1501 count($mod->conditionscompletion
) > 0;
1505 $liclasses = array();
1506 $liclasses[] = 'activity';
1507 $liclasses[] = $mod->modname
;
1508 $liclasses[] = 'modtype_'.$mod->modname
;
1509 $extraclasses = $mod->get_extra_classes();
1510 if ($extraclasses) {
1511 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1513 echo html_writer
::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1515 echo '<a title="'.$strmovefull.'"'.
1516 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.sesskey().'">'.
1517 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1518 ' alt="'.$strmovehere.'" /></a><br />
1522 $classes = array('mod-indent');
1523 if (!empty($mod->indent
)) {
1524 $classes[] = 'mod-indent-'.$mod->indent
;
1525 if ($mod->indent
> 15) {
1526 $classes[] = 'mod-indent-huge';
1529 echo html_writer
::start_tag('div', array('class'=>join(' ', $classes)));
1531 // Get data about this course-module
1532 list($content, $instancename) =
1533 get_print_section_cm_text($modinfo->cms
[$modnumber], $course);
1535 //Accessibility: for files get description via icon, this is very ugly hack!
1537 $altname = $mod->modfullname
;
1538 if (!empty($customicon)) {
1539 $archetype = plugin_supports('mod', $mod->modname
, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1540 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1541 $mimetype = mimeinfo_from_icon('type', $customicon);
1542 $altname = get_mimetype_description($mimetype);
1545 // Avoid unnecessary duplication: if e.g. a forum name already
1546 // includes the word forum (or Forum, etc) then it is unhelpful
1547 // to include that in the accessible description that is added.
1548 if (false !== strpos($tl->strtolower($instancename),
1549 $tl->strtolower($altname))) {
1552 // File type after name, for alphabetic lists (screen reader).
1554 $altname = get_accesshide(' '.$altname);
1557 // We may be displaying this just in order to show information
1558 // about visibility, without the actual link
1560 if ($mod->uservisible
) {
1561 // Nope - in this case the link is fully working for user
1564 if ($accessiblebutdim) {
1565 $linkclasses .= ' dimmed';
1566 $textclasses .= ' dimmed_text';
1567 $accesstext = '<span class="accesshide">'.
1568 get_string('hiddenfromstudents').': </span>';
1573 $linkcss = 'class="' . trim($linkclasses) . '" ';
1578 $textcss = 'class="' . trim($textclasses) . '" ';
1583 // Get on-click attribute value if specified
1584 $onclick = $mod->get_on_click();
1586 $onclick = ' onclick="' . $onclick . '"';
1589 if ($url = $mod->get_url()) {
1590 // Display link itself
1591 echo '<a ' . $linkcss . $mod->extra
. $onclick .
1592 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1593 '" class="activityicon" alt="' .
1594 $modulename . '" /> ' .
1595 $accesstext . '<span class="instancename">' .
1596 $instancename . $altname . '</span></a>';
1598 // If specified, display extra content after link
1600 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1601 '">' . $content . '</div>';
1604 // No link, so display only content
1605 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1606 $accesstext . $content . '</div>';
1609 if (!empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1610 if (!isset($groupings)) {
1611 $groupings = groups_get_all_groupings($course->id
);
1613 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1616 $textclasses = $extraclasses;
1617 $textclasses .= ' dimmed_text';
1619 $textcss = 'class="' . trim($textclasses) . '" ';
1623 $accesstext = '<span class="accesshide">' .
1624 get_string('notavailableyet', 'condition') .
1627 if ($url = $mod->get_url()) {
1628 // Display greyed-out text of link
1629 echo '<div ' . $textcss . $mod->extra
.
1630 ' >' . '<img src="' . $mod->get_icon_url() .
1631 '" class="activityicon" alt="' .
1633 '" /> <span>'. $instancename . $altname .
1636 // Do not display content after link when it is greyed out like this.
1638 // No link, so display only content (also greyed)
1639 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1640 $accesstext . $content . '</div>';
1644 // Module can put text after the link (e.g. forum unread)
1645 echo $mod->get_after_link();
1647 // If there is content but NO link (eg label), then display the
1648 // content here (BEFORE any icons). In this case cons must be
1649 // displayed after the content so that it makes more sense visually
1650 // and for accessibility reasons, e.g. if you have a one-line label
1651 // it should work similarly (at least in terms of ordering) to an
1658 if ($groupbuttons and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
1659 if (! $mod->groupmodelink
= $groupbuttonslink) {
1660 $mod->groupmode
= $course->groupmode
;
1664 $mod->groupmode
= false;
1666 echo ' ';
1667 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1668 echo $mod->get_after_edit_icons();
1672 $completion = $hidecompletion
1673 ? COMPLETION_TRACKING_NONE
1674 : $completioninfo->is_enabled($mod);
1675 if ($completion!=COMPLETION_TRACKING_NONE
&& isloggedin() &&
1676 !isguestuser() && $mod->uservisible
) {
1677 $completiondata = $completioninfo->get_data($mod,true);
1678 $completionicon = '';
1680 switch ($completion) {
1681 case COMPLETION_TRACKING_MANUAL
:
1682 $completionicon = 'manual-enabled'; break;
1683 case COMPLETION_TRACKING_AUTOMATIC
:
1684 $completionicon = 'auto-enabled'; break;
1687 } else if ($completion==COMPLETION_TRACKING_MANUAL
) {
1688 switch($completiondata->completionstate
) {
1689 case COMPLETION_INCOMPLETE
:
1690 $completionicon = 'manual-n'; break;
1691 case COMPLETION_COMPLETE
:
1692 $completionicon = 'manual-y'; break;
1694 } else { // Automatic
1695 switch($completiondata->completionstate
) {
1696 case COMPLETION_INCOMPLETE
:
1697 $completionicon = 'auto-n'; break;
1698 case COMPLETION_COMPLETE
:
1699 $completionicon = 'auto-y'; break;
1700 case COMPLETION_COMPLETE_PASS
:
1701 $completionicon = 'auto-pass'; break;
1702 case COMPLETION_COMPLETE_FAIL
:
1703 $completionicon = 'auto-fail'; break;
1706 if ($completionicon) {
1707 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1708 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1709 if ($completion == COMPLETION_TRACKING_MANUAL
&& !$isediting) {
1710 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1712 $completiondata->completionstate
==COMPLETION_COMPLETE
1713 ? COMPLETION_INCOMPLETE
1714 : COMPLETION_COMPLETE
;
1715 // In manual mode the icon is a toggle form...
1717 // If this completion state is used by the
1718 // conditional activities system, we need to turn
1720 if (!empty($CFG->enableavailability
) &&
1721 condition_info
::completion_value_used_as_condition($course, $mod)) {
1722 $extraclass = ' preventjs';
1727 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot
."/course/togglecompletion.php'><div>
1728 <input type='hidden' name='id' value='{$mod->id}' />
1729 <input type='hidden' name='sesskey' value='".sesskey()."' />
1730 <input type='hidden' name='completionstate' value='$newstate' />
1731 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1734 // In auto mode, or when editing, the icon is just an image
1735 echo "<span class='autocompletion'>";
1736 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1741 // If there is content AND a link, then display the content here
1742 // (AFTER any icons). Otherwise it was displayed before
1747 // Show availability information (for someone who isn't allowed to
1748 // see the activity itself, or for staff)
1749 if (!$mod->uservisible
) {
1750 echo '<div class="availabilityinfo">'.$mod->availableinfo
.'</div>';
1751 } else if ($canviewhidden && !empty($CFG->enableavailability
)) {
1752 $ci = new condition_info($mod);
1753 $fullinfo = $ci->get_full_information();
1755 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1756 ?
'userrestriction_visible'
1757 : 'userrestriction_hidden','condition',
1758 $fullinfo).'</div>';
1762 echo html_writer
::end_tag('div');
1763 echo html_writer
::end_tag('li')."\n";
1766 } elseif ($ismoving) {
1767 echo "<ul class=\"section\">\n";
1771 echo '<li><a title="'.$strmovefull.'"'.
1772 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.sesskey().'">'.
1773 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1774 ' alt="'.$strmovehere.'" /></a></li>
1777 if (!empty($section->sequence
) ||
$ismoving) {
1778 echo "</ul><!--class='section'-->\n\n";
1783 * Prints the menus to add activities and resources.
1785 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1786 global $CFG, $OUTPUT;
1788 // check to see if user can add menus
1789 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1793 $urlbase = "/course/mod.php?id=$course->id§ion=$section&sesskey=".sesskey().'&add=';
1795 $resources = array();
1796 $activities = array();
1798 foreach($modnames as $modname=>$modnamestr) {
1799 if (!course_allowed_module($course, $modname)) {
1803 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1804 if (!file_exists($libfile)) {
1807 include_once($libfile);
1808 $gettypesfunc = $modname.'_get_types';
1809 if (function_exists($gettypesfunc)) {
1810 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1811 if ($types = $gettypesfunc()) {
1815 foreach($types as $type) {
1816 if ($type->typestr
=== '--') {
1819 if (strpos($type->typestr
, '--') === 0) {
1820 $groupname = str_replace('--', '', $type->typestr
);
1823 $type->type
= str_replace('&', '&', $type->type
);
1824 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1825 $atype = MOD_CLASS_RESOURCE
;
1827 $menu[$urlbase.$type->type
] = $type->typestr
;
1829 if (!is_null($groupname)) {
1830 if ($atype == MOD_CLASS_RESOURCE
) {
1831 $resources[] = array($groupname=>$menu);
1833 $activities[] = array($groupname=>$menu);
1836 if ($atype == MOD_CLASS_RESOURCE
) {
1837 $resources = array_merge($resources, $menu);
1839 $activities = array_merge($activities, $menu);
1844 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1845 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1846 $resources[$urlbase.$modname] = $modnamestr;
1848 // all other archetypes are considered activity
1849 $activities[$urlbase.$modname] = $modnamestr;
1854 $straddactivity = get_string('addactivity');
1855 $straddresource = get_string('addresource');
1857 $output = '<div class="section_add_menus">';
1860 $output .= '<div class="horizontal">';
1863 if (!empty($resources)) {
1864 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1865 $select->set_help_icon('resources');
1866 $output .= $OUTPUT->render($select);
1869 if (!empty($activities)) {
1870 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1871 $select->set_help_icon('activities');
1872 $output .= $OUTPUT->render($select);
1876 $output .= '</div>';
1879 $output .= '</div>';
1889 * Return the course category context for the category with id $categoryid, except
1890 * that if $categoryid is 0, return the system context.
1892 * @param integer $categoryid a category id or 0.
1893 * @return object the corresponding context
1895 function get_category_or_system_context($categoryid) {
1897 return get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1899 return get_context_instance(CONTEXT_SYSTEM
);
1904 * Gets the child categories of a given courses category. Uses a static cache
1905 * to make repeat calls efficient.
1907 * @param int $parentid the id of a course category.
1908 * @return array all the child course categories.
1910 function get_child_categories($parentid) {
1911 static $allcategories = null;
1913 // only fill in this variable the first time
1914 if (null == $allcategories) {
1915 $allcategories = array();
1917 $categories = get_categories();
1918 foreach ($categories as $category) {
1919 if (empty($allcategories[$category->parent
])) {
1920 $allcategories[$category->parent
] = array();
1922 $allcategories[$category->parent
][] = $category;
1926 if (empty($allcategories[$parentid])) {
1929 return $allcategories[$parentid];
1934 * This function recursively travels the categories, building up a nice list
1935 * for display. It also makes an array that list all the parents for each
1938 * For example, if you have a tree of categories like:
1939 * Miscellaneous (id = 1)
1940 * Subcategory (id = 2)
1941 * Sub-subcategory (id = 4)
1942 * Other category (id = 3)
1943 * Then after calling this function you will have
1944 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1945 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1946 * 3 => 'Other category');
1947 * $parents = array(2 => array(1), 4 => array(1, 2));
1949 * If you specify $requiredcapability, then only categories where the current
1950 * user has that capability will be added to $list, although all categories
1951 * will still be added to $parents, and if you only have $requiredcapability
1952 * in a child category, not the parent, then the child catgegory will still be
1955 * If you specify the option $excluded, then that category, and all its children,
1956 * are omitted from the tree. This is useful when you are doing something like
1957 * moving categories, where you do not want to allow people to move a category
1958 * to be the child of itself.
1960 * @param array $list For output, accumulates an array categoryid => full category path name
1961 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1962 * @param string/array $requiredcapability if given, only categories where the current
1963 * user has this capability will be added to $list. Can also be an array of capabilities,
1964 * in which case they are all required.
1965 * @param integer $excludeid Omit this category and its children from the lists built.
1966 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1967 * @param string $path For internal use, as part of recursive calls.
1969 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1970 $excludeid = 0, $category = NULL, $path = "") {
1972 // initialize the arrays if needed
1973 if (!is_array($list)) {
1976 if (!is_array($parents)) {
1980 if (empty($category)) {
1981 // Start at the top level.
1982 $category = new stdClass
;
1985 // This is the excluded category, don't include it.
1986 if ($excludeid > 0 && $excludeid == $category->id
) {
1990 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
1991 $categoryname = format_string($category->name
, true, array('context' => $context));
1995 $path = $path.' / '.$categoryname;
1997 $path = $categoryname;
2000 // Add this category to $list, if the permissions check out.
2001 if (empty($requiredcapability)) {
2002 $list[$category->id
] = $path;
2005 $requiredcapability = (array)$requiredcapability;
2006 if (has_all_capabilities($requiredcapability, $context)) {
2007 $list[$category->id
] = $path;
2012 // Add all the children recursively, while updating the parents array.
2013 if ($categories = get_child_categories($category->id
)) {
2014 foreach ($categories as $cat) {
2015 if (!empty($category->id
)) {
2016 if (isset($parents[$category->id
])) {
2017 $parents[$cat->id
] = $parents[$category->id
];
2019 $parents[$cat->id
][] = $category->id
;
2021 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2027 * This function generates a structured array of courses and categories.
2029 * The depth of categories is limited by $CFG->maxcategorydepth however there
2030 * is no limit on the number of courses!
2032 * Suitable for use with the course renderers course_category_tree method:
2033 * $renderer = $PAGE->get_renderer('core','course');
2034 * echo $renderer->course_category_tree(get_course_category_tree());
2036 * @global moodle_database $DB
2040 function get_course_category_tree($id = 0, $depth = 0) {
2042 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
));
2043 $categories = get_child_categories($id);
2044 $categoryids = array();
2045 foreach ($categories as $key => &$category) {
2046 if (!$category->visible
&& !$viewhiddencats) {
2047 unset($categories[$key]);
2050 $categoryids[$category->id
] = $category;
2051 if (empty($CFG->maxcategorydepth
) ||
$depth <= $CFG->maxcategorydepth
) {
2052 list($category->categories
, $subcategories) = get_course_category_tree($category->id
, $depth+
1);
2053 foreach ($subcategories as $subid=>$subcat) {
2054 $categoryids[$subid] = $subcat;
2056 $category->courses
= array();
2061 // This is a recursive call so return the required array
2062 return array($categories, $categoryids);
2065 // The depth is 0 this function has just been called so we can finish it off
2067 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
2068 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2070 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2074 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2075 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2076 // loop throught them
2077 foreach ($courses as $course) {
2078 if ($course->id
== SITEID
) {
2081 context_instance_preload($course);
2082 if (!empty($course->visible
) ||
has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
2083 $categoryids[$course->category
]->courses
[$course->id
] = $course;
2091 * Recursive function to print out all the categories in a nice format
2092 * with or without courses included
2094 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2097 // maxcategorydepth == 0 meant no limit
2098 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
2102 if (!$displaylist) {
2103 make_categories_list($displaylist, $parentslist);
2107 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
))) {
2108 print_category_info($category, $depth, $showcourses);
2110 return; // Don't bother printing children of invisible categories
2114 $category->id
= "0";
2117 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
2118 $countcats = count($categories);
2122 foreach ($categories as $cat) {
2124 if ($count == $countcats) {
2127 $up = $first ?
false : true;
2128 $down = $last ?
false : true;
2131 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses);
2137 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2139 function make_categories_options() {
2140 make_categories_list($cats,$parents);
2141 foreach ($cats as $key => $value) {
2142 if (array_key_exists($key,$parents)) {
2143 if ($indent = count($parents[$key])) {
2144 for ($i = 0; $i < $indent; $i++
) {
2145 $cats[$key] = ' '.$cats[$key];
2154 * Prints the category info in indented fashion
2155 * This function is only used by print_whole_category_list() above
2157 function print_category_info($category, $depth=0, $showcourses = false) {
2158 global $CFG, $DB, $OUTPUT;
2160 $strsummary = get_string('summary');
2163 if (!$category->visible
) {
2164 $catlinkcss = array('class'=>'dimmed');
2166 static $coursecount = null;
2167 if (null === $coursecount) {
2168 // only need to check this once
2169 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT
;
2172 if ($showcourses and $coursecount) {
2173 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2175 $catimage = " ";
2178 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2179 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
2180 $fullname = format_string($category->name
, true, array('context' => $context));
2182 if ($showcourses and $coursecount) {
2183 echo '<div class="categorylist clearfix">';
2185 $cat .= html_writer
::tag('div', $catimage, array('class'=>'image'));
2186 $catlink = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
2187 $cat .= html_writer
::tag('div', $catlink, array('class'=>'name'));
2191 for ($i=0; $i< $depth; $i++
) {
2192 $html = html_writer
::tag('div', $html . $cat, array('class'=>'indentation'));
2198 echo html_writer
::tag('div', $html, array('class'=>'category'));
2199 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2201 // does the depth exceed maxcategorydepth
2202 // maxcategorydepth == 0 or unset meant no limit
2203 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
2204 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
2205 foreach ($courses as $course) {
2207 if (!$course->visible
) {
2208 $linkcss = array('class'=>'dimmed');
2211 $courselink = html_writer
::link(new moodle_url('/course/view.php', array('id'=>$course->id
)), format_string($course->fullname
), $linkcss);
2215 if ($icons = enrol_get_course_info_icons($course)) {
2216 foreach ($icons as $pix_icon) {
2217 $courseicon = $OUTPUT->render($pix_icon).' ';
2221 $coursecontent = html_writer
::tag('div', $courseicon.$courselink, array('class'=>'name'));
2223 if ($course->summary
) {
2224 $link = new moodle_url('/course/info.php?id='.$course->id
);
2225 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2226 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2227 array('title'=>$strsummary));
2229 $coursecontent .= html_writer
::tag('div', $actionlink, array('class'=>'info'));
2233 for ($i=0; $i <= $depth; $i++
) {
2234 $html = html_writer
::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2235 $coursecontent = '';
2237 echo html_writer
::tag('div', $html, array('class'=>'course clearfloat'));
2242 echo '<div class="categorylist">';
2244 $cat = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
2245 if (count($courses) > 0) {
2246 $cat .= html_writer
::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2250 for ($i=0; $i< $depth; $i++
) {
2251 $html = html_writer
::tag('div', $html .$cat, array('class'=>'indentation'));
2258 echo html_writer
::tag('div', $html, array('class'=>'category'));
2259 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2265 * Print the buttons relating to course requests.
2267 * @param object $systemcontext the system context.
2269 function print_course_request_buttons($systemcontext) {
2270 global $CFG, $DB, $OUTPUT;
2271 if (empty($CFG->enablecourserequests
)) {
2274 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2275 /// Print a button to request a new course
2276 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2278 /// Print a button to manage pending requests
2279 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2280 $disabled = !$DB->record_exists('course_request', array());
2281 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2286 * Does the user have permission to edit things in this category?
2288 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2289 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2291 function can_edit_in_category($categoryid = 0) {
2292 $context = get_category_or_system_context($categoryid);
2293 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2297 * Prints the turn editing on/off button on course/index.php or course/category.php.
2299 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2300 * @return string HTML of the editing button, or empty string, if this user is not allowed
2303 function update_category_button($categoryid = 0) {
2304 global $CFG, $PAGE, $OUTPUT;
2306 // Check permissions.
2307 if (!can_edit_in_category($categoryid)) {
2311 // Work out the appropriate action.
2312 if ($PAGE->user_is_editing()) {
2313 $label = get_string('turneditingoff');
2316 $label = get_string('turneditingon');
2320 // Generate the button HTML.
2321 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2323 $options['id'] = $categoryid;
2324 $page = 'category.php';
2326 $page = 'index.php';
2328 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2332 * Category is 0 (for all courses) or an object
2334 function print_courses($category) {
2335 global $CFG, $OUTPUT;
2337 if (!is_object($category) && $category==0) {
2338 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2339 if (is_array($categories) && count($categories) == 1) {
2340 $category = array_shift($categories);
2341 $courses = get_courses_wmanagers($category->id
,
2343 array('summary','summaryformat'));
2345 $courses = get_courses_wmanagers('all',
2347 array('summary','summaryformat'));
2351 $courses = get_courses_wmanagers($category->id
,
2353 array('summary','summaryformat'));
2357 echo html_writer
::start_tag('ul', array('class'=>'unlist'));
2358 foreach ($courses as $course) {
2359 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2360 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2361 echo html_writer
::start_tag('li');
2362 print_course($course);
2363 echo html_writer
::end_tag('li');
2366 echo html_writer
::end_tag('ul');
2368 echo $OUTPUT->heading(get_string("nocoursesyet"));
2369 $context = get_context_instance(CONTEXT_SYSTEM
);
2370 if (has_capability('moodle/course:create', $context)) {
2372 if (!empty($category->id
)) {
2373 $options['category'] = $category->id
;
2375 $options['category'] = $CFG->defaultrequestcategory
;
2377 echo html_writer
::start_tag('div', array('class'=>'addcoursebutton'));
2378 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2379 echo html_writer
::end_tag('div');
2385 * Print a description of a course, suitable for browsing in a list.
2387 * @param object $course the course object.
2388 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2390 function print_course($course, $highlightterms = '') {
2391 global $CFG, $USER, $DB, $OUTPUT;
2393 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2395 // Rewrite file URLs so that they are correct
2396 $course->summary
= file_rewrite_pluginfile_urls($course->summary
, 'pluginfile.php', $context->id
, 'course', 'summary', NULL);
2398 echo html_writer
::start_tag('div', array('class'=>'coursebox clearfix'));
2399 echo html_writer
::start_tag('div', array('class'=>'info'));
2400 echo html_writer
::start_tag('h3', array('class'=>'name'));
2402 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id
));
2403 $linktext = highlight($highlightterms, format_string($course->fullname
));
2404 $linkparams = array('title'=>get_string('entercourse'));
2405 if (empty($course->visible
)) {
2406 $linkparams['class'] = 'dimmed';
2408 echo html_writer
::link($linkhref, $linktext, $linkparams);
2409 echo html_writer
::end_tag('h3');
2411 /// first find all roles that are supposed to be displayed
2412 if (!empty($CFG->coursecontact
)) {
2413 $managerroles = explode(',', $CFG->coursecontact
);
2414 $namesarray = array();
2415 if (isset($course->managers
)) {
2416 if (count($course->managers
)) {
2417 $rusers = $course->managers
;
2418 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2420 /// Rename some of the role names if needed
2421 if (isset($context)) {
2422 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2425 // keep a note of users displayed to eliminate duplicates
2426 $usersshown = array();
2427 foreach ($rusers as $ra) {
2429 // if we've already displayed user don't again
2430 if (in_array($ra->user
->id
,$usersshown)) {
2433 $usersshown[] = $ra->user
->id
;
2435 $fullname = fullname($ra->user
, $canviewfullnames);
2437 if (isset($aliasnames[$ra->roleid
])) {
2438 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
2441 $namesarray[] = format_string($ra->rolename
).': '.
2442 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$ra->user
->id
, 'course'=>SITEID
)), $fullname);
2446 $rusers = get_role_users($managerroles, $context,
2447 true, '', 'r.sortorder ASC, u.lastname ASC');
2448 if (is_array($rusers) && count($rusers)) {
2449 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2451 /// Rename some of the role names if needed
2452 if (isset($context)) {
2453 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2456 foreach ($rusers as $teacher) {
2457 $fullname = fullname($teacher, $canviewfullnames);
2459 /// Apply role names
2460 if (isset($aliasnames[$teacher->roleid
])) {
2461 $teacher->rolename
= $aliasnames[$teacher->roleid
]->name
;
2464 $namesarray[] = format_string($teacher->rolename
).': '.
2465 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$teacher->id
, 'course'=>SITEID
)), $fullname);
2470 if (!empty($namesarray)) {
2471 echo html_writer
::start_tag('ul', array('class'=>'teachers'));
2472 foreach ($namesarray as $name) {
2473 echo html_writer
::tag('li', $name);
2475 echo html_writer
::end_tag('ul');
2478 echo html_writer
::end_tag('div'); // End of info div
2480 echo html_writer
::start_tag('div', array('class'=>'summary'));
2482 $options->noclean
= true;
2483 $options->para
= false;
2484 $options->overflowdiv
= true;
2485 if (!isset($course->summaryformat
)) {
2486 $course->summaryformat
= FORMAT_MOODLE
;
2488 echo highlight($highlightterms, format_text($course->summary
, $course->summaryformat
, $options, $course->id
));
2489 if ($icons = enrol_get_course_info_icons($course)) {
2490 echo html_writer
::start_tag('div', array('class'=>'enrolmenticons'));
2491 foreach ($icons as $icon) {
2492 echo $OUTPUT->render($icon);
2494 echo html_writer
::end_tag('div'); // End of enrolmenticons div
2496 echo html_writer
::end_tag('div'); // End of summary div
2497 echo html_writer
::end_tag('div'); // End of coursebox div
2501 * Prints custom user information on the home page.
2502 * Over time this can include all sorts of information
2504 function print_my_moodle() {
2505 global $USER, $CFG, $DB, $OUTPUT;
2507 if (!isloggedin() or isguestuser()) {
2508 print_error('nopermissions', '', '', 'See My Moodle');
2511 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2513 $rcourses = array();
2514 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
2515 $rcourses = get_my_remotecourses($USER->id
);
2516 $rhosts = get_my_remotehosts();
2519 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
2521 if (!empty($courses)) {
2522 echo '<ul class="unlist">';
2523 foreach ($courses as $course) {
2524 if ($course->id
== SITEID
) {
2528 print_course($course);
2535 if (!empty($rcourses)) {
2536 // at the IDP, we know of all the remote courses
2537 foreach ($rcourses as $course) {
2538 print_remote_course($course, "100%");
2540 } elseif (!empty($rhosts)) {
2541 // non-IDP, we know of all the remote servers, but not courses
2542 foreach ($rhosts as $host) {
2543 print_remote_host($host, "100%");
2549 if ($DB->count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
2550 echo "<table width=\"100%\"><tr><td align=\"center\">";
2551 print_course_search("", false, "short");
2552 echo "</td><td align=\"center\">";
2553 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2554 echo "</td></tr></table>\n";
2558 if ($DB->count_records("course_categories") > 1) {
2559 echo $OUTPUT->box_start("categorybox");
2560 print_whole_category_list();
2561 echo $OUTPUT->box_end();
2569 function print_course_search($value="", $return=false, $format="plain") {
2575 $id = 'coursesearch';
2581 $strsearchcourses= get_string("searchcourses");
2583 if ($format == 'plain') {
2584 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2585 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2586 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2587 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2588 $output .= '<input type="submit" value="'.get_string('go').'" />';
2589 $output .= '</fieldset></form>';
2590 } else if ($format == 'short') {
2591 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2592 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2593 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2594 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2595 $output .= '<input type="submit" value="'.get_string('go').'" />';
2596 $output .= '</fieldset></form>';
2597 } else if ($format == 'navbar') {
2598 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2599 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2600 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2601 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2602 $output .= '<input type="submit" value="'.get_string('go').'" />';
2603 $output .= '</fieldset></form>';
2612 function print_remote_course($course, $width="100%") {
2617 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2619 echo '<div class="coursebox remotecoursebox clearfix">';
2620 echo '<div class="info">';
2621 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2622 $linkcss.' href="'.$url.'">'
2623 . format_string($course->fullname
) .'</a><br />'
2624 . format_string($course->hostname
) . ' : '
2625 . format_string($course->cat_name
) . ' : '
2626 . format_string($course->shortname
). '</div>';
2627 echo '</div><div class="summary">';
2629 $options->noclean
= true;
2630 $options->para
= false;
2631 $options->overflowdiv
= true;
2632 echo format_text($course->summary
, $course->summaryformat
, $options);
2637 function print_remote_host($host, $width="100%") {
2642 echo '<div class="coursebox clearfix">';
2643 echo '<div class="info">';
2644 echo '<div class="name">';
2645 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2646 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2647 . s($host['name']).'</a> - ';
2648 echo $host['count'] . ' ' . get_string('courses');
2655 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2657 function add_course_module($mod) {
2660 $mod->added
= time();
2663 return $DB->insert_record("course_modules", $mod);
2667 * Returns course section - creates new if does not exist yet.
2668 * @param int $relative section number
2669 * @param int $courseid
2670 * @return object $course_section object
2672 function get_course_section($section, $courseid) {
2675 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2678 $cw = new stdClass();
2679 $cw->course
= $courseid;
2680 $cw->section
= $section;
2682 $cw->summaryformat
= FORMAT_HTML
;
2684 $id = $DB->insert_record("course_sections", $cw);
2685 return $DB->get_record("course_sections", array("id"=>$id));
2688 * Given a full mod object with section and course already defined, adds this module to that section.
2690 * @param object $mod
2691 * @param int $beforemod An existing ID which we will insert the new module before
2692 * @return int The course_sections ID where the mod is inserted
2694 function add_mod_to_section($mod, $beforemod=NULL) {
2697 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course
, "section"=>$mod->section
))) {
2699 $section->sequence
= trim($section->sequence
);
2701 if (empty($section->sequence
)) {
2702 $newsequence = "$mod->coursemodule";
2704 } else if ($beforemod) {
2705 $modarray = explode(",", $section->sequence
);
2707 if ($key = array_keys($modarray, $beforemod->id
)) {
2708 $insertarray = array($mod->id
, $beforemod->id
);
2709 array_splice($modarray, $key[0], 1, $insertarray);
2710 $newsequence = implode(",", $modarray);
2712 } else { // Just tack it on the end anyway
2713 $newsequence = "$section->sequence,$mod->coursemodule";
2717 $newsequence = "$section->sequence,$mod->coursemodule";
2720 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2721 return $section->id
; // Return course_sections ID that was used.
2723 } else { // Insert a new record
2724 $section->course
= $mod->course
;
2725 $section->section
= $mod->section
;
2726 $section->summary
= "";
2727 $section->summaryformat
= FORMAT_HTML
;
2728 $section->sequence
= $mod->coursemodule
;
2729 return $DB->insert_record("course_sections", $section);
2733 function set_coursemodule_groupmode($id, $groupmode) {
2735 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2738 function set_coursemodule_idnumber($id, $idnumber) {
2740 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2744 * $prevstateoverrides = true will set the visibility of the course module
2745 * to what is defined in visibleold. This enables us to remember the current
2746 * visibility when making a whole section hidden, so that when we toggle
2747 * that section back to visible, we are able to return the visibility of
2748 * the course module back to what it was originally.
2750 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2752 require_once($CFG->libdir
.'/gradelib.php');
2754 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2757 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
2760 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2761 foreach($events as $event) {
2770 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2771 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
2773 foreach ($grade_items as $grade_item) {
2774 $grade_item->set_hidden(!$visible);
2778 if ($prevstateoverrides) {
2779 if ($visible == '0') {
2780 // Remember the current visible state so we can toggle this back.
2781 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id'=>$id));
2783 // Get the previous saved visible states.
2784 return $DB->set_field('course_modules', 'visible', $cm->visibleold
, array('id'=>$id));
2787 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2791 * Delete a course module and any associated data at the course level (events)
2792 * Until 1.5 this function simply marked a deleted flag ... now it
2793 * deletes it completely.
2796 function delete_course_module($id) {
2798 require_once($CFG->libdir
.'/gradelib.php');
2799 require_once($CFG->dirroot
.'/blog/lib.php');
2801 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2804 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
));
2805 //delete events from calendar
2806 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2807 foreach($events as $event) {
2808 delete_event($event->id
);
2811 //delete grade items, outcome items and grades attached to modules
2812 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2813 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2814 foreach ($grade_items as $grade_item) {
2815 $grade_item->delete('moddelete');
2818 // Delete completion and availability data; it is better to do this even if the
2819 // features are not turned on, in case they were turned on previously (these will be
2820 // very quick on an empty table)
2821 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
2822 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
2824 delete_context(CONTEXT_MODULE
, $cm->id
);
2825 return $DB->delete_records('course_modules', array('id'=>$cm->id
));
2828 function delete_mod_from_section($mod, $section) {
2831 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2833 $modarray = explode(",", $section->sequence
);
2835 if ($key = array_keys ($modarray, $mod)) {
2836 array_splice($modarray, $key[0], 1);
2837 $newsequence = implode(",", $modarray);
2838 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2848 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2850 * @param object $course
2851 * @param int $section
2852 * @param int $move (-1 or 1)
2854 function move_section($course, $section, $move) {
2855 /// Moves a whole course section up and down within the course
2862 $sectiondest = $section +
$move;
2864 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2868 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$section))) {
2872 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$sectiondest))) {
2876 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id
));
2877 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id
));
2879 // if the focus is on the section that is being moved, then move the focus along
2880 if (course_get_display($course->id
) == $section) {
2881 course_set_display($course->id
, $sectiondest);
2884 // Check for duplicates and fix order if needed.
2885 // There is a very rare case that some sections in the same course have the same section id.
2886 $sections = $DB->get_records('course_sections', array('course'=>$course->id
), 'section ASC');
2888 foreach ($sections as $section) {
2889 if ($section->section
!= $n) {
2890 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id
));
2898 * Moves a section within a course, from a position to another.
2899 * Be very careful: $section and $destination refer to section number,
2902 * @param object $course
2903 * @param int $section Section number (not id!!!)
2904 * @param int $destination
2905 * @return boolean Result
2907 function move_section_to($course, $section, $destination) {
2908 /// Moves a whole course section up and down within the course
2911 if (!$destination && $destination != 0) {
2915 if ($destination > $course->numsections
) {
2919 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2920 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
2921 'section ASC, id ASC', 'id, section')) {
2925 $sections = reorder_sections($sections, $section, $destination);
2927 // Update all sections
2928 foreach ($sections as $id => $position) {
2929 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2932 // if the focus is on the section that is being moved, then move the focus along
2933 if (course_get_display($course->id
) == $section) {
2934 course_set_display($course->id
, $destination);
2940 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2941 * an original position number and a target position number, rebuilds the array so that the
2942 * move is made without any duplication of section positions.
2943 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2944 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2946 * @param array $sections
2947 * @param int $origin_position
2948 * @param int $target_position
2951 function reorder_sections($sections, $origin_position, $target_position) {
2952 if (!is_array($sections)) {
2956 // We can't move section position 0
2957 if ($origin_position < 1) {
2958 echo "We can't move section position 0";
2962 // Locate origin section in sections array
2963 if (!$origin_key = array_search($origin_position, $sections)) {
2964 echo "searched position not in sections array";
2965 return false; // searched position not in sections array
2968 // Extract origin section
2969 $origin_section = $sections[$origin_key];
2970 unset($sections[$origin_key]);
2972 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2974 $append_array = array();
2975 foreach ($sections as $id => $position) {
2977 $append_array[$id] = $position;
2978 unset($sections[$id]);
2980 if ($position == $target_position) {
2985 // Append moved section
2986 $sections[$origin_key] = $origin_section;
2988 // Append rest of array (if applicable)
2989 if (!empty($append_array)) {
2990 foreach ($append_array as $id => $position) {
2991 $sections[$id] = $position;
2995 // Renumber positions
2997 foreach ($sections as $id => $p) {
2998 $sections[$id] = $position;
3007 * Move the module object $mod to the specified $section
3008 * If $beforemod exists then that is the module
3009 * before which $modid should be inserted
3010 * All parameters are objects
3012 function moveto_module($mod, $section, $beforemod=NULL) {
3013 global $DB, $OUTPUT;
3015 /// Remove original module from original section
3016 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
3017 echo $OUTPUT->notification("Could not delete module from existing section");
3020 /// Update module itself if necessary
3022 if ($mod->section
!= $section->id
) {
3023 $mod->section
= $section->id
;
3024 $DB->update_record("course_modules", $mod);
3025 // if moving to a hidden section then hide module
3026 if (!$section->visible
) {
3027 set_coursemodule_visible($mod->id
, 0);
3031 /// Add the module into the new section
3033 $mod->course
= $section->course
;
3034 $mod->section
= $section->section
; // need relative reference
3035 $mod->coursemodule
= $mod->id
;
3037 if (! add_mod_to_section($mod, $beforemod)) {
3044 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
3045 global $CFG, $USER, $DB, $OUTPUT;
3050 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3051 // no permission to edit
3052 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
3057 $str->assign
= get_string("assignroles", 'role');
3058 $str->delete
= get_string("delete");
3059 $str->move
= get_string("move");
3060 $str->moveup
= get_string("moveup");
3061 $str->movedown
= get_string("movedown");
3062 $str->moveright
= get_string("moveright");
3063 $str->moveleft
= get_string("moveleft");
3064 $str->update
= get_string("update");
3065 $str->duplicate
= get_string("duplicate");
3066 $str->hide
= get_string("hide");
3067 $str->show
= get_string("show");
3068 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3069 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3070 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3071 $str->forcedgroupsnone
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3072 $str->forcedgroupsseparate
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3073 $str->forcedgroupsvisible
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3074 $sesskey = sesskey();
3077 if ($section >= 0) {
3078 $section = '&sr='.$section; // Section return
3084 $path = $CFG->wwwroot
.'/course';
3088 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3089 if ($mod->visible
) {
3090 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
3091 '&sesskey='.$sesskey.$section.'"><img'.
3092 ' src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" '.
3093 ' alt="'.$str->hide
.'" /></a>'."\n";
3095 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
3096 '&sesskey='.$sesskey.$section.'"><img'.
3097 ' src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" '.
3098 ' alt="'.$str->show
.'" /></a>'."\n";
3104 if ($mod->groupmode
!== false) {
3105 if ($mod->groupmode
== SEPARATEGROUPS
) {
3106 $grouptitle = $str->groupsseparate
;
3107 $forcedgrouptitle = $str->forcedgroupsseparate
;
3108 $groupclass = 'editing_groupsseparate';
3109 $groupimage = $OUTPUT->pix_url('t/groups') . '';
3110 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
3111 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
3112 $grouptitle = $str->groupsvisible
;
3113 $forcedgrouptitle = $str->forcedgroupsvisible
;
3114 $groupclass = 'editing_groupsvisible';
3115 $groupimage = $OUTPUT->pix_url('t/groupv') . '';
3116 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
3118 $grouptitle = $str->groupsnone
;
3119 $forcedgrouptitle = $str->forcedgroupsnone
;
3120 $groupclass = 'editing_groupsnone';
3121 $groupimage = $OUTPUT->pix_url('t/groupn') . '';
3122 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
3124 if ($mod->groupmodelink
) {
3125 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.'" href="'.$grouplink.'">'.
3126 '<img src="'.$groupimage.'" class="iconsmall" '.
3127 'alt="'.$grouptitle.'" /></a>';
3129 $groupmode = '<img title="'.$forcedgrouptitle.'"'.
3130 ' src="'.$groupimage.'" class="iconsmall" '.
3131 'alt="'.$forcedgrouptitle.'" />';
3137 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3139 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
3140 '&sesskey='.$sesskey.$section.'"><img'.
3141 ' src="'.$OUTPUT->pix_url('t/move') . '" class="iconsmall" '.
3142 ' alt="'.$str->move
.'" /></a>'."\n";
3144 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3145 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
3146 ' src="'.$OUTPUT->pix_url('t/up') . '" class="iconsmall" '.
3147 ' alt="'.$str->moveup
.'" /></a>'."\n".
3148 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3149 '&move=1&sesskey='.$sesskey.$section.'"><img'.
3150 ' src="'.$OUTPUT->pix_url('t/down') . '" class="iconsmall" '.
3151 ' alt="'.$str->movedown
.'" /></a>'."\n";
3158 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3160 if (right_to_left()) { // Exchange arrows on RTL
3161 $rightarrow = 't/left';
3162 $leftarrow = 't/right';
3164 $rightarrow = 't/right';
3165 $leftarrow = 't/left';
3169 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3170 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
3171 ' src="'.$OUTPUT->pix_url($leftarrow).'" class="iconsmall" '.
3172 ' alt="'.$str->moveleft
.'" /></a>'."\n";
3175 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3176 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
3177 ' src="'.$OUTPUT->pix_url($rightarrow).'" class="iconsmall" '.
3178 ' alt="'.$str->moveright
.'" /></a>'."\n";
3181 if (has_capability('moodle/role:assign', $modcontext)){
3182 $context = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3183 $assign = '<a class="editing_assign" title="'.$str->assign
.'" href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?contextid='.
3184 $context->id
.'"><img src="'.$OUTPUT->pix_url('i/roles') . '" alt="'.$str->assign
.'" class="iconsmall"/></a>';
3189 // Duplicate (require both target import caps to be able to duplicate, see modduplicate.php)
3190 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3191 if (has_all_capabilities($dupecaps, get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3192 $duplicatemodule = '<a class="editing_duplicate" title="'.$str->duplicate
.'" href="'.$path.'/mod.php?duplicate='.$mod->id
.
3193 '&sesskey='.$sesskey.$section.'"><img'.
3194 ' src="'.$OUTPUT->pix_url('t/copy') . '" class="iconsmall" '.
3195 ' alt="'.$str->duplicate
.'" /></a>'."\n";
3197 $duplicatemodule = '';
3200 return '<span class="commands">'."\n".$leftright.$move.
3201 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
3202 '&sesskey='.$sesskey.$section.'"><img'.
3203 ' src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" '.
3204 ' alt="'.$str->update
.'" /></a>'."\n".
3206 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
3207 '&sesskey='.$sesskey.$section.'"><img'.
3208 ' src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" '.
3209 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
3213 * given a course object with shortname & fullname, this function will
3214 * truncate the the number of chars allowed and add ... if it was too long
3216 function course_format_name ($course,$max=100) {
3218 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3219 $shortname = format_string($course->shortname
, true, array('context' => $context));
3220 $fullname = format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
3222 $str = $shortname.': '. $fullname;
3223 if (strlen($str) <= $max) {
3226 return $textlib->substr($str, 0, $max-3).'...';
3230 function update_restricted_mods($course, $mods) {
3233 /// Delete all the current restricted list
3234 $DB->delete_records('course_allowed_modules', array('course'=>$course->id
));
3236 if (empty($course->restrictmodules
)) {
3237 return; // We're done
3240 /// Insert the new list of restricted mods
3241 foreach ($mods as $mod) {
3243 continue; // this is the 'allow none' option
3245 $am = new stdClass();
3246 $am->course
= $course->id
;
3248 $DB->insert_record('course_allowed_modules',$am);
3253 * This function will take an int (module id) or a string (module name)
3254 * and return true or false, whether it's allowed in the given course (object)
3255 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3256 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3259 function course_allowed_module($course,$mod) {
3262 if (empty($course->restrictmodules
)) {
3266 // Admins and admin-like people who can edit everything can also add anything.
3267 // Originally there was a course:update test only, but it did not match the test in course edit form
3268 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3272 if (is_numeric($mod)) {
3274 } else if (is_string($mod)) {
3275 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3277 if (empty($modid)) {
3281 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id
, 'module'=>$modid));
3285 * Recursively delete category including all subcategories and courses.
3286 * @param stdClass $category
3287 * @param boolean $showfeedback display some notices
3288 * @return array return deleted courses
3290 function category_delete_full($category, $showfeedback=true) {
3292 require_once($CFG->libdir
.'/gradelib.php');
3293 require_once($CFG->libdir
.'/questionlib.php');
3294 require_once($CFG->dirroot
.'/cohort/lib.php');
3296 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3297 foreach ($children as $childcat) {
3298 category_delete_full($childcat, $showfeedback);
3302 $deletedcourses = array();
3303 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC')) {
3304 foreach ($courses as $course) {
3305 if (!delete_course($course, false)) {
3306 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname
);
3308 $deletedcourses[] = $course;
3312 // move or delete cohorts in this context
3313 cohort_delete_category($category);
3315 // now delete anything that may depend on course category context
3316 grade_course_category_delete($category->id
, 0, $showfeedback);
3317 if (!question_delete_course_category($category, 0, $showfeedback)) {
3318 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name
);
3321 // finally delete the category and it's context
3322 $DB->delete_records('course_categories', array('id'=>$category->id
));
3323 delete_context(CONTEXT_COURSECAT
, $category->id
);
3325 events_trigger('course_category_deleted', $category);
3327 return $deletedcourses;
3331 * Delete category, but move contents to another category.
3332 * @param object $ccategory
3333 * @param int $newparentid category id
3334 * @return bool status
3336 function category_delete_move($category, $newparentid, $showfeedback=true) {
3337 global $CFG, $DB, $OUTPUT;
3338 require_once($CFG->libdir
.'/gradelib.php');
3339 require_once($CFG->libdir
.'/questionlib.php');
3340 require_once($CFG->dirroot
.'/cohort/lib.php');
3342 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3346 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3347 foreach ($children as $childcat) {
3348 move_category($childcat, $newparentcat);
3352 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC', 'id')) {
3353 if (!move_courses(array_keys($courses), $newparentid)) {
3354 echo $OUTPUT->notification("Error moving courses");
3357 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
3360 // move or delete cohorts in this context
3361 cohort_delete_category($category);
3363 // now delete anything that may depend on course category context
3364 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
3365 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3366 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3370 // finally delete the category and it's context
3371 $DB->delete_records('course_categories', array('id'=>$category->id
));
3372 delete_context(CONTEXT_COURSECAT
, $category->id
);
3374 events_trigger('course_category_deleted', $category);
3376 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3382 * Efficiently moves many courses around while maintaining
3383 * sortorder in order.
3385 * @param array $courseids is an array of course ids
3386 * @param int $categoryid
3387 * @return bool success
3389 function move_courses($courseids, $categoryid) {
3390 global $CFG, $DB, $OUTPUT;
3392 if (empty($courseids)) {
3397 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3401 $courseids = array_reverse($courseids);
3402 $newparent = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3405 foreach ($courseids as $courseid) {
3406 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3407 $course = new stdClass();
3408 $course->id
= $courseid;
3409 $course->category
= $category->id
;
3410 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
3411 if ($category->visible
== 0) {
3412 // hide the course when moving into hidden category,
3413 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3414 $course->visible
= 0;
3417 $DB->update_record('course', $course);
3419 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3420 context_moved($context, $newparent);
3423 fix_course_sortorder();
3429 * Hide course category and child course and subcategories
3430 * @param stdClass $category
3433 function course_category_hide($category) {
3436 $category->visible
= 0;
3437 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id
));
3438 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id
));
3439 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id
)); // store visible flag so that we can return to it if we immediately unhide
3440 $DB->set_field('course', 'visible', 0, array('category' => $category->id
));
3441 // get all child categories and hide too
3442 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3443 foreach ($subcats as $cat) {
3444 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id'=>$cat->id
));
3445 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id
));
3446 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
3447 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
3453 * Show course category and child course and subcategories
3454 * @param stdClass $category
3457 function course_category_show($category) {
3460 $category->visible
= 1;
3461 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id
));
3462 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id
));
3463 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id
));
3464 // get all child categories and unhide too
3465 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3466 foreach ($subcats as $cat) {
3467 if ($cat->visibleold
) {
3468 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id
));
3470 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
3476 * Efficiently moves a category - NOTE that this can have
3477 * a huge impact access-control-wise...
3479 function move_category($category, $newparentcat) {
3482 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3485 if (empty($newparentcat->id
)) {
3486 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id
));
3488 $newparent = get_context_instance(CONTEXT_SYSTEM
);
3491 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id'=>$category->id
));
3492 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
3494 if (!$newparentcat->visible
and $category->visible
) {
3495 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3500 context_moved($context, $newparent);
3502 // now make it last in new category
3503 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id'=>$category->id
));
3505 // and fix the sortorders
3506 fix_course_sortorder();
3509 course_category_hide($category);
3514 * Returns the display name of the given section that the course prefers.
3516 * This function utilizes a callback that can be implemented within the course
3517 * formats lib.php file to customize the display name that is used to reference
3520 * By default (if callback is not defined) the method
3521 * {@see get_numeric_section_name} is called instead.
3523 * @param stdClass $course The course to get the section name for
3524 * @param stdClass $section Section object from database
3525 * @return Display name that the course format prefers, e.g. "Week 2"
3527 * @see get_generic_section_name
3529 function get_section_name(stdClass
$course, stdClass
$section) {
3532 /// Inelegant hack for bug 3408
3533 if ($course->format
== 'site') {
3534 return get_string('site');
3537 // Use course formatter callback if it exists
3538 $namingfile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3539 $namingfunction = 'callback_'.$course->format
.'_get_section_name';
3540 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3541 require_once $namingfile;
3543 if (function_exists($namingfunction)) {
3544 return $namingfunction($course, $section);
3547 // else, default behavior:
3548 return get_generic_section_name($course->format
, $section);
3552 * Gets the generic section name for a courses section.
3554 * @param string $format Course format ID e.g. 'weeks' $course->format
3555 * @param stdClass $section Section object from database
3556 * @return Display name that the course format prefers, e.g. "Week 2"
3558 function get_generic_section_name($format, stdClass
$section) {
3559 return get_string('sectionname', "format_$format") . ' ' . $section->section
;
3563 function course_format_uses_sections($format) {
3566 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3567 $featurefunction = 'callback_'.$format.'_uses_sections';
3568 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3569 require_once $featurefile;
3571 if (function_exists($featurefunction)) {
3572 return $featurefunction();
3579 * Returns the information about the ajax support in the given source format
3581 * The returned object's property (boolean)capable indicates that
3582 * the course format supports Moodle course ajax features.
3583 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3585 * @param string $format
3588 function course_format_ajax_support($format) {
3591 // set up default values
3592 $ajaxsupport = new stdClass();
3593 $ajaxsupport->capable
= false;
3594 $ajaxsupport->testedbrowsers
= array();
3596 // get the information from the course format library
3597 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3598 $featurefunction = 'callback_'.$format.'_ajax_support';
3599 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3600 require_once $featurefile;
3602 if (function_exists($featurefunction)) {
3603 $formatsupport = $featurefunction();
3604 if (isset($formatsupport->capable
)) {
3605 $ajaxsupport->capable
= $formatsupport->capable
;
3607 if (is_array($formatsupport->testedbrowsers
)) {
3608 $ajaxsupport->testedbrowsers
= $formatsupport->testedbrowsers
;
3612 return $ajaxsupport;
3616 * Can the current user delete this course?
3617 * Course creators have exception,
3618 * 1 day after the creation they can sill delete the course.
3619 * @param int $courseid
3622 function can_delete_course($courseid) {
3625 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3627 if (has_capability('moodle/course:delete', $context)) {
3631 // hack: now try to find out if creator created this course recently (1 day)
3632 if (!has_capability('moodle/course:create', $context)) {
3636 $since = time() - 60*60*24;
3638 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3639 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3641 return $DB->record_exists_select('log', $select, $params);
3645 * Save the Your name for 'Some role' strings.
3647 * @param integer $courseid the id of this course.
3648 * @param array $data the data that came from the course settings form.
3650 function save_local_role_names($courseid, $data) {
3652 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3654 foreach ($data as $fieldname => $value) {
3655 if (strpos($fieldname, 'role_') !== 0) {
3658 list($ignored, $roleid) = explode('_', $fieldname);
3660 // make up our mind whether we want to delete, update or insert
3662 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
3664 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
3665 $rolename->name
= $value;
3666 $DB->update_record('role_names', $rolename);
3669 $rolename = new stdClass
;
3670 $rolename->contextid
= $context->id
;
3671 $rolename->roleid
= $roleid;
3672 $rolename->name
= $value;
3673 $DB->insert_record('role_names', $rolename);
3679 * Create a course and either return a $course object
3681 * Please note this functions does not verify any access control,
3682 * the calling code is responsible for all validation (usually it is the form definition).
3684 * @param array $editoroptions course description editor options
3685 * @param object $data - all the data needed for an entry in the 'course' table
3686 * @return object new course instance
3688 function create_course($data, $editoroptions = NULL) {
3691 //check the categoryid - must be given for all new courses
3692 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
3694 //check if the shortname already exist
3695 if (!empty($data->shortname
)) {
3696 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
3697 throw new moodle_exception('shortnametaken');
3701 //check if the id number already exist
3702 if (!empty($data->idnumber
)) {
3703 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
3704 throw new moodle_exception('idnumbertaken');
3708 $data->timecreated
= time();
3709 $data->timemodified
= $data->timecreated
;
3711 // place at beginning of any category
3712 $data->sortorder
= 0;
3714 if ($editoroptions) {
3715 // summary text is updated later, we need context to store the files first
3716 $data->summary
= '';
3717 $data->summary_format
= FORMAT_HTML
;
3720 if (!isset($data->visible
)) {
3721 // data not from form, add missing visibility info
3722 $data->visible
= $category->visible
;
3724 $data->visibleold
= $data->visible
;
3726 $newcourseid = $DB->insert_record('course', $data);
3727 $context = get_context_instance(CONTEXT_COURSE
, $newcourseid, MUST_EXIST
);
3729 if ($editoroptions) {
3730 // Save the files used in the summary editor and store
3731 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3732 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
3733 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
3736 $course = $DB->get_record('course', array('id'=>$newcourseid));
3739 blocks_add_default_course_blocks($course);
3741 $section = new stdClass();
3742 $section->course
= $course->id
; // Create a default section.
3743 $section->section
= 0;
3744 $section->summaryformat
= FORMAT_HTML
;
3745 $DB->insert_record('course_sections', $section);
3747 fix_course_sortorder();
3749 // update module restrictions
3750 if ($course->restrictmodules
) {
3751 if (isset($data->allowedmods
)) {
3752 update_restricted_mods($course, $data->allowedmods
);
3754 if (!empty($CFG->defaultallowedmodules
)) {
3755 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules
));
3760 // new context created - better mark it as dirty
3761 mark_context_dirty($context->path
);
3763 // Save any custom role names.
3764 save_local_role_names($course->id
, (array)$data);
3766 // set up enrolments
3767 enrol_course_updated(true, $course, $data);
3769 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3772 events_trigger('course_created', $course);
3780 * Please note this functions does not verify any access control,
3781 * the calling code is responsible for all validation (usually it is the form definition).
3783 * @param object $data - all the data needed for an entry in the 'course' table
3784 * @param array $editoroptions course description editor options
3787 function update_course($data, $editoroptions = NULL) {
3790 $data->timemodified
= time();
3792 $oldcourse = $DB->get_record('course', array('id'=>$data->id
), '*', MUST_EXIST
);
3793 $context = get_context_instance(CONTEXT_COURSE
, $oldcourse->id
);
3795 if ($editoroptions) {
3796 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3799 if (!isset($data->category
) or empty($data->category
)) {
3800 // prevent nulls and 0 in category field
3801 unset($data->category
);
3803 $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
3805 if (!isset($data->visible
)) {
3806 // data not from form, add missing visibility info
3807 $data->visible
= $oldcourse->visible
;
3810 if ($data->visible
!= $oldcourse->visible
) {
3811 // reset the visibleold flag when manually hiding/unhiding course
3812 $data->visibleold
= $data->visible
;
3815 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
3816 if (empty($newcategory->visible
)) {
3817 // make sure when moving into hidden category the course is hidden automatically
3823 // Update with the new data
3824 $DB->update_record('course', $data);
3826 $course = $DB->get_record('course', array('id'=>$data->id
));
3829 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3830 context_moved($context, $newparent);
3833 fix_course_sortorder();
3835 // Test for and remove blocks which aren't appropriate anymore
3836 blocks_remove_inappropriate($course);
3838 // update module restrictions
3839 if (isset($data->allowedmods
)) {
3840 update_restricted_mods($course, $data->allowedmods
);
3843 // Save any custom role names.
3844 save_local_role_names($course->id
, $data);
3846 // update enrol settings
3847 enrol_course_updated(false, $course, $data);
3849 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3852 events_trigger('course_updated', $course);
3856 * Average number of participants
3859 function average_number_of_participants() {
3862 //count total of enrolments for visible course (except front page)
3863 $sql = 'SELECT COUNT(*) FROM (
3864 SELECT DISTINCT ue.userid, e.courseid
3865 FROM {user_enrolments} ue, {enrol} e, {course} c
3866 WHERE ue.enrolid = e.id
3867 AND e.courseid <> :siteid
3868 AND c.id = e.courseid
3869 AND c.visible = 1) as total';
3870 $params = array('siteid' => $SITE->id
);
3871 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3874 //count total of visible courses (minus front page)
3875 $coursetotal = $DB->count_records('course', array('visible' => 1));
3876 $coursetotal = $coursetotal - 1 ;
3878 //average of enrolment
3879 if (empty($coursetotal)) {
3880 $participantaverage = 0;
3882 $participantaverage = $enrolmenttotal / $coursetotal;
3885 return $participantaverage;
3889 * Average number of course modules
3892 function average_number_of_courses_modules() {
3895 //count total of visible course module (except front page)
3896 $sql = 'SELECT COUNT(*) FROM (
3897 SELECT cm.course, cm.module
3898 FROM {course} c, {course_modules} cm
3899 WHERE c.id = cm.course
3902 AND c.visible = 1) as total';
3903 $params = array('siteid' => $SITE->id
);
3904 $moduletotal = $DB->count_records_sql($sql, $params);
3907 //count total of visible courses (minus front page)
3908 $coursetotal = $DB->count_records('course', array('visible' => 1));
3909 $coursetotal = $coursetotal - 1 ;
3911 //average of course module
3912 if (empty($coursetotal)) {
3913 $coursemoduleaverage = 0;
3915 $coursemoduleaverage = $moduletotal / $coursetotal;
3918 return $coursemoduleaverage;
3922 * This class pertains to course requests and contains methods associated with
3923 * create, approving, and removing course requests.
3925 * Please note we do not allow embedded images here because there is no context
3926 * to store them with proper access control.
3928 * @copyright 2009 Sam Hemelryk
3929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3932 * @property-read int $id
3933 * @property-read string $fullname
3934 * @property-read string $shortname
3935 * @property-read string $summary
3936 * @property-read int $summaryformat
3937 * @property-read int $summarytrust
3938 * @property-read string $reason
3939 * @property-read int $requester
3941 class course_request
{
3944 * This is the stdClass that stores the properties for the course request
3945 * and is externally accessed through the __get magic method
3948 protected $properties;
3951 * An array of options for the summary editor used by course request forms.
3952 * This is initially set by {@link summary_editor_options()}
3956 protected static $summaryeditoroptions;
3959 * Static function to prepare the summary editor for working with a course
3963 * @param null|stdClass $data Optional, an object containing the default values
3964 * for the form, these may be modified when preparing the
3965 * editor so this should be called before creating the form
3966 * @return stdClass An object that can be used to set the default values for
3969 public static function prepare($data=null) {
3970 if ($data === null) {
3971 $data = new stdClass
;
3973 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
3978 * Static function to create a new course request when passed an array of properties
3981 * This function also handles saving any files that may have been used in the editor
3984 * @param stdClass $data
3985 * @return course_request The newly created course request
3987 public static function create($data) {
3988 global $USER, $DB, $CFG;
3989 $data->requester
= $USER->id
;
3991 // Summary is a required field so copy the text over
3992 $data->summary
= $data->summary_editor
['text'];
3993 $data->summaryformat
= $data->summary_editor
['format'];
3995 $data->id
= $DB->insert_record('course_request', $data);
3997 // Create a new course_request object and return it
3998 $request = new course_request($data);
4000 // Notify the admin if required.
4001 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
4004 $a->link
= "$CFG->wwwroot/course/pending.php";
4005 $a->user
= fullname($USER);
4006 $subject = get_string('courserequest');
4007 $message = get_string('courserequestnotifyemail', 'admin', $a);
4008 foreach ($users as $user) {
4009 $request->notify($user, $USER, 'courserequested', $subject, $message);
4017 * Returns an array of options to use with a summary editor
4019 * @uses course_request::$summaryeditoroptions
4020 * @return array An array of options to use with the editor
4022 public static function summary_editor_options() {
4024 if (self
::$summaryeditoroptions === null) {
4025 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4027 return self
::$summaryeditoroptions;
4031 * Loads the properties for this course request object. Id is required and if
4032 * only id is provided then we load the rest of the properties from the database
4034 * @param stdClass|int $properties Either an object containing properties
4035 * or the course_request id to load
4037 public function __construct($properties) {
4039 if (empty($properties->id
)) {
4040 if (empty($properties)) {
4041 throw new coding_exception('You must provide a course request id when creating a course_request object');
4044 $properties = new stdClass
;
4045 $properties->id
= (int)$id;
4048 if (empty($properties->requester
)) {
4049 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
4050 print_error('unknowncourserequest');
4053 $this->properties
= $properties;
4055 $this->properties
->collision
= null;
4059 * Returns the requested property
4061 * @param string $key
4064 public function __get($key) {
4065 return $this->properties
->$key;
4069 * Override this to ensure empty($request->blah) calls return a reliable answer...
4071 * This is required because we define the __get method
4074 * @return bool True is it not empty, false otherwise
4076 public function __isset($key) {
4077 return (!empty($this->properties
->$key));
4081 * Returns the user who requested this course
4083 * Uses a static var to cache the results and cut down the number of db queries
4085 * @staticvar array $requesters An array of cached users
4086 * @return stdClass The user who requested the course
4088 public function get_requester() {
4090 static $requesters= array();
4091 if (!array_key_exists($this->properties
->requester
, $requesters)) {
4092 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
4094 return $requesters[$this->properties
->requester
];
4098 * Checks that the shortname used by the course does not conflict with any other
4099 * courses that exist
4101 * @param string|null $shortnamemark The string to append to the requests shortname
4102 * should a conflict be found
4103 * @return bool true is there is a conflict, false otherwise
4105 public function check_shortname_collision($shortnamemark = '[*]') {
4108 if ($this->properties
->collision
!== null) {
4109 return $this->properties
->collision
;
4112 if (empty($this->properties
->shortname
)) {
4113 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
4114 $this->properties
->collision
= false;
4115 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
4116 if (!empty($shortnamemark)) {
4117 $this->properties
->shortname
.= ' '.$shortnamemark;
4119 $this->properties
->collision
= true;
4121 $this->properties
->collision
= false;
4123 return $this->properties
->collision
;
4127 * This function approves the request turning it into a course
4129 * This function converts the course request into a course, at the same time
4130 * transferring any files used in the summary to the new course and then removing
4131 * the course request and the files associated with it.
4133 * @return int The id of the course that was created from this request
4135 public function approve() {
4136 global $CFG, $DB, $USER;
4138 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
4140 $category = get_course_category($CFG->defaultrequestcategory
);
4141 $courseconfig = get_config('moodlecourse');
4143 // Transfer appropriate settings
4144 $data = clone($this->properties
);
4146 unset($data->reason
);
4147 unset($data->requester
);
4150 $data->category
= $category->id
;
4151 $data->sortorder
= $category->sortorder
; // place as the first in category
4153 // Set misc settings
4154 $data->requested
= 1;
4155 if (!empty($CFG->restrictmodulesfor
) && $CFG->restrictmodulesfor
!= 'none' && !empty($CFG->restrictbydefault
)) {
4156 $data->restrictmodules
= 1;
4159 // Apply course default settings
4160 $data->format
= $courseconfig->format
;
4161 $data->numsections
= $courseconfig->numsections
;
4162 $data->hiddensections
= $courseconfig->hiddensections
;
4163 $data->newsitems
= $courseconfig->newsitems
;
4164 $data->showgrades
= $courseconfig->showgrades
;
4165 $data->showreports
= $courseconfig->showreports
;
4166 $data->maxbytes
= $courseconfig->maxbytes
;
4167 $data->groupmode
= $courseconfig->groupmode
;
4168 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
4169 $data->visible
= $courseconfig->visible
;
4170 $data->visibleold
= $data->visible
;
4171 $data->lang
= $courseconfig->lang
;
4173 $course = create_course($data);
4174 $context = get_context_instance(CONTEXT_COURSE
, $course->id
, MUST_EXIST
);
4176 // add enrol instances
4177 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
4178 if ($manual = enrol_get_plugin('manual')) {
4179 $manual->add_default_instance($course);
4183 // enrol the requester as teacher if necessary
4184 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4185 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
4190 $a = new stdClass();
4191 $a->name
= format_string($course->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, $course->id
)));
4192 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
4193 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4199 * Reject a course request
4201 * This function rejects a course request, emailing the requesting user the
4202 * provided notice and then removing the request from the database
4204 * @param string $notice The message to display to the user
4206 public function reject($notice) {
4208 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
4209 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4214 * Deletes the course request and any associated files
4216 public function delete() {
4218 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
4222 * Send a message from one user to another using events_trigger
4224 * @param object $touser
4225 * @param object $fromuser
4226 * @param string $name
4227 * @param string $subject
4228 * @param string $message
4230 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4231 $eventdata = new stdClass();
4232 $eventdata->component
= 'moodle';
4233 $eventdata->name
= $name;
4234 $eventdata->userfrom
= $fromuser;
4235 $eventdata->userto
= $touser;
4236 $eventdata->subject
= $subject;
4237 $eventdata->fullmessage
= $message;
4238 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
4239 $eventdata->fullmessagehtml
= '';
4240 $eventdata->smallmessage
= '';
4241 $eventdata->notification
= 1;
4242 message_send($eventdata);
4247 * Return a list of page types
4248 * @param string $pagetype current page type
4249 * @param stdClass $parentcontext Block's parent context
4250 * @param stdClass $currentcontext Current context of block
4252 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4253 // if above course context ,display all course fomats
4254 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id
);
4255 if ($course->id
== SITEID
) {
4256 return array('*'=>get_string('page-x', 'pagetype'));
4258 return array('*'=>get_string('page-x', 'pagetype'),
4259 'course-*'=>get_string('page-course-x', 'pagetype'),
4260 'course-view-*'=>get_string('page-course-view-x', 'pagetype')