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('fullnamecourse'),
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('fullnamecourse')."</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 echo "<td class=\"r$row c0\" >\n";
502 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course
]."</a>\n";
505 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
506 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
507 echo "<td class=\"r$row c2\" >\n";
508 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
509 echo $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
511 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
512 echo "<td class=\"r$row c3\" >\n";
513 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
515 echo "<td class=\"r$row c4\">\n";
516 echo $log->action
.': '.$log->module
;
518 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
523 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
527 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
528 $modid, $modaction, $groupid) {
531 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
532 get_string('fullnamecourse')."\t".get_string('action')."\t".get_string('info');
534 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
535 $modname, $modid, $modaction, $groupid)) {
541 if ($course->id
== SITEID
) {
543 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
544 foreach ($ccc as $cc) {
545 $courses[$cc->id
] = $cc->shortname
;
549 $courses[$course->id
] = $course->shortname
;
554 $tt = getdate(time());
555 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
557 $strftimedatetime = get_string("strftimedatetime");
559 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
561 header("Content-Type: application/download\n");
562 header("Content-Disposition: attachment; filename=$filename");
563 header("Expires: 0");
564 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
565 header("Pragma: public");
567 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
570 if (empty($logs['logs'])) {
574 foreach ($logs['logs'] as $log) {
575 if (isset($ldcache[$log->module
][$log->action
])) {
576 $ld = $ldcache[$log->module
][$log->action
];
578 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
579 $ldcache[$log->module
][$log->action
] = $ld;
581 if ($ld && !empty($log->info
)) {
582 // ugly hack to make sure fullname is shown correctly
583 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
584 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
586 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
591 $log->info
= format_string($log->info
);
592 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
594 $firstField = $courses[$log->course
];
595 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
596 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
597 $text = implode("\t", $row);
604 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
605 $modid, $modaction, $groupid) {
609 require_once("$CFG->libdir/excellib.class.php");
611 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
612 $modname, $modid, $modaction, $groupid)) {
618 if ($course->id
== SITEID
) {
620 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
621 foreach ($ccc as $cc) {
622 $courses[$cc->id
] = $cc->shortname
;
626 $courses[$course->id
] = $course->shortname
;
631 $tt = getdate(time());
632 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
634 $strftimedatetime = get_string("strftimedatetime");
636 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
637 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
640 $workbook = new MoodleExcelWorkbook('-');
641 $workbook->send($filename);
643 $worksheet = array();
644 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
645 get_string('fullnamecourse'), get_string('action'), get_string('info'));
647 // Creating worksheets
648 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
649 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
650 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
651 $worksheet[$wsnumber]->set_column(1, 1, 30);
652 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
653 userdate(time(), $strftimedatetime));
655 foreach ($headers as $item) {
656 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
661 if (empty($logs['logs'])) {
666 $formatDate =& $workbook->add_format();
667 $formatDate->set_num_format(get_string('log_excel_date_format'));
669 $row = FIRSTUSEDEXCELROW
;
671 $myxls =& $worksheet[$wsnumber];
672 foreach ($logs['logs'] as $log) {
673 if (isset($ldcache[$log->module
][$log->action
])) {
674 $ld = $ldcache[$log->module
][$log->action
];
676 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
677 $ldcache[$log->module
][$log->action
] = $ld;
679 if ($ld && !empty($log->info
)) {
680 // ugly hack to make sure fullname is shown correctly
681 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
682 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
684 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
689 $log->info
= format_string($log->info
);
690 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
693 if ($row > EXCELROWS
) {
695 $myxls =& $worksheet[$wsnumber];
696 $row = FIRSTUSEDEXCELROW
;
700 $myxls->write($row, 0, $courses[$log->course
], '');
701 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
702 $myxls->write($row, 2, $log->ip
, '');
703 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
704 $myxls->write($row, 3, $fullname, '');
705 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
706 $myxls->write($row, 5, $log->info
, '');
715 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
716 $modid, $modaction, $groupid) {
720 require_once("$CFG->libdir/odslib.class.php");
722 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
723 $modname, $modid, $modaction, $groupid)) {
729 if ($course->id
== SITEID
) {
731 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
732 foreach ($ccc as $cc) {
733 $courses[$cc->id
] = $cc->shortname
;
737 $courses[$course->id
] = $course->shortname
;
742 $tt = getdate(time());
743 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
745 $strftimedatetime = get_string("strftimedatetime");
747 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
748 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
751 $workbook = new MoodleODSWorkbook('-');
752 $workbook->send($filename);
754 $worksheet = array();
755 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
756 get_string('fullnamecourse'), get_string('action'), get_string('info'));
758 // Creating worksheets
759 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
760 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
761 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
762 $worksheet[$wsnumber]->set_column(1, 1, 30);
763 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
764 userdate(time(), $strftimedatetime));
766 foreach ($headers as $item) {
767 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
772 if (empty($logs['logs'])) {
777 $formatDate =& $workbook->add_format();
778 $formatDate->set_num_format(get_string('log_excel_date_format'));
780 $row = FIRSTUSEDEXCELROW
;
782 $myxls =& $worksheet[$wsnumber];
783 foreach ($logs['logs'] as $log) {
784 if (isset($ldcache[$log->module
][$log->action
])) {
785 $ld = $ldcache[$log->module
][$log->action
];
787 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
788 $ldcache[$log->module
][$log->action
] = $ld;
790 if ($ld && !empty($log->info
)) {
791 // ugly hack to make sure fullname is shown correctly
792 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
793 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
795 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
800 $log->info
= format_string($log->info
);
801 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
804 if ($row > EXCELROWS
) {
806 $myxls =& $worksheet[$wsnumber];
807 $row = FIRSTUSEDEXCELROW
;
811 $myxls->write_string($row, 0, $courses[$log->course
]);
812 $myxls->write_date($row, 1, $log->time
);
813 $myxls->write_string($row, 2, $log->ip
);
814 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
815 $myxls->write_string($row, 3, $fullname);
816 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
817 $myxls->write_string($row, 5, $log->info
);
827 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
829 if (empty($CFG->gdversion
)) {
830 echo "(".get_string("gdneed").")";
832 // MDL-10818, do not display broken graph when user has no permission to view graph
833 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE
, $course->id
)) ||
834 ($course->showreports
and $USER->id
== $userid)) {
835 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
836 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
842 function print_overview($courses, array $remote_courses=array()) {
843 global $CFG, $USER, $DB, $OUTPUT;
845 $htmlarray = array();
846 if ($modules = $DB->get_records('modules')) {
847 foreach ($modules as $mod) {
848 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
849 include_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
850 $fname = $mod->name
.'_print_overview';
851 if (function_exists($fname)) {
852 $fname($courses,$htmlarray);
857 foreach ($courses as $course) {
858 echo $OUTPUT->box_start('coursebox');
859 $attributes = array('title' => s($course->fullname
));
860 if (empty($course->visible
)) {
861 $attributes['class'] = 'dimmed';
863 echo $OUTPUT->heading(html_writer
::link(
864 new moodle_url('/course/view.php', array('id' => $course->id
)), format_string($course->fullname
), $attributes), 3);
865 if (array_key_exists($course->id
,$htmlarray)) {
866 foreach ($htmlarray[$course->id
] as $modname => $html) {
870 echo $OUTPUT->box_end();
873 if (!empty($remote_courses)) {
874 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
876 foreach ($remote_courses as $course) {
877 echo $OUTPUT->box_start('coursebox');
878 $attributes = array('title' => s($course->fullname
));
879 echo $OUTPUT->heading(html_writer
::link(
880 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid
, 'wantsurl' => '/course/view.php?id='.$course->remoteid
)),
881 format_string($course->shortname
),
882 $attributes) . ' (' . format_string($course->hostname
) . ')', 3);
883 echo $OUTPUT->box_end();
889 * This function trawls through the logs looking for
890 * anything new since the user's last login
892 function print_recent_activity($course) {
893 // $course is an object
894 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
896 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
898 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
900 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD
, -2); // better db caching for guests - 100 seconds
902 if (!isguestuser()) {
903 if (!empty($USER->lastcourseaccess
[$course->id
])) {
904 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
905 $timestart = $USER->lastcourseaccess
[$course->id
];
910 echo '<div class="activitydate">';
911 echo get_string('activitysince', '', userdate($timestart));
913 echo '<div class="activityhead">';
915 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
921 /// Firstly, have there been any new enrolments?
923 $users = get_recent_enrolments($course->id
, $timestart);
925 //Accessibility: new users now appear in an <OL> list.
927 echo '<div class="newusers">';
928 echo $OUTPUT->heading(get_string("newusers").':', 3);
930 echo "<ol class=\"list\">\n";
931 foreach ($users as $user) {
932 $fullname = fullname($user, $viewfullnames);
933 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
935 echo "</ol>\n</div>\n";
938 /// Next, have there been any modifications to the course structure?
940 $modinfo =& get_fast_modinfo($course);
942 $changelist = array();
944 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
945 module = 'course' AND
946 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
947 array($timestart, $course->id
), "id ASC");
950 $actions = array('add mod', 'update mod', 'delete mod');
951 $newgones = array(); // added and later deleted items
952 foreach ($logs as $key => $log) {
953 if (!in_array($log->action
, $actions)) {
956 $info = explode(' ', $log->info
);
958 // note: in most cases I replaced hardcoding of label with use of
959 // $cm->has_view() but it was not possible to do this here because
960 // we don't necessarily have the $cm for it
961 if ($info[0] == 'label') { // Labels are ignored in recent activity
965 if (count($info) != 2) {
966 debugging("Incorrect log entry info: id = ".$log->id
, DEBUG_DEVELOPER
);
971 $instanceid = $info[1];
973 if ($log->action
== 'delete mod') {
974 // unfortunately we do not know if the mod was visible
975 if (!array_key_exists($log->info
, $newgones)) {
976 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
977 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
980 if (!isset($modinfo->instances
[$modname][$instanceid])) {
981 if ($log->action
== 'add mod') {
982 // do not display added and later deleted activities
983 $newgones[$log->info
] = true;
987 $cm = $modinfo->instances
[$modname][$instanceid];
988 if (!$cm->uservisible
) {
992 if ($log->action
== 'add mod') {
993 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
994 $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>");
996 } else if ($log->action
== 'update mod' and empty($changelist[$log->info
])) {
997 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
998 $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>");
1004 if (!empty($changelist)) {
1005 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1007 foreach ($changelist as $changeinfo => $change) {
1008 echo '<p class="activity">'.$change['text'].'</p>';
1012 /// Now display new things from each module
1014 $usedmodules = array();
1015 foreach($modinfo->cms
as $cm) {
1016 if (isset($usedmodules[$cm->modname
])) {
1019 if (!$cm->uservisible
) {
1022 $usedmodules[$cm->modname
] = $cm->modname
;
1025 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1026 if (file_exists($CFG->dirroot
.'/mod/'.$modname.'/lib.php')) {
1027 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
1028 $print_recent_activity = $modname.'_print_recent_activity';
1029 if (function_exists($print_recent_activity)) {
1030 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1031 $content = $print_recent_activity($course, $viewfullnames, $timestart) ||
$content;
1034 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1039 echo '<p class="message">'.get_string('nothingnew').'</p>';
1044 * For a given course, returns an array of course activity objects
1045 * Each item in the array contains he following properties:
1047 function get_array_of_activities($courseid) {
1048 // cm - course module id
1049 // mod - name of the module (eg forum)
1050 // section - the number of the section (eg week or topic)
1051 // name - the name of the instance
1052 // visible - is the instance visible or not
1053 // groupingid - grouping id
1054 // groupmembersonly - is this instance visible to group members only
1055 // extra - contains extra string to include in any link
1057 if(!empty($CFG->enableavailability
)) {
1058 require_once($CFG->libdir
.'/conditionlib.php');
1061 $course = $DB->get_record('course', array('id'=>$courseid));
1063 if (empty($course)) {
1064 throw new moodle_exception('courseidnotfound');
1069 $rawmods = get_course_mods($courseid);
1070 if (empty($rawmods)) {
1071 return $mod; // always return array
1074 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1075 foreach ($sections as $section) {
1076 if (!empty($section->sequence
)) {
1077 $sequence = explode(",", $section->sequence
);
1078 foreach ($sequence as $seq) {
1079 if (empty($rawmods[$seq])) {
1082 $mod[$seq]->id
= $rawmods[$seq]->instance
;
1083 $mod[$seq]->cm
= $rawmods[$seq]->id
;
1084 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
1086 // Oh dear. Inconsistent names left here for backward compatibility.
1087 $mod[$seq]->section
= $section->section
;
1088 $mod[$seq]->sectionid
= $rawmods[$seq]->section
;
1090 $mod[$seq]->module
= $rawmods[$seq]->module
;
1091 $mod[$seq]->added
= $rawmods[$seq]->added
;
1092 $mod[$seq]->score
= $rawmods[$seq]->score
;
1093 $mod[$seq]->idnumber
= $rawmods[$seq]->idnumber
;
1094 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
1095 $mod[$seq]->visibleold
= $rawmods[$seq]->visibleold
;
1096 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
1097 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
1098 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
1099 $mod[$seq]->indent
= $rawmods[$seq]->indent
;
1100 $mod[$seq]->completion
= $rawmods[$seq]->completion
;
1101 $mod[$seq]->extra
= "";
1102 $mod[$seq]->completiongradeitemnumber
=
1103 $rawmods[$seq]->completiongradeitemnumber
;
1104 $mod[$seq]->completionview
= $rawmods[$seq]->completionview
;
1105 $mod[$seq]->completionexpected
= $rawmods[$seq]->completionexpected
;
1106 $mod[$seq]->availablefrom
= $rawmods[$seq]->availablefrom
;
1107 $mod[$seq]->availableuntil
= $rawmods[$seq]->availableuntil
;
1108 $mod[$seq]->showavailability
= $rawmods[$seq]->showavailability
;
1109 if (!empty($CFG->enableavailability
)) {
1110 condition_info
::fill_availability_conditions($rawmods[$seq]);
1111 $mod[$seq]->conditionscompletion
= $rawmods[$seq]->conditionscompletion
;
1112 $mod[$seq]->conditionsgrade
= $rawmods[$seq]->conditionsgrade
;
1115 $modname = $mod[$seq]->mod
;
1116 $functionname = $modname."_get_coursemodule_info";
1118 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1122 include_once("$CFG->dirroot/mod/$modname/lib.php");
1124 if (function_exists($functionname)) {
1125 if ($info = $functionname($rawmods[$seq])) {
1126 if (!empty($info->icon
)) {
1127 $mod[$seq]->icon
= $info->icon
;
1129 if (!empty($info->iconcomponent
)) {
1130 $mod[$seq]->iconcomponent
= $info->iconcomponent
;
1132 if (!empty($info->name
)) {
1133 $mod[$seq]->name
= $info->name
;
1135 if ($info instanceof cached_cm_info
) {
1136 // When using cached_cm_info you can include three new fields
1137 // that aren't available for legacy code
1138 if (!empty($info->content
)) {
1139 $mod[$seq]->content
= $info->content
;
1141 if (!empty($info->extraclasses
)) {
1142 $mod[$seq]->extraclasses
= $info->extraclasses
;
1144 if (!empty($info->onclick
)) {
1145 $mod[$seq]->onclick
= $info->onclick
;
1147 if (!empty($info->customdata
)) {
1148 $mod[$seq]->customdata
= $info->customdata
;
1151 // When using a stdclass, the (horrible) deprecated ->extra field
1152 // is available for BC
1153 if (!empty($info->extra
)) {
1154 $mod[$seq]->extra
= $info->extra
;
1159 if (!isset($mod[$seq]->name
)) {
1160 $mod[$seq]->name
= $DB->get_field($rawmods[$seq]->modname
, "name", array("id"=>$rawmods[$seq]->instance
));
1163 // Minimise the database size by unsetting default options when they are
1164 // 'empty'. This list corresponds to code in the cm_info constructor.
1165 foreach(array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1166 'indent', 'completion', 'extra', 'extraclasses', 'onclick', 'content',
1167 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1168 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1169 'completionview', 'completionexpected', 'score') as $property) {
1170 if (property_exists($mod[$seq], $property) &&
1171 empty($mod[$seq]->{$property})) {
1172 unset($mod[$seq]->{$property});
1175 // Special case: this value is usually set to null, but may be 0
1176 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1177 is_null($mod[$seq]->completiongradeitemnumber
)) {
1178 unset($mod[$seq]->completiongradeitemnumber
);
1189 * Returns a number of useful structures for course displays
1191 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1192 global $CFG, $DB, $COURSE;
1194 $mods = array(); // course modules indexed by id
1195 $modnames = array(); // all course module names (except resource!)
1196 $modnamesplural= array(); // all course module names (plural form)
1197 $modnamesused = array(); // course module names used
1199 if ($allmods = $DB->get_records("modules")) {
1200 foreach ($allmods as $mod) {
1201 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1204 if ($mod->visible
) {
1205 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1206 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1209 textlib_get_instance()->asort($modnames);
1211 print_error("nomodules", 'debug');
1214 $course = ($courseid==$COURSE->id
) ?
$COURSE : $DB->get_record('course',array('id'=>$courseid));
1215 $modinfo = get_fast_modinfo($course);
1217 if ($rawmods=$modinfo->cms
) {
1218 foreach($rawmods as $mod) { // Index the mods
1219 if (empty($modnames[$mod->modname
])) {
1222 $mods[$mod->id
] = $mod;
1223 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1224 if (!$mod->visible
and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1228 if (!groups_course_module_visible($mod)) {
1231 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1233 if ($modnamesused) {
1234 textlib_get_instance()->asort($modnamesused);
1240 * Returns an array of sections for the requested course id
1242 * This function stores the sections against the course id within a staticvar encase
1243 * of subsequent requests. This is used all over + in some standard libs and course
1244 * format callbacks so subsequent requests are a reality.
1246 * @staticvar array $coursesections
1247 * @param int $courseid
1248 * @return array Array of sections
1250 function get_all_sections($courseid) {
1252 static $coursesections = array();
1253 if (!array_key_exists($courseid, $coursesections)) {
1254 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1255 "section, id, course, name, summary, summaryformat, sequence, visible");
1257 return $coursesections[$courseid];
1261 * Returns the course section to display or 0 meaning show all sections. Returns 0 for guests.
1262 * It also sets the $USER->display cache to array($courseid=>return value)
1264 * @param int $courseid The course id
1265 * @return int Course section to display, 0 means all
1267 function course_get_display($courseid) {
1270 if (!isloggedin() or isguestuser()) {
1271 //do not get settings in db for guests
1272 return 0; //return the implicit setting
1275 if (!isset($USER->display
[$courseid])) {
1276 if (!$display = $DB->get_field('course_display', 'display', array('userid' => $USER->id
, 'course'=>$courseid))) {
1277 $display = 0; // all sections option is not stored in DB, this makes the table much smaller
1279 //use display cache for one course only - we need to keep session small
1280 $USER->display
= array($courseid => $display);
1283 return $USER->display
[$courseid];
1287 * Show one section only or all sections.
1289 * @param int $courseid The course id
1290 * @param mixed $display show only this section, 0 or 'all' means show all sections
1291 * @return int Course section to display, 0 means all
1293 function course_set_display($courseid, $display) {
1296 if ($display === 'all' or empty($display)) {
1300 if (!isloggedin() or isguestuser()) {
1301 //do not store settings in db for guests
1305 if ($display == 0) {
1306 //show all, do not store anything in database
1307 $DB->delete_records('course_display', array('userid' => $USER->id
, 'course' => $courseid));
1310 if ($DB->record_exists('course_display', array('userid' => $USER->id
, 'course' => $courseid))) {
1311 $DB->set_field('course_display', 'display', $display, array('userid' => $USER->id
, 'course' => $courseid));
1313 $record = new stdClass();
1314 $record->userid
= $USER->id
;
1315 $record->course
= $courseid;
1316 $record->display
= $display;
1317 $DB->insert_record('course_display', $record);
1321 //use display cache for one course only - we need to keep session small
1322 $USER->display
= array($courseid => $display);
1328 * For a given course section, marks it visible or hidden,
1329 * and does the same for every activity in that section
1331 function set_section_visible($courseid, $sectionnumber, $visibility) {
1334 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1335 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id
));
1336 if (!empty($section->sequence
)) {
1337 $modules = explode(",", $section->sequence
);
1338 foreach ($modules as $moduleid) {
1339 set_coursemodule_visible($moduleid, $visibility, true);
1342 rebuild_course_cache($courseid);
1347 * Obtains shared data that is used in print_section when displaying a
1348 * course-module entry.
1350 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1352 * This data is also used in other areas of the code.
1353 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1354 * @param object $course Moodle course object
1355 * @return array An array with the following values in this order:
1356 * $content (optional extra content for after link),
1357 * $instancename (text of link)
1359 function get_print_section_cm_text(cm_info
$cm, $course) {
1362 // Get course context
1363 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1365 // Get content from modinfo if specified. Content displays either
1366 // in addition to the standard link (below), or replaces it if
1367 // the link is turned off by setting ->url to null.
1368 if (($content = $cm->get_content()) !== '') {
1369 $labelformatoptions = new stdClass();
1370 $labelformatoptions->noclean
= true;
1371 $labelformatoptions->overflowdiv
= true;
1372 $labelformatoptions->context
= $coursecontext;
1373 $content = format_text($content, FORMAT_HTML
, $labelformatoptions);
1378 $stringoptions = new stdClass
;
1379 $stringoptions->context
= $coursecontext;
1380 $instancename = format_string($cm->name
, true, $stringoptions);
1381 return array($content, $instancename);
1385 * Prints a section full of activity modules
1387 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1388 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1390 static $initialised;
1392 static $groupbuttons;
1393 static $groupbuttonslink;
1396 static $strmovehere;
1397 static $strmovefull;
1398 static $strunreadpostsone;
1400 static $modulenames;
1402 if (!isset($initialised)) {
1403 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1404 $groupbuttonslink = (!$course->groupmodeforce
);
1405 $isediting = $PAGE->user_is_editing();
1406 $ismoving = $isediting && ismoving($course->id
);
1408 $strmovehere = get_string("movehere");
1409 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1411 $modulenames = array();
1412 $initialised = true;
1415 $tl = textlib_get_instance();
1417 $modinfo = get_fast_modinfo($course);
1418 $completioninfo = new completion_info($course);
1420 //Accessibility: replace table with list <ul>, but don't output empty list.
1421 if (!empty($section->sequence
)) {
1423 // Fix bug #5027, don't want style=\"width:$width\".
1424 echo "<ul class=\"section img-text\">\n";
1425 $sectionmods = explode(",", $section->sequence
);
1427 foreach ($sectionmods as $modnumber) {
1428 if (empty($mods[$modnumber])) {
1435 $mod = $mods[$modnumber];
1437 if ($ismoving and $mod->id
== $USER->activitycopy
) {
1438 // do not display moving mod
1442 if (isset($modinfo->cms
[$modnumber])) {
1443 // We can continue (because it will not be displayed at all)
1445 // 1) The activity is not visible to users
1447 // 2a) The 'showavailability' option is not set (if that is set,
1448 // we need to display the activity so we can show
1449 // availability info)
1451 // 2b) The 'availableinfo' is empty, i.e. the activity was
1452 // hidden in a way that leaves no info, such as using the
1454 if (!$modinfo->cms
[$modnumber]->uservisible
&&
1455 (empty($modinfo->cms
[$modnumber]->showavailability
) ||
1456 empty($modinfo->cms
[$modnumber]->availableinfo
))) {
1457 // visibility shortcut
1461 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1462 // module not installed
1465 if (!coursemodule_visible_for_user($mod) &&
1466 empty($mod->showavailability
)) {
1467 // full visibility check
1472 if (!isset($modulenames[$mod->modname
])) {
1473 $modulenames[$mod->modname
] = get_string('modulename', $mod->modname
);
1475 $modulename = $modulenames[$mod->modname
];
1477 // In some cases the activity is visible to user, but it is
1478 // dimmed. This is done if viewhiddenactivities is true and if:
1479 // 1. the activity is not visible, or
1480 // 2. the activity has dates set which do not include current, or
1481 // 3. the activity has any other conditions set (regardless of whether
1482 // current user meets them)
1483 $canviewhidden = has_capability(
1484 'moodle/course:viewhiddenactivities',
1485 get_context_instance(CONTEXT_MODULE
, $mod->id
));
1486 $accessiblebutdim = false;
1487 if ($canviewhidden) {
1488 $accessiblebutdim = !$mod->visible
;
1489 if (!empty($CFG->enableavailability
)) {
1490 $accessiblebutdim = $accessiblebutdim ||
1491 $mod->availablefrom
> time() ||
1492 ($mod->availableuntil
&& $mod->availableuntil
< time()) ||
1493 count($mod->conditionsgrade
) > 0 ||
1494 count($mod->conditionscompletion
) > 0;
1498 $liclasses = array();
1499 $liclasses[] = 'activity';
1500 $liclasses[] = $mod->modname
;
1501 $liclasses[] = 'modtype_'.$mod->modname
;
1502 $extraclasses = $mod->get_extra_classes();
1503 if ($extraclasses) {
1504 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1506 echo html_writer
::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1508 echo '<a title="'.$strmovefull.'"'.
1509 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.sesskey().'">'.
1510 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1511 ' alt="'.$strmovehere.'" /></a><br />
1515 $classes = array('mod-indent');
1516 if (!empty($mod->indent
)) {
1517 $classes[] = 'mod-indent-'.$mod->indent
;
1518 if ($mod->indent
> 15) {
1519 $classes[] = 'mod-indent-huge';
1522 echo html_writer
::start_tag('div', array('class'=>join(' ', $classes)));
1524 // Get data about this course-module
1525 list($content, $instancename) =
1526 get_print_section_cm_text($modinfo->cms
[$modnumber], $course);
1528 //Accessibility: for files get description via icon, this is very ugly hack!
1530 $altname = $mod->modfullname
;
1531 if (!empty($customicon)) {
1532 $archetype = plugin_supports('mod', $mod->modname
, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1533 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1534 $mimetype = mimeinfo_from_icon('type', $customicon);
1535 $altname = get_mimetype_description($mimetype);
1538 // Avoid unnecessary duplication: if e.g. a forum name already
1539 // includes the word forum (or Forum, etc) then it is unhelpful
1540 // to include that in the accessible description that is added.
1541 if (false !== strpos($tl->strtolower($instancename),
1542 $tl->strtolower($altname))) {
1545 // File type after name, for alphabetic lists (screen reader).
1547 $altname = get_accesshide(' '.$altname);
1550 // We may be displaying this just in order to show information
1551 // about visibility, without the actual link
1553 if ($mod->uservisible
) {
1554 // Nope - in this case the link is fully working for user
1557 if ($accessiblebutdim) {
1558 $linkclasses .= ' dimmed';
1559 $textclasses .= ' dimmed_text';
1560 $accesstext = '<span class="accesshide">'.
1561 get_string('hiddenfromstudents').': </span>';
1566 $linkcss = 'class="' . trim($linkclasses) . '" ';
1571 $textcss = 'class="' . trim($textclasses) . '" ';
1576 // Get on-click attribute value if specified
1577 $onclick = $mod->get_on_click();
1579 $onclick = ' onclick="' . $onclick . '"';
1582 if ($url = $mod->get_url()) {
1583 // Display link itself
1584 echo '<a ' . $linkcss . $mod->extra
. $onclick .
1585 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1586 '" class="activityicon" alt="' .
1587 $modulename . '" /> ' .
1588 $accesstext . '<span class="instancename">' .
1589 $instancename . $altname . '</span></a>';
1591 // If specified, display extra content after link
1593 $contentpart = '<div class="contentafterlink' .
1594 trim($textclasses) . '">' . $content . '</div>';
1597 // No link, so display only content
1598 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1599 $accesstext . $content . '</div>';
1602 if (!empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1603 if (!isset($groupings)) {
1604 $groupings = groups_get_all_groupings($course->id
);
1606 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1609 $textclasses = $extraclasses;
1610 $textclasses .= ' dimmed_text';
1612 $textcss = 'class="' . trim($textclasses) . '" ';
1616 $accesstext = '<span class="accesshide">' .
1617 get_string('notavailableyet', 'condition') .
1620 if ($url = $mod->get_url()) {
1621 // Display greyed-out text of link
1622 echo '<div ' . $textcss . $mod->extra
.
1623 ' >' . '<img src="' . $mod->get_icon_url() .
1624 '" class="activityicon" alt="' .
1626 '" /> <span>'. $instancename . $altname .
1629 // Do not display content after link when it is greyed out like this.
1631 // No link, so display only content (also greyed)
1632 $contentpart = '<div ' . $textcss . $mod->extra
. '>' .
1633 $accesstext . $content . '</div>';
1637 // Module can put text after the link (e.g. forum unread)
1638 echo $mod->get_after_link();
1640 // If there is content but NO link (eg label), then display the
1641 // content here (BEFORE any icons). In this case cons must be
1642 // displayed after the content so that it makes more sense visually
1643 // and for accessibility reasons, e.g. if you have a one-line label
1644 // it should work similarly (at least in terms of ordering) to an
1651 if ($groupbuttons and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
1652 if (! $mod->groupmodelink
= $groupbuttonslink) {
1653 $mod->groupmode
= $course->groupmode
;
1657 $mod->groupmode
= false;
1659 echo ' ';
1660 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1661 echo $mod->get_after_edit_icons();
1665 $completion = $hidecompletion
1666 ? COMPLETION_TRACKING_NONE
1667 : $completioninfo->is_enabled($mod);
1668 if ($completion!=COMPLETION_TRACKING_NONE
&& isloggedin() &&
1669 !isguestuser() && $mod->uservisible
) {
1670 $completiondata = $completioninfo->get_data($mod,true);
1671 $completionicon = '';
1673 switch ($completion) {
1674 case COMPLETION_TRACKING_MANUAL
:
1675 $completionicon = 'manual-enabled'; break;
1676 case COMPLETION_TRACKING_AUTOMATIC
:
1677 $completionicon = 'auto-enabled'; break;
1680 } else if ($completion==COMPLETION_TRACKING_MANUAL
) {
1681 switch($completiondata->completionstate
) {
1682 case COMPLETION_INCOMPLETE
:
1683 $completionicon = 'manual-n'; break;
1684 case COMPLETION_COMPLETE
:
1685 $completionicon = 'manual-y'; break;
1687 } else { // Automatic
1688 switch($completiondata->completionstate
) {
1689 case COMPLETION_INCOMPLETE
:
1690 $completionicon = 'auto-n'; break;
1691 case COMPLETION_COMPLETE
:
1692 $completionicon = 'auto-y'; break;
1693 case COMPLETION_COMPLETE_PASS
:
1694 $completionicon = 'auto-pass'; break;
1695 case COMPLETION_COMPLETE_FAIL
:
1696 $completionicon = 'auto-fail'; break;
1699 if ($completionicon) {
1700 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1701 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1702 if ($completion == COMPLETION_TRACKING_MANUAL
&& !$isediting) {
1703 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1705 $completiondata->completionstate
==COMPLETION_COMPLETE
1706 ? COMPLETION_INCOMPLETE
1707 : COMPLETION_COMPLETE
;
1708 // In manual mode the icon is a toggle form...
1710 // If this completion state is used by the
1711 // conditional activities system, we need to turn
1713 if (!empty($CFG->enableavailability
) &&
1714 condition_info
::completion_value_used_as_condition($course, $mod)) {
1715 $extraclass = ' preventjs';
1720 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot
."/course/togglecompletion.php'><div>
1721 <input type='hidden' name='id' value='{$mod->id}' />
1722 <input type='hidden' name='sesskey' value='".sesskey()."' />
1723 <input type='hidden' name='completionstate' value='$newstate' />
1724 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1727 // In auto mode, or when editing, the icon is just an image
1728 echo "<span class='autocompletion'>";
1729 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1734 // If there is content AND a link, then display the content here
1735 // (AFTER any icons). Otherwise it was displayed before
1740 // Show availability information (for someone who isn't allowed to
1741 // see the activity itself, or for staff)
1742 if (!$mod->uservisible
) {
1743 echo '<div class="availabilityinfo">'.$mod->availableinfo
.'</div>';
1744 } else if ($canviewhidden && !empty($CFG->enableavailability
)) {
1745 $ci = new condition_info($mod);
1746 $fullinfo = $ci->get_full_information();
1748 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1749 ?
'userrestriction_visible'
1750 : 'userrestriction_hidden','condition',
1751 $fullinfo).'</div>';
1755 echo html_writer
::end_tag('div');
1756 echo html_writer
::end_tag('li')."\n";
1759 } elseif ($ismoving) {
1760 echo "<ul class=\"section\">\n";
1764 echo '<li><a title="'.$strmovefull.'"'.
1765 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.sesskey().'">'.
1766 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1767 ' alt="'.$strmovehere.'" /></a></li>
1770 if (!empty($section->sequence
) ||
$ismoving) {
1771 echo "</ul><!--class='section'-->\n\n";
1776 * Prints the menus to add activities and resources.
1778 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1779 global $CFG, $OUTPUT;
1781 // check to see if user can add menus
1782 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1786 $urlbase = "/course/mod.php?id=$course->id§ion=$section&sesskey=".sesskey().'&add=';
1788 $resources = array();
1789 $activities = array();
1791 foreach($modnames as $modname=>$modnamestr) {
1792 if (!course_allowed_module($course, $modname)) {
1796 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1797 if (!file_exists($libfile)) {
1800 include_once($libfile);
1801 $gettypesfunc = $modname.'_get_types';
1802 if (function_exists($gettypesfunc)) {
1803 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1804 if ($types = $gettypesfunc()) {
1808 foreach($types as $type) {
1809 if ($type->typestr
=== '--') {
1812 if (strpos($type->typestr
, '--') === 0) {
1813 $groupname = str_replace('--', '', $type->typestr
);
1816 $type->type
= str_replace('&', '&', $type->type
);
1817 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1818 $atype = MOD_CLASS_RESOURCE
;
1820 $menu[$urlbase.$type->type
] = $type->typestr
;
1822 if (!is_null($groupname)) {
1823 if ($atype == MOD_CLASS_RESOURCE
) {
1824 $resources[] = array($groupname=>$menu);
1826 $activities[] = array($groupname=>$menu);
1829 if ($atype == MOD_CLASS_RESOURCE
) {
1830 $resources = array_merge($resources, $menu);
1832 $activities = array_merge($activities, $menu);
1837 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1838 if ($archetype == MOD_ARCHETYPE_RESOURCE
) {
1839 $resources[$urlbase.$modname] = $modnamestr;
1841 // all other archetypes are considered activity
1842 $activities[$urlbase.$modname] = $modnamestr;
1847 $straddactivity = get_string('addactivity');
1848 $straddresource = get_string('addresource');
1850 $output = '<div class="section_add_menus">';
1853 $output .= '<div class="horizontal">';
1856 if (!empty($resources)) {
1857 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1858 $select->set_help_icon('resources');
1859 $output .= $OUTPUT->render($select);
1862 if (!empty($activities)) {
1863 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1864 $select->set_help_icon('activities');
1865 $output .= $OUTPUT->render($select);
1869 $output .= '</div>';
1872 $output .= '</div>';
1882 * Return the course category context for the category with id $categoryid, except
1883 * that if $categoryid is 0, return the system context.
1885 * @param integer $categoryid a category id or 0.
1886 * @return object the corresponding context
1888 function get_category_or_system_context($categoryid) {
1890 return get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1892 return get_context_instance(CONTEXT_SYSTEM
);
1897 * Gets the child categories of a given courses category. Uses a static cache
1898 * to make repeat calls efficient.
1900 * @param int $parentid the id of a course category.
1901 * @return array all the child course categories.
1903 function get_child_categories($parentid) {
1904 static $allcategories = null;
1906 // only fill in this variable the first time
1907 if (null == $allcategories) {
1908 $allcategories = array();
1910 $categories = get_categories();
1911 foreach ($categories as $category) {
1912 if (empty($allcategories[$category->parent
])) {
1913 $allcategories[$category->parent
] = array();
1915 $allcategories[$category->parent
][] = $category;
1919 if (empty($allcategories[$parentid])) {
1922 return $allcategories[$parentid];
1927 * This function recursively travels the categories, building up a nice list
1928 * for display. It also makes an array that list all the parents for each
1931 * For example, if you have a tree of categories like:
1932 * Miscellaneous (id = 1)
1933 * Subcategory (id = 2)
1934 * Sub-subcategory (id = 4)
1935 * Other category (id = 3)
1936 * Then after calling this function you will have
1937 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1938 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1939 * 3 => 'Other category');
1940 * $parents = array(2 => array(1), 4 => array(1, 2));
1942 * If you specify $requiredcapability, then only categories where the current
1943 * user has that capability will be added to $list, although all categories
1944 * will still be added to $parents, and if you only have $requiredcapability
1945 * in a child category, not the parent, then the child catgegory will still be
1948 * If you specify the option $excluded, then that category, and all its children,
1949 * are omitted from the tree. This is useful when you are doing something like
1950 * moving categories, where you do not want to allow people to move a category
1951 * to be the child of itself.
1953 * @param array $list For output, accumulates an array categoryid => full category path name
1954 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1955 * @param string/array $requiredcapability if given, only categories where the current
1956 * user has this capability will be added to $list. Can also be an array of capabilities,
1957 * in which case they are all required.
1958 * @param integer $excludeid Omit this category and its children from the lists built.
1959 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1960 * @param string $path For internal use, as part of recursive calls.
1962 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1963 $excludeid = 0, $category = NULL, $path = "") {
1965 // initialize the arrays if needed
1966 if (!is_array($list)) {
1969 if (!is_array($parents)) {
1973 if (empty($category)) {
1974 // Start at the top level.
1975 $category = new stdClass
;
1978 // This is the excluded category, don't include it.
1979 if ($excludeid > 0 && $excludeid == $category->id
) {
1985 $path = $path.' / '.format_string($category->name
);
1987 $path = format_string($category->name
);
1990 // Add this category to $list, if the permissions check out.
1991 if (empty($requiredcapability)) {
1992 $list[$category->id
] = $path;
1995 ensure_context_subobj_present($category, CONTEXT_COURSECAT
);
1996 $requiredcapability = (array)$requiredcapability;
1997 if (has_all_capabilities($requiredcapability, $category->context
)) {
1998 $list[$category->id
] = $path;
2003 // Add all the children recursively, while updating the parents array.
2004 if ($categories = get_child_categories($category->id
)) {
2005 foreach ($categories as $cat) {
2006 if (!empty($category->id
)) {
2007 if (isset($parents[$category->id
])) {
2008 $parents[$cat->id
] = $parents[$category->id
];
2010 $parents[$cat->id
][] = $category->id
;
2012 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2018 * This function generates a structured array of courses and categories.
2020 * The depth of categories is limited by $CFG->maxcategorydepth however there
2021 * is no limit on the number of courses!
2023 * Suitable for use with the course renderers course_category_tree method:
2024 * $renderer = $PAGE->get_renderer('core','course');
2025 * echo $renderer->course_category_tree(get_course_category_tree());
2027 * @global moodle_database $DB
2031 function get_course_category_tree($id = 0, $depth = 0) {
2033 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
));
2034 $categories = get_child_categories($id);
2035 $categoryids = array();
2036 foreach ($categories as $key => &$category) {
2037 if (!$category->visible
&& !$viewhiddencats) {
2038 unset($categories[$key]);
2041 $categoryids[$category->id
] = $category;
2042 if (empty($CFG->maxcategorydepth
) ||
$depth <= $CFG->maxcategorydepth
) {
2043 list($category->categories
, $subcategories) = get_course_category_tree($category->id
, $depth+
1);
2044 foreach ($subcategories as $subid=>$subcat) {
2045 $categoryids[$subid] = $subcat;
2047 $category->courses
= array();
2052 // This is a recursive call so return the required array
2053 return array($categories, $categoryids);
2056 // The depth is 0 this function has just been called so we can finish it off
2058 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
2059 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2061 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2065 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2066 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2067 // loop throught them
2068 foreach ($courses as $course) {
2069 if ($course->id
== SITEID
) {
2072 context_instance_preload($course);
2073 if (!empty($course->visible
) ||
has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
2074 $categoryids[$course->category
]->courses
[$course->id
] = $course;
2082 * Recursive function to print out all the categories in a nice format
2083 * with or without courses included
2085 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2088 // maxcategorydepth == 0 meant no limit
2089 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
2093 if (!$displaylist) {
2094 make_categories_list($displaylist, $parentslist);
2098 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
))) {
2099 print_category_info($category, $depth, $showcourses);
2101 return; // Don't bother printing children of invisible categories
2105 $category->id
= "0";
2108 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
2109 $countcats = count($categories);
2113 foreach ($categories as $cat) {
2115 if ($count == $countcats) {
2118 $up = $first ?
false : true;
2119 $down = $last ?
false : true;
2122 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses);
2128 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2130 function make_categories_options() {
2131 make_categories_list($cats,$parents);
2132 foreach ($cats as $key => $value) {
2133 if (array_key_exists($key,$parents)) {
2134 if ($indent = count($parents[$key])) {
2135 for ($i = 0; $i < $indent; $i++
) {
2136 $cats[$key] = ' '.$cats[$key];
2145 * Prints the category info in indented fashion
2146 * This function is only used by print_whole_category_list() above
2148 function print_category_info($category, $depth=0, $showcourses = false) {
2149 global $CFG, $DB, $OUTPUT;
2151 $strsummary = get_string('summary');
2154 if (!$category->visible
) {
2155 $catlinkcss = array('class'=>'dimmed');
2157 static $coursecount = null;
2158 if (null === $coursecount) {
2159 // only need to check this once
2160 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT
;
2163 if ($showcourses and $coursecount) {
2164 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2166 $catimage = " ";
2169 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2170 if ($showcourses and $coursecount) {
2171 echo '<div class="categorylist clearfix">';
2173 $cat .= html_writer
::tag('div', $catimage, array('class'=>'image'));
2174 $catlink = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), format_string($category->name
), $catlinkcss);
2175 $cat .= html_writer
::tag('div', $catlink, array('class'=>'name'));
2179 for ($i=0; $i< $depth; $i++
) {
2180 $html = html_writer
::tag('div', $html . $cat, array('class'=>'indentation'));
2186 echo html_writer
::tag('div', $html, array('class'=>'category'));
2187 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2189 // does the depth exceed maxcategorydepth
2190 // maxcategorydepth == 0 or unset meant no limit
2191 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
2192 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
2193 foreach ($courses as $course) {
2195 if (!$course->visible
) {
2196 $linkcss = array('class'=>'dimmed');
2199 $courselink = html_writer
::link(new moodle_url('/course/view.php', array('id'=>$course->id
)), format_string($course->fullname
), $linkcss);
2203 if ($icons = enrol_get_course_info_icons($course)) {
2204 foreach ($icons as $pix_icon) {
2205 $courseicon = $OUTPUT->render($pix_icon).' ';
2209 $coursecontent = html_writer
::tag('div', $courseicon.$courselink, array('class'=>'name'));
2211 if ($course->summary
) {
2212 $link = new moodle_url('/course/info.php?id='.$course->id
);
2213 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2214 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2215 array('title'=>$strsummary));
2217 $coursecontent .= html_writer
::tag('div', $actionlink, array('class'=>'info'));
2221 for ($i=0; $i <= $depth; $i++
) {
2222 $html = html_writer
::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2223 $coursecontent = '';
2225 echo html_writer
::tag('div', $html, array('class'=>'course clearfloat'));
2230 echo '<div class="categorylist">';
2232 $cat = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), format_string($category->name
), $catlinkcss);
2233 $cat .= html_writer
::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2236 for ($i=0; $i< $depth; $i++
) {
2237 $html = html_writer
::tag('div', $html .$cat, array('class'=>'indentation'));
2244 echo html_writer
::tag('div', $html, array('class'=>'category'));
2245 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
2251 * Print the buttons relating to course requests.
2253 * @param object $systemcontext the system context.
2255 function print_course_request_buttons($systemcontext) {
2256 global $CFG, $DB, $OUTPUT;
2257 if (empty($CFG->enablecourserequests
)) {
2260 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2261 /// Print a button to request a new course
2262 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2264 /// Print a button to manage pending requests
2265 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2266 $disabled = !$DB->record_exists('course_request', array());
2267 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2272 * Does the user have permission to edit things in this category?
2274 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2275 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2277 function can_edit_in_category($categoryid = 0) {
2278 $context = get_category_or_system_context($categoryid);
2279 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2283 * Prints the turn editing on/off button on course/index.php or course/category.php.
2285 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2286 * @return string HTML of the editing button, or empty string, if this user is not allowed
2289 function update_category_button($categoryid = 0) {
2290 global $CFG, $PAGE, $OUTPUT;
2292 // Check permissions.
2293 if (!can_edit_in_category($categoryid)) {
2297 // Work out the appropriate action.
2298 if ($PAGE->user_is_editing()) {
2299 $label = get_string('turneditingoff');
2302 $label = get_string('turneditingon');
2306 // Generate the button HTML.
2307 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2309 $options['id'] = $categoryid;
2310 $page = 'category.php';
2312 $page = 'index.php';
2314 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2318 * Category is 0 (for all courses) or an object
2320 function print_courses($category) {
2321 global $CFG, $OUTPUT;
2323 if (!is_object($category) && $category==0) {
2324 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2325 if (is_array($categories) && count($categories) == 1) {
2326 $category = array_shift($categories);
2327 $courses = get_courses_wmanagers($category->id
,
2329 array('summary','summaryformat'));
2331 $courses = get_courses_wmanagers('all',
2333 array('summary','summaryformat'));
2337 $courses = get_courses_wmanagers($category->id
,
2339 array('summary','summaryformat'));
2343 echo html_writer
::start_tag('ul', array('class'=>'unlist'));
2344 foreach ($courses as $course) {
2345 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
2346 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2347 echo html_writer
::start_tag('li');
2348 print_course($course);
2349 echo html_writer
::end_tag('li');
2352 echo html_writer
::end_tag('ul');
2354 echo $OUTPUT->heading(get_string("nocoursesyet"));
2355 $context = get_context_instance(CONTEXT_SYSTEM
);
2356 if (has_capability('moodle/course:create', $context)) {
2358 if (!empty($category->id
)) {
2359 $options['category'] = $category->id
;
2361 $options['category'] = $CFG->defaultrequestcategory
;
2363 echo html_writer
::start_tag('div', array('class'=>'addcoursebutton'));
2364 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2365 echo html_writer
::end_tag('div');
2371 * Print a description of a course, suitable for browsing in a list.
2373 * @param object $course the course object.
2374 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2376 function print_course($course, $highlightterms = '') {
2377 global $CFG, $USER, $DB, $OUTPUT;
2379 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2381 // Rewrite file URLs so that they are correct
2382 $course->summary
= file_rewrite_pluginfile_urls($course->summary
, 'pluginfile.php', $context->id
, 'course', 'summary', NULL);
2384 echo html_writer
::start_tag('div', array('class'=>'coursebox clearfix'));
2385 echo html_writer
::start_tag('div', array('class'=>'info'));
2386 echo html_writer
::start_tag('h3', array('class'=>'name'));
2388 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id
));
2389 $linktext = highlight($highlightterms, format_string($course->fullname
));
2390 $linkparams = array('title'=>get_string('entercourse'));
2391 if (empty($course->visible
)) {
2392 $linkparams['class'] = 'dimmed';
2394 echo html_writer
::link($linkhref, $linktext, $linkparams);
2395 echo html_writer
::end_tag('h3');
2397 /// first find all roles that are supposed to be displayed
2398 if (!empty($CFG->coursecontact
)) {
2399 $managerroles = explode(',', $CFG->coursecontact
);
2400 $namesarray = array();
2401 if (isset($course->managers
)) {
2402 if (count($course->managers
)) {
2403 $rusers = $course->managers
;
2404 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2406 /// Rename some of the role names if needed
2407 if (isset($context)) {
2408 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2411 // keep a note of users displayed to eliminate duplicates
2412 $usersshown = array();
2413 foreach ($rusers as $ra) {
2415 // if we've already displayed user don't again
2416 if (in_array($ra->user
->id
,$usersshown)) {
2419 $usersshown[] = $ra->user
->id
;
2421 $fullname = fullname($ra->user
, $canviewfullnames);
2423 if (isset($aliasnames[$ra->roleid
])) {
2424 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
2427 $namesarray[] = format_string($ra->rolename
).': '.
2428 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$ra->user
->id
, 'course'=>SITEID
)), $fullname);
2432 $rusers = get_role_users($managerroles, $context,
2433 true, '', 'r.sortorder ASC, u.lastname ASC');
2434 if (is_array($rusers) && count($rusers)) {
2435 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2437 /// Rename some of the role names if needed
2438 if (isset($context)) {
2439 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id
), '', 'roleid,contextid,name');
2442 foreach ($rusers as $teacher) {
2443 $fullname = fullname($teacher, $canviewfullnames);
2445 /// Apply role names
2446 if (isset($aliasnames[$teacher->roleid
])) {
2447 $teacher->rolename
= $aliasnames[$teacher->roleid
]->name
;
2450 $namesarray[] = format_string($teacher->rolename
).': '.
2451 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$teacher->id
, 'course'=>SITEID
)), $fullname);
2456 if (!empty($namesarray)) {
2457 echo html_writer
::start_tag('ul', array('class'=>'teachers'));
2458 foreach ($namesarray as $name) {
2459 echo html_writer
::tag('li', $name);
2461 echo html_writer
::end_tag('ul');
2464 echo html_writer
::end_tag('div'); // End of info div
2466 echo html_writer
::start_tag('div', array('class'=>'summary'));
2468 $options->noclean
= true;
2469 $options->para
= false;
2470 $options->overflowdiv
= true;
2471 if (!isset($course->summaryformat
)) {
2472 $course->summaryformat
= FORMAT_MOODLE
;
2474 echo highlight($highlightterms, format_text($course->summary
, $course->summaryformat
, $options, $course->id
));
2475 if ((!isloggedin() ||
is_siteadmin()) && $icons = enrol_get_course_info_icons($course)) {
2476 echo html_writer
::start_tag('div', array('class'=>'enrolmenticons'));
2477 foreach ($icons as $icon) {
2478 echo $OUTPUT->render($icon);
2480 echo html_writer
::end_tag('div'); // End of enrolmenticons div
2482 echo html_writer
::end_tag('div'); // End of summary div
2483 echo html_writer
::end_tag('div'); // End of coursebox div
2487 * Prints custom user information on the home page.
2488 * Over time this can include all sorts of information
2490 function print_my_moodle() {
2491 global $USER, $CFG, $DB, $OUTPUT;
2493 if (!isloggedin() or isguestuser()) {
2494 print_error('nopermissions', '', '', 'See My Moodle');
2497 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2499 $rcourses = array();
2500 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
2501 $rcourses = get_my_remotecourses($USER->id
);
2502 $rhosts = get_my_remotehosts();
2505 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
2507 if (!empty($courses)) {
2508 echo '<ul class="unlist">';
2509 foreach ($courses as $course) {
2510 if ($course->id
== SITEID
) {
2514 print_course($course);
2521 if (!empty($rcourses)) {
2522 // at the IDP, we know of all the remote courses
2523 foreach ($rcourses as $course) {
2524 print_remote_course($course, "100%");
2526 } elseif (!empty($rhosts)) {
2527 // non-IDP, we know of all the remote servers, but not courses
2528 foreach ($rhosts as $host) {
2529 print_remote_host($host, "100%");
2535 if ($DB->count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
2536 echo "<table width=\"100%\"><tr><td align=\"center\">";
2537 print_course_search("", false, "short");
2538 echo "</td><td align=\"center\">";
2539 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2540 echo "</td></tr></table>\n";
2544 if ($DB->count_records("course_categories") > 1) {
2545 echo $OUTPUT->box_start("categorybox");
2546 print_whole_category_list();
2547 echo $OUTPUT->box_end();
2555 function print_course_search($value="", $return=false, $format="plain") {
2561 $id = 'coursesearch';
2567 $strsearchcourses= get_string("searchcourses");
2569 if ($format == 'plain') {
2570 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2571 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2572 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2573 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2574 $output .= '<input type="submit" value="'.get_string('go').'" />';
2575 $output .= '</fieldset></form>';
2576 } else if ($format == 'short') {
2577 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2578 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2579 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2580 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2581 $output .= '<input type="submit" value="'.get_string('go').'" />';
2582 $output .= '</fieldset></form>';
2583 } else if ($format == 'navbar') {
2584 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2585 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2586 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2587 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2588 $output .= '<input type="submit" value="'.get_string('go').'" />';
2589 $output .= '</fieldset></form>';
2598 function print_remote_course($course, $width="100%") {
2603 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2605 echo '<div class="coursebox remotecoursebox clearfix">';
2606 echo '<div class="info">';
2607 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2608 $linkcss.' href="'.$url.'">'
2609 . format_string($course->fullname
) .'</a><br />'
2610 . format_string($course->hostname
) . ' : '
2611 . format_string($course->cat_name
) . ' : '
2612 . format_string($course->shortname
). '</div>';
2613 echo '</div><div class="summary">';
2615 $options->noclean
= true;
2616 $options->para
= false;
2617 $options->overflowdiv
= true;
2618 echo format_text($course->summary
, $course->summaryformat
, $options);
2623 function print_remote_host($host, $width="100%") {
2628 echo '<div class="coursebox clearfix">';
2629 echo '<div class="info">';
2630 echo '<div class="name">';
2631 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2632 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2633 . s($host['name']).'</a> - ';
2634 echo $host['count'] . ' ' . get_string('courses');
2641 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2643 function add_course_module($mod) {
2646 $mod->added
= time();
2649 return $DB->insert_record("course_modules", $mod);
2653 * Returns course section - creates new if does not exist yet.
2654 * @param int $relative section number
2655 * @param int $courseid
2656 * @return object $course_section object
2658 function get_course_section($section, $courseid) {
2661 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2664 $cw = new stdClass();
2665 $cw->course
= $courseid;
2666 $cw->section
= $section;
2668 $cw->summaryformat
= FORMAT_HTML
;
2670 $id = $DB->insert_record("course_sections", $cw);
2671 return $DB->get_record("course_sections", array("id"=>$id));
2674 * Given a full mod object with section and course already defined, adds this module to that section.
2676 * @param object $mod
2677 * @param int $beforemod An existing ID which we will insert the new module before
2678 * @return int The course_sections ID where the mod is inserted
2680 function add_mod_to_section($mod, $beforemod=NULL) {
2683 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course
, "section"=>$mod->section
))) {
2685 $section->sequence
= trim($section->sequence
);
2687 if (empty($section->sequence
)) {
2688 $newsequence = "$mod->coursemodule";
2690 } else if ($beforemod) {
2691 $modarray = explode(",", $section->sequence
);
2693 if ($key = array_keys($modarray, $beforemod->id
)) {
2694 $insertarray = array($mod->id
, $beforemod->id
);
2695 array_splice($modarray, $key[0], 1, $insertarray);
2696 $newsequence = implode(",", $modarray);
2698 } else { // Just tack it on the end anyway
2699 $newsequence = "$section->sequence,$mod->coursemodule";
2703 $newsequence = "$section->sequence,$mod->coursemodule";
2706 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2707 return $section->id
; // Return course_sections ID that was used.
2709 } else { // Insert a new record
2710 $section->course
= $mod->course
;
2711 $section->section
= $mod->section
;
2712 $section->summary
= "";
2713 $section->summaryformat
= FORMAT_HTML
;
2714 $section->sequence
= $mod->coursemodule
;
2715 return $DB->insert_record("course_sections", $section);
2719 function set_coursemodule_groupmode($id, $groupmode) {
2721 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2724 function set_coursemodule_idnumber($id, $idnumber) {
2726 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2730 * $prevstateoverrides = true will set the visibility of the course module
2731 * to what is defined in visibleold. This enables us to remember the current
2732 * visibility when making a whole section hidden, so that when we toggle
2733 * that section back to visible, we are able to return the visibility of
2734 * the course module back to what it was originally.
2736 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2738 require_once($CFG->libdir
.'/gradelib.php');
2740 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2743 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
2746 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2747 foreach($events as $event) {
2756 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2757 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
2759 foreach ($grade_items as $grade_item) {
2760 $grade_item->set_hidden(!$visible);
2764 if ($prevstateoverrides) {
2765 if ($visible == '0') {
2766 // Remember the current visible state so we can toggle this back.
2767 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id'=>$id));
2769 // Get the previous saved visible states.
2770 return $DB->set_field('course_modules', 'visible', $cm->visibleold
, array('id'=>$id));
2773 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2777 * Delete a course module and any associated data at the course level (events)
2778 * Until 1.5 this function simply marked a deleted flag ... now it
2779 * deletes it completely.
2782 function delete_course_module($id) {
2784 require_once($CFG->libdir
.'/gradelib.php');
2785 require_once($CFG->dirroot
.'/blog/lib.php');
2787 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2790 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
));
2791 //delete events from calendar
2792 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2793 foreach($events as $event) {
2794 delete_event($event->id
);
2797 //delete grade items, outcome items and grades attached to modules
2798 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2799 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2800 foreach ($grade_items as $grade_item) {
2801 $grade_item->delete('moddelete');
2804 // Delete completion and availability data; it is better to do this even if the
2805 // features are not turned on, in case they were turned on previously (these will be
2806 // very quick on an empty table)
2807 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
2808 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
2810 delete_context(CONTEXT_MODULE
, $cm->id
);
2811 return $DB->delete_records('course_modules', array('id'=>$cm->id
));
2814 function delete_mod_from_section($mod, $section) {
2817 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2819 $modarray = explode(",", $section->sequence
);
2821 if ($key = array_keys ($modarray, $mod)) {
2822 array_splice($modarray, $key[0], 1);
2823 $newsequence = implode(",", $modarray);
2824 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2834 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2836 * @param object $course
2837 * @param int $section
2838 * @param int $move (-1 or 1)
2840 function move_section($course, $section, $move) {
2841 /// Moves a whole course section up and down within the course
2848 $sectiondest = $section +
$move;
2850 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2854 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$section))) {
2858 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id
, "section"=>$sectiondest))) {
2862 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id
));
2863 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id
));
2865 // if the focus is on the section that is being moved, then move the focus along
2866 if (course_get_display($course->id
) == $section) {
2867 course_set_display($course->id
, $sectiondest);
2870 // Check for duplicates and fix order if needed.
2871 // There is a very rare case that some sections in the same course have the same section id.
2872 $sections = $DB->get_records('course_sections', array('course'=>$course->id
), 'section ASC');
2874 foreach ($sections as $section) {
2875 if ($section->section
!= $n) {
2876 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id
));
2884 * Moves a section within a course, from a position to another.
2885 * Be very careful: $section and $destination refer to section number,
2888 * @param object $course
2889 * @param int $section Section number (not id!!!)
2890 * @param int $destination
2891 * @return boolean Result
2893 function move_section_to($course, $section, $destination) {
2894 /// Moves a whole course section up and down within the course
2897 if (!$destination && $destination != 0) {
2901 if ($destination > $course->numsections
) {
2905 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2906 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
2907 'section ASC, id ASC', 'id, section')) {
2911 $sections = reorder_sections($sections, $section, $destination);
2913 // Update all sections
2914 foreach ($sections as $id => $position) {
2915 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2918 // if the focus is on the section that is being moved, then move the focus along
2919 if (course_get_display($course->id
) == $section) {
2920 course_set_display($course->id
, $destination);
2926 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2927 * an original position number and a target position number, rebuilds the array so that the
2928 * move is made without any duplication of section positions.
2929 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2930 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2932 * @param array $sections
2933 * @param int $origin_position
2934 * @param int $target_position
2937 function reorder_sections($sections, $origin_position, $target_position) {
2938 if (!is_array($sections)) {
2942 // We can't move section position 0
2943 if ($origin_position < 1) {
2944 echo "We can't move section position 0";
2948 // Locate origin section in sections array
2949 if (!$origin_key = array_search($origin_position, $sections)) {
2950 echo "searched position not in sections array";
2951 return false; // searched position not in sections array
2954 // Extract origin section
2955 $origin_section = $sections[$origin_key];
2956 unset($sections[$origin_key]);
2958 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2960 $append_array = array();
2961 foreach ($sections as $id => $position) {
2963 $append_array[$id] = $position;
2964 unset($sections[$id]);
2966 if ($position == $target_position) {
2971 // Append moved section
2972 $sections[$origin_key] = $origin_section;
2974 // Append rest of array (if applicable)
2975 if (!empty($append_array)) {
2976 foreach ($append_array as $id => $position) {
2977 $sections[$id] = $position;
2981 // Renumber positions
2983 foreach ($sections as $id => $p) {
2984 $sections[$id] = $position;
2993 * Move the module object $mod to the specified $section
2994 * If $beforemod exists then that is the module
2995 * before which $modid should be inserted
2996 * All parameters are objects
2998 function moveto_module($mod, $section, $beforemod=NULL) {
2999 global $DB, $OUTPUT;
3001 /// Remove original module from original section
3002 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
3003 echo $OUTPUT->notification("Could not delete module from existing section");
3006 /// Update module itself if necessary
3008 if ($mod->section
!= $section->id
) {
3009 $mod->section
= $section->id
;
3010 $DB->update_record("course_modules", $mod);
3011 // if moving to a hidden section then hide module
3012 if (!$section->visible
) {
3013 set_coursemodule_visible($mod->id
, 0);
3017 /// Add the module into the new section
3019 $mod->course
= $section->course
;
3020 $mod->section
= $section->section
; // need relative reference
3021 $mod->coursemodule
= $mod->id
;
3023 if (! add_mod_to_section($mod, $beforemod)) {
3030 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
3031 global $CFG, $USER, $DB, $OUTPUT;
3036 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3037 // no permission to edit
3038 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
3043 $str->assign
= get_string("assignroles", 'role');
3044 $str->delete
= get_string("delete");
3045 $str->move
= get_string("move");
3046 $str->moveup
= get_string("moveup");
3047 $str->movedown
= get_string("movedown");
3048 $str->moveright
= get_string("moveright");
3049 $str->moveleft
= get_string("moveleft");
3050 $str->update
= get_string("update");
3051 $str->duplicate
= get_string("duplicate");
3052 $str->hide
= get_string("hide");
3053 $str->show
= get_string("show");
3054 $str->clicktochange
= get_string("clicktochange");
3055 $str->forcedmode
= get_string("forcedmode");
3056 $str->groupsnone
= get_string("groupsnone");
3057 $str->groupsseparate
= get_string("groupsseparate");
3058 $str->groupsvisible
= get_string("groupsvisible");
3059 $sesskey = sesskey();
3062 if ($section >= 0) {
3063 $section = '&sr='.$section; // Section return
3069 $path = $CFG->wwwroot
.'/course';
3073 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3074 if ($mod->visible
) {
3075 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
3076 '&sesskey='.$sesskey.$section.'"><img'.
3077 ' src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" '.
3078 ' alt="'.$str->hide
.'" /></a>'."\n";
3080 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
3081 '&sesskey='.$sesskey.$section.'"><img'.
3082 ' src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" '.
3083 ' alt="'.$str->show
.'" /></a>'."\n";
3089 if ($mod->groupmode
!== false) {
3090 if ($mod->groupmode
== SEPARATEGROUPS
) {
3091 $grouptitle = $str->groupsseparate
;
3092 $groupclass = 'editing_groupsseparate';
3093 $groupimage = $OUTPUT->pix_url('t/groups') . '';
3094 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
3095 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
3096 $grouptitle = $str->groupsvisible
;
3097 $groupclass = 'editing_groupsvisible';
3098 $groupimage = $OUTPUT->pix_url('t/groupv') . '';
3099 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
3101 $grouptitle = $str->groupsnone
;
3102 $groupclass = 'editing_groupsnone';
3103 $groupimage = $OUTPUT->pix_url('t/groupn') . '';
3104 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
3106 if ($mod->groupmodelink
) {
3107 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
3108 '<img src="'.$groupimage.'" class="iconsmall" '.
3109 'alt="'.$grouptitle.'" /></a>';
3111 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
3112 ' src="'.$groupimage.'" class="iconsmall" '.
3113 'alt="'.$grouptitle.'" />';
3119 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3121 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
3122 '&sesskey='.$sesskey.$section.'"><img'.
3123 ' src="'.$OUTPUT->pix_url('t/move') . '" class="iconsmall" '.
3124 ' alt="'.$str->move
.'" /></a>'."\n";
3126 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3127 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
3128 ' src="'.$OUTPUT->pix_url('t/up') . '" class="iconsmall" '.
3129 ' alt="'.$str->moveup
.'" /></a>'."\n".
3130 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3131 '&move=1&sesskey='.$sesskey.$section.'"><img'.
3132 ' src="'.$OUTPUT->pix_url('t/down') . '" class="iconsmall" '.
3133 ' alt="'.$str->movedown
.'" /></a>'."\n";
3140 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
3142 if (right_to_left()) { // Exchange arrows on RTL
3143 $rightarrow = 't/left';
3144 $leftarrow = 't/right';
3146 $rightarrow = 't/right';
3147 $leftarrow = 't/left';
3151 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3152 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
3153 ' src="'.$OUTPUT->pix_url($leftarrow).'" class="iconsmall" '.
3154 ' alt="'.$str->moveleft
.'" /></a>'."\n";
3157 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
3158 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
3159 ' src="'.$OUTPUT->pix_url($rightarrow).'" class="iconsmall" '.
3160 ' alt="'.$str->moveright
.'" /></a>'."\n";
3163 if (has_capability('moodle/course:managegroups', $modcontext)){
3164 $context = get_context_instance(CONTEXT_MODULE
, $mod->id
);
3165 $assign = '<a class="editing_assign" title="'.$str->assign
.'" href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?contextid='.
3166 $context->id
.'"><img src="'.$OUTPUT->pix_url('i/roles') . '" alt="'.$str->assign
.'" class="iconsmall"/></a>';
3171 return '<span class="commands">'."\n".$leftright.$move.
3172 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
3173 '&sesskey='.$sesskey.$section.'"><img'.
3174 ' src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" '.
3175 ' alt="'.$str->update
.'" /></a>'."\n".
3176 '<a class="editing_duplicate" title="'.$str->duplicate
.'" href="'.$path.'/mod.php?duplicate='.$mod->id
.
3177 '&sesskey='.$sesskey.$section.'"><img'.
3178 ' src="'.$OUTPUT->pix_url('t/copy') . '" class="iconsmall" '.
3179 ' alt="'.$str->duplicate
.'" /></a>'."\n".
3180 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
3181 '&sesskey='.$sesskey.$section.'"><img'.
3182 ' src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" '.
3183 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
3187 * given a course object with shortname & fullname, this function will
3188 * truncate the the number of chars allowed and add ... if it was too long
3190 function course_format_name ($course,$max=100) {
3192 $str = $course->shortname
.': '. $course->fullname
;
3193 if (strlen($str) <= $max) {
3197 return substr($str,0,$max-3).'...';
3201 function update_restricted_mods($course, $mods) {
3204 /// Delete all the current restricted list
3205 $DB->delete_records('course_allowed_modules', array('course'=>$course->id
));
3207 if (empty($course->restrictmodules
)) {
3208 return; // We're done
3211 /// Insert the new list of restricted mods
3212 foreach ($mods as $mod) {
3214 continue; // this is the 'allow none' option
3216 $am = new stdClass();
3217 $am->course
= $course->id
;
3219 $DB->insert_record('course_allowed_modules',$am);
3224 * This function will take an int (module id) or a string (module name)
3225 * and return true or false, whether it's allowed in the given course (object)
3226 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3227 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3230 function course_allowed_module($course,$mod) {
3233 if (empty($course->restrictmodules
)) {
3237 // Admins and admin-like people who can edit everything can also add anything.
3238 // Originally there was a course:update test only, but it did not match the test in course edit form
3239 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3243 if (is_numeric($mod)) {
3245 } else if (is_string($mod)) {
3246 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3248 if (empty($modid)) {
3252 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id
, 'module'=>$modid));
3256 * Recursively delete category including all subcategories and courses.
3257 * @param stdClass $category
3258 * @param boolean $showfeedback display some notices
3259 * @return array return deleted courses
3261 function category_delete_full($category, $showfeedback=true) {
3263 require_once($CFG->libdir
.'/gradelib.php');
3264 require_once($CFG->libdir
.'/questionlib.php');
3265 require_once($CFG->dirroot
.'/cohort/lib.php');
3267 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3268 foreach ($children as $childcat) {
3269 category_delete_full($childcat, $showfeedback);
3273 $deletedcourses = array();
3274 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC')) {
3275 foreach ($courses as $course) {
3276 if (!delete_course($course, false)) {
3277 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname
);
3279 $deletedcourses[] = $course;
3283 // move or delete cohorts in this context
3284 cohort_delete_category($category);
3286 // now delete anything that may depend on course category context
3287 grade_course_category_delete($category->id
, 0, $showfeedback);
3288 if (!question_delete_course_category($category, 0, $showfeedback)) {
3289 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name
);
3292 // finally delete the category and it's context
3293 $DB->delete_records('course_categories', array('id'=>$category->id
));
3294 delete_context(CONTEXT_COURSECAT
, $category->id
);
3296 events_trigger('course_category_deleted', $category);
3298 return $deletedcourses;
3302 * Delete category, but move contents to another category.
3303 * @param object $ccategory
3304 * @param int $newparentid category id
3305 * @return bool status
3307 function category_delete_move($category, $newparentid, $showfeedback=true) {
3308 global $CFG, $DB, $OUTPUT;
3309 require_once($CFG->libdir
.'/gradelib.php');
3310 require_once($CFG->libdir
.'/questionlib.php');
3311 require_once($CFG->dirroot
.'/cohort/lib.php');
3313 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3317 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
3318 foreach ($children as $childcat) {
3319 move_category($childcat, $newparentcat);
3323 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC', 'id')) {
3324 if (!move_courses(array_keys($courses), $newparentid)) {
3325 echo $OUTPUT->notification("Error moving courses");
3328 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
3331 // move or delete cohorts in this context
3332 cohort_delete_category($category);
3334 // now delete anything that may depend on course category context
3335 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
3336 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3337 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3341 // finally delete the category and it's context
3342 $DB->delete_records('course_categories', array('id'=>$category->id
));
3343 delete_context(CONTEXT_COURSECAT
, $category->id
);
3345 events_trigger('course_category_deleted', $category);
3347 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3353 * Efficiently moves many courses around while maintaining
3354 * sortorder in order.
3356 * @param array $courseids is an array of course ids
3357 * @param int $categoryid
3358 * @return bool success
3360 function move_courses($courseids, $categoryid) {
3361 global $CFG, $DB, $OUTPUT;
3363 if (empty($courseids)) {
3368 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3372 $courseids = array_reverse($courseids);
3375 foreach ($courseids as $courseid) {
3376 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3377 $course->category
= $category->id
;
3378 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
3379 if ($category->visible
== 0) {
3380 // hide the course when moving into hidden category,
3381 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3382 $course->visible
= 0;
3385 $DB->update_record('course', $course);
3387 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3388 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3389 context_moved($context, $newparent);
3392 fix_course_sortorder();
3398 * Hide course category and child course and subcategories
3399 * @param stdClass $category
3402 function course_category_hide($category) {
3405 $category->visible
= 0;
3406 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id
));
3407 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id
));
3408 $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
3409 $DB->set_field('course', 'visible', 0, array('category' => $category->id
));
3410 // get all child categories and hide too
3411 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3412 foreach ($subcats as $cat) {
3413 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id'=>$cat->id
));
3414 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id
));
3415 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
3416 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
3422 * Show course category and child course and subcategories
3423 * @param stdClass $category
3426 function course_category_show($category) {
3429 $category->visible
= 1;
3430 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id
));
3431 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id
));
3432 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id
));
3433 // get all child categories and unhide too
3434 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3435 foreach ($subcats as $cat) {
3436 if ($cat->visibleold
) {
3437 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id
));
3439 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
3445 * Efficiently moves a category - NOTE that this can have
3446 * a huge impact access-control-wise...
3448 function move_category($category, $newparentcat) {
3451 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3454 if (empty($newparentcat->id
)) {
3455 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id
));
3457 $newparent = get_context_instance(CONTEXT_SYSTEM
);
3460 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id'=>$category->id
));
3461 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
3463 if (!$newparentcat->visible
and $category->visible
) {
3464 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3469 context_moved($context, $newparent);
3471 // now make it last in new category
3472 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id'=>$category->id
));
3474 // and fix the sortorders
3475 fix_course_sortorder();
3478 course_category_hide($category);
3483 * Returns the display name of the given section that the course prefers.
3485 * This function utilizes a callback that can be implemented within the course
3486 * formats lib.php file to customize the display name that is used to reference
3489 * By default (if callback is not defined) the method
3490 * {@see get_numeric_section_name} is called instead.
3492 * @param stdClass $course The course to get the section name for
3493 * @param stdClass $section Section object from database
3494 * @return Display name that the course format prefers, e.g. "Week 2"
3496 * @see get_generic_section_name
3498 function get_section_name(stdClass
$course, stdClass
$section) {
3501 /// Inelegant hack for bug 3408
3502 if ($course->format
== 'site') {
3503 return get_string('site');
3506 // Use course formatter callback if it exists
3507 $namingfile = $CFG->dirroot
.'/course/format/'.$course->format
.'/lib.php';
3508 $namingfunction = 'callback_'.$course->format
.'_get_section_name';
3509 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3510 require_once $namingfile;
3512 if (function_exists($namingfunction)) {
3513 return $namingfunction($course, $section);
3516 // else, default behavior:
3517 return get_generic_section_name($course->format
, $section);
3521 * Gets the generic section name for a courses section.
3523 * @param string $format Course format ID e.g. 'weeks' $course->format
3524 * @param stdClass $section Section object from database
3525 * @return Display name that the course format prefers, e.g. "Week 2"
3527 function get_generic_section_name($format, stdClass
$section) {
3528 return get_string('sectionname', "format_$format") . ' ' . $section->section
;
3532 function course_format_uses_sections($format) {
3535 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3536 $featurefunction = 'callback_'.$format.'_uses_sections';
3537 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3538 require_once $featurefile;
3540 if (function_exists($featurefunction)) {
3541 return $featurefunction();
3548 * Returns the information about the ajax support in the given source format
3550 * The returned object's property (boolean)capable indicates that
3551 * the course format supports Moodle course ajax features.
3552 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3554 * @param string $format
3557 function course_format_ajax_support($format) {
3560 // set up default values
3561 $ajaxsupport = new stdClass();
3562 $ajaxsupport->capable
= false;
3563 $ajaxsupport->testedbrowsers
= array();
3565 // get the information from the course format library
3566 $featurefile = $CFG->dirroot
.'/course/format/'.$format.'/lib.php';
3567 $featurefunction = 'callback_'.$format.'_ajax_support';
3568 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3569 require_once $featurefile;
3571 if (function_exists($featurefunction)) {
3572 $formatsupport = $featurefunction();
3573 if (isset($formatsupport->capable
)) {
3574 $ajaxsupport->capable
= $formatsupport->capable
;
3576 if (is_array($formatsupport->testedbrowsers
)) {
3577 $ajaxsupport->testedbrowsers
= $formatsupport->testedbrowsers
;
3581 return $ajaxsupport;
3585 * Can the current user delete this course?
3586 * Course creators have exception,
3587 * 1 day after the creation they can sill delete the course.
3588 * @param int $courseid
3591 function can_delete_course($courseid) {
3594 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3596 if (has_capability('moodle/course:delete', $context)) {
3600 // hack: now try to find out if creator created this course recently (1 day)
3601 if (!has_capability('moodle/course:create', $context)) {
3605 $since = time() - 60*60*24;
3607 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3608 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3610 return $DB->record_exists_select('log', $select, $params);
3614 * Save the Your name for 'Some role' strings.
3616 * @param integer $courseid the id of this course.
3617 * @param array $data the data that came from the course settings form.
3619 function save_local_role_names($courseid, $data) {
3621 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3623 foreach ($data as $fieldname => $value) {
3624 if (strpos($fieldname, 'role_') !== 0) {
3627 list($ignored, $roleid) = explode('_', $fieldname);
3629 // make up our mind whether we want to delete, update or insert
3631 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
3633 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
3634 $rolename->name
= $value;
3635 $DB->update_record('role_names', $rolename);
3638 $rolename = new stdClass
;
3639 $rolename->contextid
= $context->id
;
3640 $rolename->roleid
= $roleid;
3641 $rolename->name
= $value;
3642 $DB->insert_record('role_names', $rolename);
3648 * Create a course and either return a $course object
3650 * Please note this functions does not verify any access control,
3651 * the calling code is responsible for all validation (usually it is the form definition).
3653 * @param array $editoroptions course description editor options
3654 * @param object $data - all the data needed for an entry in the 'course' table
3655 * @return object new course instance
3657 function create_course($data, $editoroptions = NULL) {
3660 //check the categoryid - must be given for all new courses
3661 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
3663 //check if the shortname already exist
3664 if (!empty($data->shortname
)) {
3665 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
3666 throw new moodle_exception('shortnametaken');
3670 //check if the id number already exist
3671 if (!empty($data->idnumber
)) {
3672 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
3673 throw new moodle_exception('idnumbertaken');
3677 $data->timecreated
= time();
3678 $data->timemodified
= $data->timecreated
;
3680 // place at beginning of any category
3681 $data->sortorder
= 0;
3683 if ($editoroptions) {
3684 // summary text is updated later, we need context to store the files first
3685 $data->summary
= '';
3686 $data->summary_format
= FORMAT_HTML
;
3689 if (!isset($data->visible
)) {
3690 // data not from form, add missing visibility info
3691 $data->visible
= $category->visible
;
3693 $data->visibleold
= $data->visible
;
3695 $newcourseid = $DB->insert_record('course', $data);
3696 $context = get_context_instance(CONTEXT_COURSE
, $newcourseid, MUST_EXIST
);
3698 if ($editoroptions) {
3699 // Save the files used in the summary editor and store
3700 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3701 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
3702 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
3705 $course = $DB->get_record('course', array('id'=>$newcourseid));
3708 blocks_add_default_course_blocks($course);
3710 $section = new stdClass();
3711 $section->course
= $course->id
; // Create a default section.
3712 $section->section
= 0;
3713 $section->summaryformat
= FORMAT_HTML
;
3714 $DB->insert_record('course_sections', $section);
3716 fix_course_sortorder();
3718 // update module restrictions
3719 if ($course->restrictmodules
) {
3720 if (isset($data->allowedmods
)) {
3721 update_restricted_mods($course, $data->allowedmods
);
3723 if (!empty($CFG->defaultallowedmodules
)) {
3724 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules
));
3729 // new context created - better mark it as dirty
3730 mark_context_dirty($context->path
);
3732 // Save any custom role names.
3733 save_local_role_names($course->id
, (array)$data);
3735 // set up enrolments
3736 enrol_course_updated(true, $course, $data);
3738 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3741 events_trigger('course_created', $course);
3749 * Please note this functions does not verify any access control,
3750 * the calling code is responsible for all validation (usually it is the form definition).
3752 * @param object $data - all the data needed for an entry in the 'course' table
3753 * @param array $editoroptions course description editor options
3756 function update_course($data, $editoroptions = NULL) {
3759 $data->timemodified
= time();
3761 $oldcourse = $DB->get_record('course', array('id'=>$data->id
), '*', MUST_EXIST
);
3762 $context = get_context_instance(CONTEXT_COURSE
, $oldcourse->id
);
3764 if ($editoroptions) {
3765 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3768 if (!isset($data->category
) or empty($data->category
)) {
3769 // prevent nulls and 0 in category field
3770 unset($data->category
);
3772 $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
3774 if (!isset($data->visible
)) {
3775 // data not from form, add missing visibility info
3776 $data->visible
= $oldcourse->visible
;
3779 if ($data->visible
!= $oldcourse->visible
) {
3780 // reset the visibleold flag when manually hiding/unhiding course
3781 $data->visibleold
= $data->visible
;
3784 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
3785 if (empty($newcategory->visible
)) {
3786 // make sure when moving into hidden category the course is hidden automatically
3792 // Update with the new data
3793 $DB->update_record('course', $data);
3795 $course = $DB->get_record('course', array('id'=>$data->id
));
3798 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3799 context_moved($context, $newparent);
3802 fix_course_sortorder();
3804 // Test for and remove blocks which aren't appropriate anymore
3805 blocks_remove_inappropriate($course);
3807 // update module restrictions
3808 if (isset($data->allowedmods
)) {
3809 update_restricted_mods($course, $data->allowedmods
);
3812 // Save any custom role names.
3813 save_local_role_names($course->id
, $data);
3815 // update enrol settings
3816 enrol_course_updated(false, $course, $data);
3818 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3821 events_trigger('course_updated', $course);
3825 * Average number of participants
3828 function average_number_of_participants() {
3831 //count total of enrolments for visible course (except front page)
3832 $sql = 'SELECT COUNT(*) FROM (
3833 SELECT DISTINCT ue.userid, e.courseid
3834 FROM {user_enrolments} ue, {enrol} e, {course} c
3835 WHERE ue.enrolid = e.id
3836 AND e.courseid <> :siteid
3837 AND c.id = e.courseid
3838 AND c.visible = 1) as total';
3839 $params = array('siteid' => $SITE->id
);
3840 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3843 //count total of visible courses (minus front page)
3844 $coursetotal = $DB->count_records('course', array('visible' => 1));
3845 $coursetotal = $coursetotal - 1 ;
3847 //average of enrolment
3848 if (empty($coursetotal)) {
3849 $participantaverage = 0;
3851 $participantaverage = $enrolmenttotal / $coursetotal;
3854 return $participantaverage;
3858 * Average number of course modules
3861 function average_number_of_courses_modules() {
3864 //count total of visible course module (except front page)
3865 $sql = 'SELECT COUNT(*) FROM (
3866 SELECT cm.course, cm.module
3867 FROM {course} c, {course_modules} cm
3868 WHERE c.id = cm.course
3871 AND c.visible = 1) as total';
3872 $params = array('siteid' => $SITE->id
);
3873 $moduletotal = $DB->count_records_sql($sql, $params);
3876 //count total of visible courses (minus front page)
3877 $coursetotal = $DB->count_records('course', array('visible' => 1));
3878 $coursetotal = $coursetotal - 1 ;
3880 //average of course module
3881 if (empty($coursetotal)) {
3882 $coursemoduleaverage = 0;
3884 $coursemoduleaverage = $moduletotal / $coursetotal;
3887 return $coursemoduleaverage;
3891 * This class pertains to course requests and contains methods associated with
3892 * create, approving, and removing course requests.
3894 * Please note we do not allow embedded images here because there is no context
3895 * to store them with proper access control.
3897 * @copyright 2009 Sam Hemelryk
3898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3901 * @property-read int $id
3902 * @property-read string $fullname
3903 * @property-read string $shortname
3904 * @property-read string $summary
3905 * @property-read int $summaryformat
3906 * @property-read int $summarytrust
3907 * @property-read string $reason
3908 * @property-read int $requester
3910 class course_request
{
3913 * This is the stdClass that stores the properties for the course request
3914 * and is externally accessed through the __get magic method
3917 protected $properties;
3920 * An array of options for the summary editor used by course request forms.
3921 * This is initially set by {@link summary_editor_options()}
3925 protected static $summaryeditoroptions;
3928 * Static function to prepare the summary editor for working with a course
3932 * @param null|stdClass $data Optional, an object containing the default values
3933 * for the form, these may be modified when preparing the
3934 * editor so this should be called before creating the form
3935 * @return stdClass An object that can be used to set the default values for
3938 public static function prepare($data=null) {
3939 if ($data === null) {
3940 $data = new stdClass
;
3942 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
3947 * Static function to create a new course request when passed an array of properties
3950 * This function also handles saving any files that may have been used in the editor
3953 * @param stdClass $data
3954 * @return course_request The newly created course request
3956 public static function create($data) {
3957 global $USER, $DB, $CFG;
3958 $data->requester
= $USER->id
;
3960 // Summary is a required field so copy the text over
3961 $data->summary
= $data->summary_editor
['text'];
3962 $data->summaryformat
= $data->summary_editor
['format'];
3964 $data->id
= $DB->insert_record('course_request', $data);
3966 // Create a new course_request object and return it
3967 $request = new course_request($data);
3969 // Notify the admin if required.
3970 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
3973 $a->link
= "$CFG->wwwroot/course/pending.php";
3974 $a->user
= fullname($USER);
3975 $subject = get_string('courserequest');
3976 $message = get_string('courserequestnotifyemail', 'admin', $a);
3977 foreach ($users as $user) {
3978 $request->notify($user, $USER, 'courserequested', $subject, $message);
3986 * Returns an array of options to use with a summary editor
3988 * @uses course_request::$summaryeditoroptions
3989 * @return array An array of options to use with the editor
3991 public static function summary_editor_options() {
3993 if (self
::$summaryeditoroptions === null) {
3994 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
3996 return self
::$summaryeditoroptions;
4000 * Loads the properties for this course request object. Id is required and if
4001 * only id is provided then we load the rest of the properties from the database
4003 * @param stdClass|int $properties Either an object containing properties
4004 * or the course_request id to load
4006 public function __construct($properties) {
4008 if (empty($properties->id
)) {
4009 if (empty($properties)) {
4010 throw new coding_exception('You must provide a course request id when creating a course_request object');
4013 $properties = new stdClass
;
4014 $properties->id
= (int)$id;
4017 if (empty($properties->requester
)) {
4018 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
4019 print_error('unknowncourserequest');
4022 $this->properties
= $properties;
4024 $this->properties
->collision
= null;
4028 * Returns the requested property
4030 * @param string $key
4033 public function __get($key) {
4034 return $this->properties
->$key;
4038 * Override this to ensure empty($request->blah) calls return a reliable answer...
4040 * This is required because we define the __get method
4043 * @return bool True is it not empty, false otherwise
4045 public function __isset($key) {
4046 return (!empty($this->properties
->$key));
4050 * Returns the user who requested this course
4052 * Uses a static var to cache the results and cut down the number of db queries
4054 * @staticvar array $requesters An array of cached users
4055 * @return stdClass The user who requested the course
4057 public function get_requester() {
4059 static $requesters= array();
4060 if (!array_key_exists($this->properties
->requester
, $requesters)) {
4061 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
4063 return $requesters[$this->properties
->requester
];
4067 * Checks that the shortname used by the course does not conflict with any other
4068 * courses that exist
4070 * @param string|null $shortnamemark The string to append to the requests shortname
4071 * should a conflict be found
4072 * @return bool true is there is a conflict, false otherwise
4074 public function check_shortname_collision($shortnamemark = '[*]') {
4077 if ($this->properties
->collision
!== null) {
4078 return $this->properties
->collision
;
4081 if (empty($this->properties
->shortname
)) {
4082 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
4083 $this->properties
->collision
= false;
4084 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
4085 if (!empty($shortnamemark)) {
4086 $this->properties
->shortname
.= ' '.$shortnamemark;
4088 $this->properties
->collision
= true;
4090 $this->properties
->collision
= false;
4092 return $this->properties
->collision
;
4096 * This function approves the request turning it into a course
4098 * This function converts the course request into a course, at the same time
4099 * transferring any files used in the summary to the new course and then removing
4100 * the course request and the files associated with it.
4102 * @return int The id of the course that was created from this request
4104 public function approve() {
4105 global $CFG, $DB, $USER;
4107 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
4109 $category = get_course_category($CFG->defaultrequestcategory
);
4110 $courseconfig = get_config('moodlecourse');
4112 // Transfer appropriate settings
4113 $data = clone($this->properties
);
4115 unset($data->reason
);
4116 unset($data->requester
);
4119 $data->category
= $category->id
;
4120 $data->sortorder
= $category->sortorder
; // place as the first in category
4122 // Set misc settings
4123 $data->requested
= 1;
4124 if (!empty($CFG->restrictmodulesfor
) && $CFG->restrictmodulesfor
!= 'none' && !empty($CFG->restrictbydefault
)) {
4125 $data->restrictmodules
= 1;
4128 // Apply course default settings
4129 $data->format
= $courseconfig->format
;
4130 $data->numsections
= $courseconfig->numsections
;
4131 $data->hiddensections
= $courseconfig->hiddensections
;
4132 $data->newsitems
= $courseconfig->newsitems
;
4133 $data->showgrades
= $courseconfig->showgrades
;
4134 $data->showreports
= $courseconfig->showreports
;
4135 $data->maxbytes
= $courseconfig->maxbytes
;
4136 $data->groupmode
= $courseconfig->groupmode
;
4137 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
4138 $data->visible
= $courseconfig->visible
;
4139 $data->visibleold
= $data->visible
;
4140 $data->lang
= $courseconfig->lang
;
4142 $course = create_course($data);
4143 $context = get_context_instance(CONTEXT_COURSE
, $course->id
, MUST_EXIST
);
4145 // add enrol instances
4146 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
4147 if ($manual = enrol_get_plugin('manual')) {
4148 $manual->add_default_instance($course);
4152 // enrol the requester as teacher if necessary
4153 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4154 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
4159 $a = new stdClass();
4160 $a->name
= $course->fullname
;
4161 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
4162 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4168 * Reject a course request
4170 * This function rejects a course request, emailing the requesting user the
4171 * provided notice and then removing the request from the database
4173 * @param string $notice The message to display to the user
4175 public function reject($notice) {
4177 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
4178 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4183 * Deletes the course request and any associated files
4185 public function delete() {
4187 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
4191 * Send a message from one user to another using events_trigger
4193 * @param object $touser
4194 * @param object $fromuser
4195 * @param string $name
4196 * @param string $subject
4197 * @param string $message
4199 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4200 $eventdata = new stdClass();
4201 $eventdata->component
= 'moodle';
4202 $eventdata->name
= $name;
4203 $eventdata->userfrom
= $fromuser;
4204 $eventdata->userto
= $touser;
4205 $eventdata->subject
= $subject;
4206 $eventdata->fullmessage
= $message;
4207 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
4208 $eventdata->fullmessagehtml
= '';
4209 $eventdata->smallmessage
= '';
4210 $eventdata->notification
= 1;
4211 message_send($eventdata);
4216 * Return a list of page types
4217 * @param string $pagetype current page type
4218 * @param stdClass $parentcontext Block's parent context
4219 * @param stdClass $currentcontext Current context of block
4221 function course_pagetypelist($pagetype, $parentcontext, $currentcontext) {
4222 // if above course context ,display all course fomats
4223 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id
);
4224 if ($course->id
== SITEID
) {
4225 return array('*'=>get_string('page-x', 'pagetype'));
4227 return array('*'=>get_string('page-x', 'pagetype'),
4228 'course-*'=>get_string('page-course-x', 'pagetype'),
4229 'course-view-*'=>get_string('page-course-view-x', 'pagetype'),
4230 'mod-*'=>get_string('page-mod-x', 'pagetype')