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');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
38 * Number of courses to display when summaries are included.
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
73 if (strpos($url, '../') === 0) {
74 $url = ltrim($url, '.');
76 $url = "/course/$url";
81 $url = "/$module/$url";
94 $url = "/message/$url";
106 $url = "/mod/$module/$url";
110 //now let's sanitise urls - there might be some ugly nasties:-(
111 $parts = explode('?', $url);
112 $script = array_shift($parts);
113 if (strpos($script, 'http') === 0) {
114 $script = clean_param($script, PARAM_URL);
116 $script = clean_param($script, PARAM_PATH);
121 $query = implode('', $parts);
122 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
123 $parts = explode('&', $query);
124 $eq = urlencode('=');
125 foreach ($parts as $key=>$part) {
126 $part = urlencode(urldecode($part));
127 $part = str_replace($eq, '=', $part);
128 $parts[$key] = $part;
130 $query = '?'.implode('&', $parts);
133 return $script.$query;
137 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
138 $modname="", $modid=0, $modaction="", $groupid=0) {
141 // It is assumed that $date is the GMT time of midnight for that day,
142 // and so the next 86400 seconds worth of logs are printed.
144 /// Setup for group handling.
146 // TODO: I don't understand group/context/etc. enough to be able to do
147 // something interesting with it here
148 // What is the context of a remote course?
150 /// If the group mode is separate, and this user does not have editing privileges,
151 /// then only the user's group can be viewed.
152 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
153 // $groupid = get_current_group($course->id);
155 /// If this course doesn't have groups, no groupid can be specified.
156 //else if (!$course->groupmode) {
165 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
167 LEFT JOIN {user} u ON l.userid = u.id
171 $where .= "l.hostid = :hostid";
172 $params['hostid'] = $hostid;
174 // TODO: Is 1 really a magic number referring to the sitename?
175 if ($course != SITEID || $modid != 0) {
176 $where .= " AND l.course=:courseid";
177 $params['courseid'] = $course;
181 $where .= " AND l.module = :modname";
182 $params['modname'] = $modname;
185 if ('site_errors' === $modid) {
186 $where .= " AND ( l.action='error' OR l.action='infected' )";
188 //TODO: This assumes that modids are the same across sites... probably
190 $where .= " AND l.cmid = :modid";
191 $params['modid'] = $modid;
195 $firstletter = substr($modaction, 0, 1);
196 if ($firstletter == '-') {
197 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
198 $params['modaction'] = '%'.substr($modaction, 1).'%';
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
201 $params['modaction'] = '%'.$modaction.'%';
206 $where .= " AND l.userid = :user";
207 $params['user'] = $user;
211 $enddate = $date + 86400;
212 $where .= " AND l.time > :date AND l.time < :enddate";
213 $params['date'] = $date;
214 $params['enddate'] = $enddate;
218 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
219 if(!empty($result['totalcount'])) {
220 $where .= " ORDER BY $order";
221 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
223 $result['logs'] = array();
228 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
229 $modname="", $modid=0, $modaction="", $groupid=0) {
230 global $DB, $SESSION, $USER;
231 // It is assumed that $date is the GMT time of midnight for that day,
232 // and so the next 86400 seconds worth of logs are printed.
234 /// Setup for group handling.
236 /// If the group mode is separate, and this user does not have editing privileges,
237 /// then only the user's group can be viewed.
238 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
239 if (isset($SESSION->currentgroup[$course->id])) {
240 $groupid = $SESSION->currentgroup[$course->id];
242 $groupid = groups_get_all_groups($course->id, $USER->id);
243 if (is_array($groupid)) {
244 $groupid = array_shift(array_keys($groupid));
245 $SESSION->currentgroup[$course->id] = $groupid;
251 /// If this course doesn't have groups, no groupid can be specified.
252 else if (!$course->groupmode) {
259 if ($course->id != SITEID || $modid != 0) {
260 $joins[] = "l.course = :courseid";
261 $params['courseid'] = $course->id;
265 $joins[] = "l.module = :modname";
266 $params['modname'] = $modname;
269 if ('site_errors' === $modid) {
270 $joins[] = "( l.action='error' OR l.action='infected' )";
272 $joins[] = "l.cmid = :modid";
273 $params['modid'] = $modid;
277 $firstletter = substr($modaction, 0, 1);
278 if ($firstletter == '-') {
279 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
280 $params['modaction'] = '%'.substr($modaction, 1).'%';
282 $joins[] = $DB->sql_like('l.action', ':modaction', false);
283 $params['modaction'] = '%'.$modaction.'%';
288 /// Getting all members of a group.
289 if ($groupid and !$user) {
290 if ($gusers = groups_get_members($groupid)) {
291 $gusers = array_keys($gusers);
292 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
294 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
298 $joins[] = "l.userid = :userid";
299 $params['userid'] = $user;
303 $enddate = $date + 86400;
304 $joins[] = "l.time > :date AND l.time < :enddate";
305 $params['date'] = $date;
306 $params['enddate'] = $enddate;
309 $selector = implode(' AND ', $joins);
311 $totalcount = 0; // Initialise
313 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
314 $result['totalcount'] = $totalcount;
319 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
320 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
322 global $CFG, $DB, $OUTPUT;
324 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
325 $modname, $modid, $modaction, $groupid)) {
326 echo $OUTPUT->notification("No logs found!");
327 echo $OUTPUT->footer();
333 if ($course->id == SITEID) {
335 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
336 foreach ($ccc as $cc) {
337 $courses[$cc->id] = $cc->shortname;
341 $courses[$course->id] = $course->shortname;
344 $totalcount = $logs['totalcount'];
347 $tt = getdate(time());
348 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
350 $strftimedatetime = get_string("strftimedatetime");
352 echo "<div class=\"info\">\n";
353 print_string("displayingrecords", "", $totalcount);
356 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
358 $table = new html_table();
359 $table->classes = array('logtable','generaltable');
360 $table->align = array('right', 'left', 'left');
361 $table->head = array(
363 get_string('ip_address'),
364 get_string('fullnameuser'),
365 get_string('action'),
368 $table->data = array();
370 if ($course->id == SITEID) {
371 array_unshift($table->align, 'left');
372 array_unshift($table->head, get_string('course'));
375 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
376 if (empty($logs['logs'])) {
377 $logs['logs'] = array();
380 foreach ($logs['logs'] as $log) {
382 if (isset($ldcache[$log->module][$log->action])) {
383 $ld = $ldcache[$log->module][$log->action];
385 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
386 $ldcache[$log->module][$log->action] = $ld;
388 if ($ld && is_numeric($log->info)) {
389 // ugly hack to make sure fullname is shown correctly
390 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
391 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
393 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
398 $log->info = format_string($log->info);
400 // If $log->url has been trimmed short by the db size restriction
401 // code in add_to_log, keep a note so we don't add a link to a broken url
402 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
405 if ($course->id == SITEID) {
406 if (empty($log->course)) {
407 $row[] = get_string('site');
409 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
413 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
415 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
416 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
418 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
420 $displayaction="$log->module $log->action";
422 $row[] = $displayaction;
424 $link = make_log_url($log->module,$log->url);
425 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
428 $table->data[] = $row;
431 echo html_writer::table($table);
432 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
436 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
437 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
439 global $CFG, $DB, $OUTPUT;
441 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
442 $modname, $modid, $modaction, $groupid)) {
443 echo $OUTPUT->notification("No logs found!");
444 echo $OUTPUT->footer();
448 if ($course->id == SITEID) {
450 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
451 foreach ($ccc as $cc) {
452 $courses[$cc->id] = $cc->shortname;
457 $totalcount = $logs['totalcount'];
460 $tt = getdate(time());
461 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
463 $strftimedatetime = get_string("strftimedatetime");
465 echo "<div class=\"info\">\n";
466 print_string("displayingrecords", "", $totalcount);
469 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
471 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
473 if ($course->id == SITEID) {
474 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
476 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
477 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
478 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
479 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
480 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
483 if (empty($logs['logs'])) {
489 foreach ($logs['logs'] as $log) {
491 $log->info = $log->coursename;
492 $row = ($row + 1) % 2;
494 if (isset($ldcache[$log->module][$log->action])) {
495 $ld = $ldcache[$log->module][$log->action];
497 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
498 $ldcache[$log->module][$log->action] = $ld;
500 if (0 && $ld && !empty($log->info)) {
501 // ugly hack to make sure fullname is shown correctly
502 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
503 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
505 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
510 $log->info = format_string($log->info);
512 echo '<tr class="r'.$row.'">';
513 if ($course->id == SITEID) {
514 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
515 echo "<td class=\"r$row c0\" >\n";
516 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
519 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
520 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
521 echo "<td class=\"r$row c2\" >\n";
522 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
523 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
525 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
526 echo "<td class=\"r$row c3\" >\n";
527 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
529 echo "<td class=\"r$row c4\">\n";
530 echo $log->action .': '.$log->module;
532 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
537 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
541 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
542 $modid, $modaction, $groupid) {
545 require_once($CFG->libdir . '/csvlib.class.php');
547 $csvexporter = new csv_export_writer('tab');
550 $header[] = get_string('course');
551 $header[] = get_string('time');
552 $header[] = get_string('ip_address');
553 $header[] = get_string('fullnameuser');
554 $header[] = get_string('action');
555 $header[] = get_string('info');
557 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
558 $modname, $modid, $modaction, $groupid)) {
564 if ($course->id == SITEID) {
566 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
567 foreach ($ccc as $cc) {
568 $courses[$cc->id] = $cc->shortname;
572 $courses[$course->id] = $course->shortname;
577 $tt = getdate(time());
578 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
580 $strftimedatetime = get_string("strftimedatetime");
582 $csvexporter->set_filename('logs', '.txt');
583 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
584 $csvexporter->add_data($title);
585 $csvexporter->add_data($header);
587 if (empty($logs['logs'])) {
591 foreach ($logs['logs'] as $log) {
592 if (isset($ldcache[$log->module][$log->action])) {
593 $ld = $ldcache[$log->module][$log->action];
595 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
596 $ldcache[$log->module][$log->action] = $ld;
598 if ($ld && is_numeric($log->info)) {
599 // ugly hack to make sure fullname is shown correctly
600 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
601 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
603 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
608 $log->info = format_string($log->info);
609 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
611 $coursecontext = context_course::instance($course->id);
612 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
613 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
614 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
615 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
616 $csvexporter->add_data($row);
618 $csvexporter->download_file();
623 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
624 $modid, $modaction, $groupid) {
628 require_once("$CFG->libdir/excellib.class.php");
630 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
631 $modname, $modid, $modaction, $groupid)) {
637 if ($course->id == SITEID) {
639 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
640 foreach ($ccc as $cc) {
641 $courses[$cc->id] = $cc->shortname;
645 $courses[$course->id] = $course->shortname;
650 $tt = getdate(time());
651 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
653 $strftimedatetime = get_string("strftimedatetime");
655 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
656 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
659 $workbook = new MoodleExcelWorkbook('-');
660 $workbook->send($filename);
662 $worksheet = array();
663 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
664 get_string('fullnameuser'), get_string('action'), get_string('info'));
666 // Creating worksheets
667 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
668 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
669 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
670 $worksheet[$wsnumber]->set_column(1, 1, 30);
671 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
672 userdate(time(), $strftimedatetime));
674 foreach ($headers as $item) {
675 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
680 if (empty($logs['logs'])) {
685 $formatDate =& $workbook->add_format();
686 $formatDate->set_num_format(get_string('log_excel_date_format'));
688 $row = FIRSTUSEDEXCELROW;
690 $myxls =& $worksheet[$wsnumber];
691 foreach ($logs['logs'] as $log) {
692 if (isset($ldcache[$log->module][$log->action])) {
693 $ld = $ldcache[$log->module][$log->action];
695 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
696 $ldcache[$log->module][$log->action] = $ld;
698 if ($ld && is_numeric($log->info)) {
699 // ugly hack to make sure fullname is shown correctly
700 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
701 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
703 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
708 $log->info = format_string($log->info);
709 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
712 if ($row > EXCELROWS) {
714 $myxls =& $worksheet[$wsnumber];
715 $row = FIRSTUSEDEXCELROW;
719 $coursecontext = context_course::instance($course->id);
721 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
722 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
723 $myxls->write($row, 2, $log->ip, '');
724 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
725 $myxls->write($row, 3, $fullname, '');
726 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
727 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
728 $myxls->write($row, 5, $log->info, '');
737 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
738 $modid, $modaction, $groupid) {
742 require_once("$CFG->libdir/odslib.class.php");
744 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
745 $modname, $modid, $modaction, $groupid)) {
751 if ($course->id == SITEID) {
753 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
754 foreach ($ccc as $cc) {
755 $courses[$cc->id] = $cc->shortname;
759 $courses[$course->id] = $course->shortname;
764 $tt = getdate(time());
765 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
767 $strftimedatetime = get_string("strftimedatetime");
769 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
770 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
773 $workbook = new MoodleODSWorkbook('-');
774 $workbook->send($filename);
776 $worksheet = array();
777 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
778 get_string('fullnameuser'), get_string('action'), get_string('info'));
780 // Creating worksheets
781 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
782 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
783 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
784 $worksheet[$wsnumber]->set_column(1, 1, 30);
785 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
786 userdate(time(), $strftimedatetime));
788 foreach ($headers as $item) {
789 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
794 if (empty($logs['logs'])) {
799 $formatDate =& $workbook->add_format();
800 $formatDate->set_num_format(get_string('log_excel_date_format'));
802 $row = FIRSTUSEDEXCELROW;
804 $myxls =& $worksheet[$wsnumber];
805 foreach ($logs['logs'] as $log) {
806 if (isset($ldcache[$log->module][$log->action])) {
807 $ld = $ldcache[$log->module][$log->action];
809 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
810 $ldcache[$log->module][$log->action] = $ld;
812 if ($ld && is_numeric($log->info)) {
813 // ugly hack to make sure fullname is shown correctly
814 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
815 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
817 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
822 $log->info = format_string($log->info);
823 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
826 if ($row > EXCELROWS) {
828 $myxls =& $worksheet[$wsnumber];
829 $row = FIRSTUSEDEXCELROW;
833 $coursecontext = context_course::instance($course->id);
835 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
836 $myxls->write_date($row, 1, $log->time);
837 $myxls->write_string($row, 2, $log->ip);
838 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
839 $myxls->write_string($row, 3, $fullname);
840 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
841 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
842 $myxls->write_string($row, 5, $log->info);
852 * For a given course, returns an array of course activity objects
853 * Each item in the array contains he following properties:
855 function get_array_of_activities($courseid) {
856 // cm - course module id
857 // mod - name of the module (eg forum)
858 // section - the number of the section (eg week or topic)
859 // name - the name of the instance
860 // visible - is the instance visible or not
861 // groupingid - grouping id
862 // groupmembersonly - is this instance visible to group members only
863 // extra - contains extra string to include in any link
865 if(!empty($CFG->enableavailability)) {
866 require_once($CFG->libdir.'/conditionlib.php');
869 $course = $DB->get_record('course', array('id'=>$courseid));
871 if (empty($course)) {
872 throw new moodle_exception('courseidnotfound');
877 $rawmods = get_course_mods($courseid);
878 if (empty($rawmods)) {
879 return $mod; // always return array
882 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
883 foreach ($sections as $section) {
884 if (!empty($section->sequence)) {
885 $sequence = explode(",", $section->sequence);
886 foreach ($sequence as $seq) {
887 if (empty($rawmods[$seq])) {
890 $mod[$seq] = new stdClass();
891 $mod[$seq]->id = $rawmods[$seq]->instance;
892 $mod[$seq]->cm = $rawmods[$seq]->id;
893 $mod[$seq]->mod = $rawmods[$seq]->modname;
895 // Oh dear. Inconsistent names left here for backward compatibility.
896 $mod[$seq]->section = $section->section;
897 $mod[$seq]->sectionid = $rawmods[$seq]->section;
899 $mod[$seq]->module = $rawmods[$seq]->module;
900 $mod[$seq]->added = $rawmods[$seq]->added;
901 $mod[$seq]->score = $rawmods[$seq]->score;
902 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
903 $mod[$seq]->visible = $rawmods[$seq]->visible;
904 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
905 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
906 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
907 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
908 $mod[$seq]->indent = $rawmods[$seq]->indent;
909 $mod[$seq]->completion = $rawmods[$seq]->completion;
910 $mod[$seq]->extra = "";
911 $mod[$seq]->completiongradeitemnumber =
912 $rawmods[$seq]->completiongradeitemnumber;
913 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
914 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
915 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
916 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
917 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
918 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
919 if (!empty($CFG->enableavailability)) {
920 condition_info::fill_availability_conditions($rawmods[$seq]);
921 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
922 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
923 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
926 $modname = $mod[$seq]->mod;
927 $functionname = $modname."_get_coursemodule_info";
929 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
933 include_once("$CFG->dirroot/mod/$modname/lib.php");
935 if ($hasfunction = function_exists($functionname)) {
936 if ($info = $functionname($rawmods[$seq])) {
937 if (!empty($info->icon)) {
938 $mod[$seq]->icon = $info->icon;
940 if (!empty($info->iconcomponent)) {
941 $mod[$seq]->iconcomponent = $info->iconcomponent;
943 if (!empty($info->name)) {
944 $mod[$seq]->name = $info->name;
946 if ($info instanceof cached_cm_info) {
947 // When using cached_cm_info you can include three new fields
948 // that aren't available for legacy code
949 if (!empty($info->content)) {
950 $mod[$seq]->content = $info->content;
952 if (!empty($info->extraclasses)) {
953 $mod[$seq]->extraclasses = $info->extraclasses;
955 if (!empty($info->iconurl)) {
956 $mod[$seq]->iconurl = $info->iconurl;
958 if (!empty($info->onclick)) {
959 $mod[$seq]->onclick = $info->onclick;
961 if (!empty($info->customdata)) {
962 $mod[$seq]->customdata = $info->customdata;
965 // When using a stdclass, the (horrible) deprecated ->extra field
966 // is available for BC
967 if (!empty($info->extra)) {
968 $mod[$seq]->extra = $info->extra;
973 // When there is no modname_get_coursemodule_info function,
974 // but showdescriptions is enabled, then we use the 'intro'
975 // and 'introformat' fields in the module table
976 if (!$hasfunction && $rawmods[$seq]->showdescription) {
977 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
978 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
979 // Set content from intro and introformat. Filters are disabled
980 // because we filter it with format_text at display time
981 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
982 $modvalues, $rawmods[$seq]->id, false);
984 // To save making another query just below, put name in here
985 $mod[$seq]->name = $modvalues->name;
988 if (!isset($mod[$seq]->name)) {
989 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
992 // Minimise the database size by unsetting default options when they are
993 // 'empty'. This list corresponds to code in the cm_info constructor.
994 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
995 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
996 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
997 'availableuntil', 'conditionscompletion', 'conditionsgrade',
998 'completionview', 'completionexpected', 'score', 'showdescription')
1000 if (property_exists($mod[$seq], $property) &&
1001 empty($mod[$seq]->{$property})) {
1002 unset($mod[$seq]->{$property});
1005 // Special case: this value is usually set to null, but may be 0
1006 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1007 is_null($mod[$seq]->completiongradeitemnumber)) {
1008 unset($mod[$seq]->completiongradeitemnumber);
1018 * Returns the localised human-readable names of all used modules
1020 * @param bool $plural if true returns the plural forms of the names
1021 * @return array where key is the module name (component name without 'mod_') and
1022 * the value is the human-readable string. Array sorted alphabetically by value
1024 function get_module_types_names($plural = false) {
1025 static $modnames = null;
1027 if ($modnames === null) {
1028 $modnames = array(0 => array(), 1 => array());
1029 if ($allmods = $DB->get_records("modules")) {
1030 foreach ($allmods as $mod) {
1031 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1032 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1033 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1036 collatorlib::asort($modnames[0]);
1037 collatorlib::asort($modnames[1]);
1040 return $modnames[(int)$plural];
1044 * Set highlighted section. Only one section can be highlighted at the time.
1046 * @param int $courseid course id
1047 * @param int $marker highlight section with this number, 0 means remove higlightin
1050 function course_set_marker($courseid, $marker) {
1052 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1053 format_base::reset_course_cache($courseid);
1057 * For a given course section, marks it visible or hidden,
1058 * and does the same for every activity in that section
1060 * @param int $courseid course id
1061 * @param int $sectionnumber The section number to adjust
1062 * @param int $visibility The new visibility
1063 * @return array A list of resources which were hidden in the section
1065 function set_section_visible($courseid, $sectionnumber, $visibility) {
1068 $resourcestotoggle = array();
1069 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1070 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1071 if (!empty($section->sequence)) {
1072 $modules = explode(",", $section->sequence);
1073 foreach ($modules as $moduleid) {
1074 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1076 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1077 set_coursemodule_visible($moduleid, $cm->visibleold);
1079 // We hide the section, so we hide the module but we store the original state in visibleold.
1080 set_coursemodule_visible($moduleid, 0);
1081 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1086 rebuild_course_cache($courseid, true);
1088 // Determine which modules are visible for AJAX update
1089 if (!empty($modules)) {
1090 list($insql, $params) = $DB->get_in_or_equal($modules);
1091 $select = 'id ' . $insql . ' AND visible = ?';
1092 array_push($params, $visibility);
1094 $select .= ' AND visibleold = 1';
1096 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1099 return $resourcestotoggle;
1103 * Retrieve all metadata for the requested modules
1105 * @param object $course The Course
1106 * @param array $modnames An array containing the list of modules and their
1108 * @param int $sectionreturn The section to return to
1109 * @return array A list of stdClass objects containing metadata about each
1112 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1113 global $CFG, $OUTPUT;
1115 // get_module_metadata will be called once per section on the page and courses may show
1116 // different modules to one another
1117 static $modlist = array();
1118 if (!isset($modlist[$course->id])) {
1119 $modlist[$course->id] = array();
1123 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1124 if ($sectionreturn !== null) {
1125 $urlbase->param('sr', $sectionreturn);
1127 foreach($modnames as $modname => $modnamestr) {
1128 if (!course_allowed_module($course, $modname)) {
1131 if (isset($modlist[$course->id][$modname])) {
1132 // This module is already cached
1133 $return[$modname] = $modlist[$course->id][$modname];
1137 // Include the module lib
1138 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1139 if (!file_exists($libfile)) {
1142 include_once($libfile);
1144 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1145 $gettypesfunc = $modname.'_get_types';
1146 if (function_exists($gettypesfunc)) {
1147 $types = $gettypesfunc();
1148 if (is_array($types) && count($types) > 0) {
1149 $group = new stdClass();
1150 $group->name = $modname;
1151 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1152 foreach($types as $type) {
1153 if ($type->typestr === '--') {
1156 if (strpos($type->typestr, '--') === 0) {
1157 $group->title = str_replace('--', '', $type->typestr);
1160 // Set the Sub Type metadata
1161 $subtype = new stdClass();
1162 $subtype->title = $type->typestr;
1163 $subtype->type = str_replace('&', '&', $type->type);
1164 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1165 $subtype->archetype = $type->modclass;
1167 // The group archetype should match the subtype archetypes and all subtypes
1168 // should have the same archetype
1169 $group->archetype = $subtype->archetype;
1171 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1172 $subtype->help = get_string('help' . $subtype->name, $modname);
1174 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1175 $group->types[] = $subtype;
1177 $modlist[$course->id][$modname] = $group;
1180 $module = new stdClass();
1181 $module->title = $modnamestr;
1182 $module->name = $modname;
1183 $module->link = new moodle_url($urlbase, array('add' => $modname));
1184 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1185 $sm = get_string_manager();
1186 if ($sm->string_exists('modulename_help', $modname)) {
1187 $module->help = get_string('modulename_help', $modname);
1188 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1189 $link = get_string('modulename_link', $modname);
1190 $linktext = get_string('morehelp');
1191 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1194 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1195 $modlist[$course->id][$modname] = $module;
1197 if (isset($modlist[$course->id][$modname])) {
1198 $return[$modname] = $modlist[$course->id][$modname];
1200 debugging("Invalid module metadata configuration for {$modname}");
1208 * Return the course category context for the category with id $categoryid, except
1209 * that if $categoryid is 0, return the system context.
1211 * @param integer $categoryid a category id or 0.
1212 * @return object the corresponding context
1214 function get_category_or_system_context($categoryid) {
1216 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1218 return context_system::instance();
1223 * This function generates a structured array of courses and categories.
1225 * The depth of categories is limited by $CFG->maxcategorydepth however there
1226 * is no limit on the number of courses!
1228 * Suitable for use with the course renderers course_category_tree method:
1229 * $renderer = $PAGE->get_renderer('core','course');
1230 * echo $renderer->course_category_tree(get_course_category_tree());
1232 * @global moodle_database $DB
1236 function get_course_category_tree($id = 0, $depth = 0) {
1238 require_once($CFG->libdir. '/coursecatlib.php');
1239 if (!$coursecat = coursecat::get($id, IGNORE_MISSING)) {
1242 $categories = array();
1243 $categoryids = array();
1244 foreach ($coursecat->get_children() as $child) {
1245 $categories[] = $category = (object)convert_to_array($child);
1246 $categoryids[$category->id] = $category;
1247 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
1248 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
1249 foreach ($subcategories as $subid=>$subcat) {
1250 $categoryids[$subid] = $subcat;
1252 $category->courses = array();
1257 // This is a recursive call so return the required array
1258 return array($categories, $categoryids);
1261 if (empty($categoryids)) {
1262 // No categories available (probably all hidden).
1266 // The depth is 0 this function has just been called so we can finish it off
1268 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1269 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
1271 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
1275 WHERE c.category $catsql ORDER BY c.sortorder ASC";
1276 if ($courses = $DB->get_records_sql($sql, $catparams)) {
1277 // loop throught them
1278 foreach ($courses as $course) {
1279 if ($course->id == SITEID) {
1282 context_instance_preload($course);
1283 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1284 $categoryids[$course->category]->courses[$course->id] = $course;
1292 * Recursive function to print out all the categories in a nice format
1293 * with or without courses included
1295 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1297 require_once($CFG->libdir. '/coursecatlib.php');
1299 // maxcategorydepth == 0 meant no limit
1300 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
1304 // make sure category is visible to the current user
1306 if (!$coursecat = coursecat::get($category->id, IGNORE_MISSING)) {
1310 $coursecat = coursecat::get(0);
1313 if (!$categorycourses) {
1314 $categorycourses = get_category_courses_array($coursecat->id);
1317 if ($coursecat->id) {
1318 print_category_info($category, $depth, $showcourses, $categorycourses[$category->id]);
1321 if ($categories = $coursecat->get_children()) { // Print all the children recursively
1322 $countcats = count($categories);
1326 foreach ($categories as $cat) {
1328 if ($count == $countcats) {
1331 $up = $first ? false : true;
1332 $down = $last ? false : true;
1335 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses, $categorycourses);
1341 * Gets an array whose keys are category ids and whose values are arrays of courses in the corresponding category.
1343 * @param int $categoryid
1346 function get_category_courses_array($categoryid = 0) {
1347 $tree = get_course_category_tree($categoryid);
1348 $flattened = array();
1349 foreach ($tree as $category) {
1350 get_category_courses_array_recursively($flattened, $category);
1356 * Recursive function to help flatten the course category tree.
1358 * Do not call this function directly, instead calll its parent function {@link get_category_courses_array}
1360 * @param array &$flattened An array passed by reference in which to store courses for each category.
1361 * @param stdClass $category The category to get courses for.
1363 function get_category_courses_array_recursively(array &$flattened, $category) {
1364 $flattened[$category->id] = $category->courses;
1365 foreach ($category->categories as $childcategory) {
1366 get_category_courses_array_recursively($flattened, $childcategory);
1371 * Returns full course categories trees to be used in html_writer::select()
1373 * Calls {@link coursecat::make_categories_list()} to build the tree and
1374 * adds whitespace to denote nesting
1376 * @return array array mapping coursecat id to the display name
1378 function make_categories_options() {
1380 require_once($CFG->libdir. '/coursecatlib.php');
1381 $cats = coursecat::make_categories_list();
1382 foreach ($cats as $key => $value) {
1383 $cats[$key] = str_repeat(' ', coursecat::get($key)->depth - 1). $value;
1389 * Prints the category information.
1391 * This function is only used by print_whole_category_list() above
1393 * @param stdClass $category
1394 * @param int $depth The depth of the category.
1395 * @param bool $showcourses If set to true course information will also be printed.
1396 * @param array|null $courses An array of courses belonging to the category, or null if you don't have it yet.
1398 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1399 global $CFG, $DB, $OUTPUT;
1401 $strsummary = get_string('summary');
1404 if (!$category->visible) {
1405 $catlinkcss = array('class'=>'dimmed');
1407 static $coursecount = null;
1408 if (null === $coursecount) {
1409 // only need to check this once
1410 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
1413 if ($showcourses and $coursecount) {
1414 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
1416 $catimage = " ";
1419 if (is_null($courses)) {
1420 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
1422 $context = context_coursecat::instance($category->id);
1423 $fullname = format_string($category->name, true, array('context' => $context));
1425 if ($showcourses and $coursecount) {
1426 echo '<div class="categorylist clearfix">';
1428 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
1429 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
1430 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
1434 for ($i=0; $i< $depth; $i++) {
1435 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
1441 echo html_writer::tag('div', $html, array('class'=>'category'));
1442 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
1444 // does the depth exceed maxcategorydepth
1445 // maxcategorydepth == 0 or unset meant no limit
1446 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
1447 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
1448 foreach ($courses as $course) {
1450 if (!$course->visible) {
1451 $linkcss = array('class'=>'dimmed');
1454 $coursename = get_course_display_name_for_list($course);
1455 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
1459 if ($icons = enrol_get_course_info_icons($course)) {
1460 foreach ($icons as $pix_icon) {
1461 $courseicon = $OUTPUT->render($pix_icon);
1465 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
1467 if ($course->summary) {
1468 $link = new moodle_url('/course/info.php?id='.$course->id);
1469 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
1470 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
1471 array('title'=>$strsummary));
1473 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
1477 for ($i=0; $i <= $depth; $i++) {
1478 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
1479 $coursecontent = '';
1481 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
1486 echo '<div class="categorylist">';
1488 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
1489 if (count($courses) > 0) {
1490 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
1494 for ($i=0; $i< $depth; $i++) {
1495 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
1502 echo html_writer::tag('div', $html, array('class'=>'category'));
1503 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
1509 * Print the buttons relating to course requests.
1511 * @param object $context current page context.
1513 function print_course_request_buttons($context) {
1514 global $CFG, $DB, $OUTPUT;
1515 if (empty($CFG->enablecourserequests)) {
1518 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1519 /// Print a button to request a new course
1520 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1522 /// Print a button to manage pending requests
1523 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1524 $disabled = !$DB->record_exists('course_request', array());
1525 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1530 * Does the user have permission to edit things in this category?
1532 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1533 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1535 function can_edit_in_category($categoryid = 0) {
1536 $context = get_category_or_system_context($categoryid);
1537 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1541 * Print courses in category. If category is 0 then all courses are printed.
1542 * @param int|stdClass $category category object or id.
1543 * @return bool true if courses found and printed, else false.
1545 function print_courses($category) {
1546 global $CFG, $OUTPUT;
1547 require_once($CFG->libdir. '/coursecatlib.php');
1549 if (!is_object($category) && $category==0) {
1550 $categories = coursecat::get(0)->get_children(); // Parent = 0 ie top-level categories only
1551 if (is_array($categories) && count($categories) == 1) {
1552 $category = array_shift($categories);
1553 $courses = get_courses_wmanagers($category->id,
1555 array('summary','summaryformat'));
1557 $courses = get_courses_wmanagers('all',
1559 array('summary','summaryformat'));
1563 $courses = get_courses_wmanagers($category->id,
1565 array('summary','summaryformat'));
1569 echo html_writer::start_tag('ul', array('class'=>'unlist'));
1570 foreach ($courses as $course) {
1571 $coursecontext = context_course::instance($course->id);
1572 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
1573 echo html_writer::start_tag('li');
1574 print_course($course);
1575 echo html_writer::end_tag('li');
1578 echo html_writer::end_tag('ul');
1580 echo $OUTPUT->heading(get_string("nocoursesyet"));
1581 $context = context_system::instance();
1582 if (has_capability('moodle/course:create', $context)) {
1584 if (!empty($category->id)) {
1585 $options['category'] = $category->id;
1587 $options['category'] = $CFG->defaultrequestcategory;
1589 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
1590 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
1591 echo html_writer::end_tag('div');
1599 * Print a description of a course, suitable for browsing in a list.
1601 * @param object $course the course object.
1602 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
1604 function print_course($course, $highlightterms = '') {
1605 global $CFG, $USER, $DB, $OUTPUT;
1607 $context = context_course::instance($course->id);
1609 // Rewrite file URLs so that they are correct
1610 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
1612 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
1613 echo html_writer::start_tag('div', array('class'=>'info'));
1614 echo html_writer::start_tag('h3', array('class'=>'name'));
1616 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
1618 $coursename = get_course_display_name_for_list($course);
1619 $linktext = highlight($highlightterms, format_string($coursename));
1620 $linkparams = array('title'=>get_string('entercourse'));
1621 if (empty($course->visible)) {
1622 $linkparams['class'] = 'dimmed';
1624 echo html_writer::link($linkhref, $linktext, $linkparams);
1625 echo html_writer::end_tag('h3');
1627 /// first find all roles that are supposed to be displayed
1628 if (!empty($CFG->coursecontact)) {
1629 $managerroles = explode(',', $CFG->coursecontact);
1632 if (!isset($course->managers)) {
1633 list($sort, $sortparams) = users_order_by_sql('u');
1634 $rusers = get_role_users($managerroles, $context, true,
1635 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
1636 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
1637 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
1639 // use the managers array if we have it for perf reasosn
1640 // populate the datastructure like output of get_role_users();
1641 foreach ($course->managers as $manager) {
1642 $user = clone($manager->user);
1643 $user->roleid = $manager->roleid;
1644 $user->rolename = $manager->rolename;
1645 $user->roleshortname = $manager->roleshortname;
1646 $user->rolecoursealias = $manager->rolecoursealias;
1647 $rusers[$user->id] = $user;
1651 $namesarray = array();
1652 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1653 foreach ($rusers as $ra) {
1654 if (isset($namesarray[$ra->id])) {
1655 // only display a user once with the higest sortorder role
1659 $role = new stdClass();
1660 $role->id = $ra->roleid;
1661 $role->name = $ra->rolename;
1662 $role->shortname = $ra->roleshortname;
1663 $role->coursealias = $ra->rolecoursealias;
1664 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
1666 $fullname = fullname($ra, $canviewfullnames);
1667 $namesarray[$ra->id] = $rolename.': '.
1668 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
1671 if (!empty($namesarray)) {
1672 echo html_writer::start_tag('ul', array('class'=>'teachers'));
1673 foreach ($namesarray as $name) {
1674 echo html_writer::tag('li', $name);
1676 echo html_writer::end_tag('ul');
1679 echo html_writer::end_tag('div'); // End of info div
1681 echo html_writer::start_tag('div', array('class'=>'summary'));
1682 $options = new stdClass();
1683 $options->noclean = true;
1684 $options->para = false;
1685 $options->overflowdiv = true;
1686 if (!isset($course->summaryformat)) {
1687 $course->summaryformat = FORMAT_MOODLE;
1689 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
1690 if ($icons = enrol_get_course_info_icons($course)) {
1691 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
1692 foreach ($icons as $icon) {
1693 $icon->attributes["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
1694 echo $OUTPUT->render($icon);
1696 echo html_writer::end_tag('div'); // End of enrolmenticons div
1698 echo html_writer::end_tag('div'); // End of summary div
1699 echo html_writer::end_tag('div'); // End of coursebox div
1703 * Prints custom user information on the home page.
1704 * Over time this can include all sorts of information
1706 function print_my_moodle() {
1707 global $USER, $CFG, $DB, $OUTPUT;
1709 if (!isloggedin() or isguestuser()) {
1710 print_error('nopermissions', '', '', 'See My Moodle');
1713 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
1715 $rcourses = array();
1716 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1717 $rcourses = get_my_remotecourses($USER->id);
1718 $rhosts = get_my_remotehosts();
1721 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1723 if (!empty($courses)) {
1724 echo '<ul class="unlist">';
1725 foreach ($courses as $course) {
1726 if ($course->id == SITEID) {
1730 print_course($course);
1737 if (!empty($rcourses)) {
1738 // at the IDP, we know of all the remote courses
1739 foreach ($rcourses as $course) {
1740 print_remote_course($course, "100%");
1742 } elseif (!empty($rhosts)) {
1743 // non-IDP, we know of all the remote servers, but not courses
1744 foreach ($rhosts as $host) {
1745 print_remote_host($host, "100%");
1751 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1752 echo "<table width=\"100%\"><tr><td align=\"center\">";
1753 print_course_search("", false, "short");
1754 echo "</td><td align=\"center\">";
1755 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
1756 echo "</td></tr></table>\n";
1760 if ($DB->count_records("course_categories") > 1) {
1761 echo $OUTPUT->box_start("categorybox");
1762 print_whole_category_list();
1763 echo $OUTPUT->box_end();
1770 function print_remote_course($course, $width="100%") {
1775 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
1777 echo '<div class="coursebox remotecoursebox clearfix">';
1778 echo '<div class="info">';
1779 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1780 $linkcss.' href="'.$url.'">'
1781 . format_string($course->fullname) .'</a><br />'
1782 . format_string($course->hostname) . ' : '
1783 . format_string($course->cat_name) . ' : '
1784 . format_string($course->shortname). '</div>';
1785 echo '</div><div class="summary">';
1786 $options = new stdClass();
1787 $options->noclean = true;
1788 $options->para = false;
1789 $options->overflowdiv = true;
1790 echo format_text($course->summary, $course->summaryformat, $options);
1795 function print_remote_host($host, $width="100%") {
1800 echo '<div class="coursebox clearfix">';
1801 echo '<div class="info">';
1802 echo '<div class="name">';
1803 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
1804 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1805 . s($host['name']).'</a> - ';
1806 echo $host['count'] . ' ' . get_string('courses');
1813 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1815 function add_course_module($mod) {
1818 $mod->added = time();
1821 $cmid = $DB->insert_record("course_modules", $mod);
1822 rebuild_course_cache($mod->course, true);
1827 * Creates missing course section(s) and rebuilds course cache
1829 * @param int|stdClass $courseorid course id or course object
1830 * @param int|array $sections list of relative section numbers to create
1831 * @return bool if there were any sections created
1833 function course_create_sections_if_missing($courseorid, $sections) {
1835 if (!is_array($sections)) {
1836 $sections = array($sections);
1838 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1839 if (is_object($courseorid)) {
1840 $courseorid = $courseorid->id;
1842 $coursechanged = false;
1843 foreach ($sections as $sectionnum) {
1844 if (!in_array($sectionnum, $existing)) {
1845 $cw = new stdClass();
1846 $cw->course = $courseorid;
1847 $cw->section = $sectionnum;
1849 $cw->summaryformat = FORMAT_HTML;
1851 $id = $DB->insert_record("course_sections", $cw);
1852 $coursechanged = true;
1855 if ($coursechanged) {
1856 rebuild_course_cache($courseorid, true);
1858 return $coursechanged;
1862 * Adds an existing module to the section
1864 * Updates both tables {course_sections} and {course_modules}
1866 * @param int|stdClass $courseorid course id or course object
1867 * @param int $cmid id of the module already existing in course_modules table
1868 * @param int $sectionnum relative number of the section (field course_sections.section)
1869 * If section does not exist it will be created
1870 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1871 * before which the module needs to be included. Null for inserting in the
1872 * end of the section
1873 * @return int The course_sections ID where the module is inserted
1875 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1876 global $DB, $COURSE;
1877 if (is_object($beforemod)) {
1878 $beforemod = $beforemod->id;
1880 if (is_object($courseorid)) {
1881 $courseid = $courseorid->id;
1883 $courseid = $courseorid;
1885 course_create_sections_if_missing($courseorid, $sectionnum);
1886 // Do not try to use modinfo here, there is no guarantee it is valid!
1887 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
1888 $modarray = explode(",", trim($section->sequence));
1889 if (empty($section->sequence)) {
1890 $newsequence = "$cmid";
1891 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1892 $insertarray = array($cmid, $beforemod);
1893 array_splice($modarray, $key[0], 1, $insertarray);
1894 $newsequence = implode(",", $modarray);
1896 $newsequence = "$section->sequence,$cmid";
1898 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1899 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1900 if (is_object($courseorid)) {
1901 rebuild_course_cache($courseorid->id, true);
1903 rebuild_course_cache($courseorid, true);
1905 return $section->id; // Return course_sections ID that was used.
1908 function set_coursemodule_groupmode($id, $groupmode) {
1910 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1911 if ($cm->groupmode != $groupmode) {
1912 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1913 rebuild_course_cache($cm->course, true);
1915 return ($cm->groupmode != $groupmode);
1918 function set_coursemodule_idnumber($id, $idnumber) {
1920 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1921 if ($cm->idnumber != $idnumber) {
1922 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1923 rebuild_course_cache($cm->course, true);
1925 return ($cm->idnumber != $idnumber);
1929 * Set the visibility of a module and inherent properties.
1931 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1932 * has been moved to {@link set_section_visible()} which was the only place from which
1933 * the parameter was used.
1935 * @param int $id of the module
1936 * @param int $visible state of the module
1937 * @return bool false when the module was not found, true otherwise
1939 function set_coursemodule_visible($id, $visible) {
1941 require_once($CFG->libdir.'/gradelib.php');
1943 // Trigger developer's attention when using the previously removed argument.
1944 if (func_num_args() > 2) {
1945 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1946 has been removed.', DEBUG_DEVELOPER);
1949 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1953 // Create events and propagate visibility to associated grade items if the value has changed.
1954 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1955 if ($cm->visible == $visible) {
1959 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1962 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1963 foreach($events as $event) {
1972 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1973 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1975 foreach ($grade_items as $grade_item) {
1976 $grade_item->set_hidden(!$visible);
1980 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1981 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1982 $cminfo = new stdClass();
1984 $cminfo->visible = $visible;
1985 $cminfo->visibleold = $visible;
1986 $DB->update_record('course_modules', $cminfo);
1988 rebuild_course_cache($cm->course, true);
1993 * This function will handles the whole deletion process of a module. This includes calling
1994 * the modules delete_instance function, deleting files, events, grades, conditional data,
1995 * the data in the course_module and course_sections table and adding a module deletion
1998 * @param int $cmid the course module id
2001 function course_delete_module($cmid) {
2002 global $CFG, $DB, $USER;
2004 require_once($CFG->libdir.'/gradelib.php');
2005 require_once($CFG->dirroot.'/blog/lib.php');
2007 // Get the course module.
2008 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
2012 // Get the module context.
2013 $modcontext = context_module::instance($cm->id);
2015 // Get the course module name.
2016 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
2018 // Get the file location of the delete_instance function for this module.
2019 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
2021 // Include the file required to call the delete_instance function for this module.
2022 if (file_exists($modlib)) {
2023 require_once($modlib);
2025 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
2026 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
2029 $deleteinstancefunction = $modulename . '_delete_instance';
2031 // Ensure the delete_instance function exists for this module.
2032 if (!function_exists($deleteinstancefunction)) {
2033 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
2034 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
2037 // Call the delete_instance function, if it returns false throw an exception.
2038 if (!$deleteinstancefunction($cm->instance)) {
2039 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
2040 "Cannot delete the module $modulename (instance).");
2043 // Remove all module files in case modules forget to do that.
2044 $fs = get_file_storage();
2045 $fs->delete_area_files($modcontext->id);
2047 // Delete events from calendar.
2048 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
2049 foreach($events as $event) {
2050 delete_event($event->id);
2054 // Delete grade items, outcome items and grades attached to modules.
2055 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
2056 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
2057 foreach ($grade_items as $grade_item) {
2058 $grade_item->delete('moddelete');
2062 // Delete completion and availability data; it is better to do this even if the
2063 // features are not turned on, in case they were turned on previously (these will be
2064 // very quick on an empty table).
2065 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2066 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2067 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2068 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2069 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2071 // Delete the context.
2072 delete_context(CONTEXT_MODULE, $cm->id);
2074 // Delete the module from the course_modules table.
2075 $DB->delete_records('course_modules', array('id' => $cm->id));
2077 // Delete module from that section.
2078 if (!delete_mod_from_section($cm->id, $cm->section)) {
2079 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
2080 "Cannot delete the module $modulename (instance) from section.");
2083 // Trigger a mod_deleted event with information about this module.
2084 $eventdata = new stdClass();
2085 $eventdata->modulename = $modulename;
2086 $eventdata->cmid = $cm->id;
2087 $eventdata->courseid = $cm->course;
2088 $eventdata->userid = $USER->id;
2089 events_trigger('mod_deleted', $eventdata);
2091 add_to_log($cm->course, 'course', "delete mod",
2092 "view.php?id=$cm->course",
2093 "$modulename $cm->instance", $cm->id);
2095 rebuild_course_cache($cm->course, true);
2098 function delete_mod_from_section($modid, $sectionid) {
2101 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2103 $modarray = explode(",", $section->sequence);
2105 if ($key = array_keys ($modarray, $modid)) {
2106 array_splice($modarray, $key[0], 1);
2107 $newsequence = implode(",", $modarray);
2108 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2109 rebuild_course_cache($section->course, true);
2120 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2122 * @param object $course course object
2123 * @param int $section Section number (not id!!!)
2124 * @param int $move (-1 or 1)
2125 * @return boolean true if section moved successfully
2126 * @todo MDL-33379 remove this function in 2.5
2128 function move_section($course, $section, $move) {
2129 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2131 /// Moves a whole course section up and down within the course
2138 $sectiondest = $section + $move;
2140 // compartibility with course formats using field 'numsections'
2141 $courseformatoptions = course_get_format($course)->get_format_options();
2142 if (array_key_exists('numsections', $courseformatoptions) &&
2143 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2147 $retval = move_section_to($course, $section, $sectiondest);
2152 * Moves a section within a course, from a position to another.
2153 * Be very careful: $section and $destination refer to section number,
2156 * @param object $course
2157 * @param int $section Section number (not id!!!)
2158 * @param int $destination
2159 * @return boolean Result
2161 function move_section_to($course, $section, $destination) {
2162 /// Moves a whole course section up and down within the course
2165 if (!$destination && $destination != 0) {
2169 // compartibility with course formats using field 'numsections'
2170 $courseformatoptions = course_get_format($course)->get_format_options();
2171 if ((array_key_exists('numsections', $courseformatoptions) &&
2172 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
2176 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2177 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2178 'section ASC, id ASC', 'id, section')) {
2182 $movedsections = reorder_sections($sections, $section, $destination);
2184 // Update all sections. Do this in 2 steps to avoid breaking database
2185 // uniqueness constraint
2186 $transaction = $DB->start_delegated_transaction();
2187 foreach ($movedsections as $id => $position) {
2188 if ($sections[$id] !== $position) {
2189 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2192 foreach ($movedsections as $id => $position) {
2193 if ($sections[$id] !== $position) {
2194 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2198 // If we move the highlighted section itself, then just highlight the destination.
2199 // Adjust the higlighted section location if we move something over it either direction.
2200 if ($section == $course->marker) {
2201 course_set_marker($course->id, $destination);
2202 } elseif ($section > $course->marker && $course->marker >= $destination) {
2203 course_set_marker($course->id, $course->marker+1);
2204 } elseif ($section < $course->marker && $course->marker <= $destination) {
2205 course_set_marker($course->id, $course->marker-1);
2208 $transaction->allow_commit();
2209 rebuild_course_cache($course->id, true);
2214 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2215 * an original position number and a target position number, rebuilds the array so that the
2216 * move is made without any duplication of section positions.
2217 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2218 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2220 * @param array $sections
2221 * @param int $origin_position
2222 * @param int $target_position
2225 function reorder_sections($sections, $origin_position, $target_position) {
2226 if (!is_array($sections)) {
2230 // We can't move section position 0
2231 if ($origin_position < 1) {
2232 echo "We can't move section position 0";
2236 // Locate origin section in sections array
2237 if (!$origin_key = array_search($origin_position, $sections)) {
2238 echo "searched position not in sections array";
2239 return false; // searched position not in sections array
2242 // Extract origin section
2243 $origin_section = $sections[$origin_key];
2244 unset($sections[$origin_key]);
2246 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2248 $append_array = array();
2249 foreach ($sections as $id => $position) {
2251 $append_array[$id] = $position;
2252 unset($sections[$id]);
2254 if ($position == $target_position) {
2255 if ($target_position < $origin_position) {
2256 $append_array[$id] = $position;
2257 unset($sections[$id]);
2263 // Append moved section
2264 $sections[$origin_key] = $origin_section;
2266 // Append rest of array (if applicable)
2267 if (!empty($append_array)) {
2268 foreach ($append_array as $id => $position) {
2269 $sections[$id] = $position;
2273 // Renumber positions
2275 foreach ($sections as $id => $p) {
2276 $sections[$id] = $position;
2285 * Move the module object $mod to the specified $section
2286 * If $beforemod exists then that is the module
2287 * before which $modid should be inserted
2288 * All parameters are objects
2290 function moveto_module($mod, $section, $beforemod=NULL) {
2291 global $OUTPUT, $DB;
2293 /// Remove original module from original section
2294 if (! delete_mod_from_section($mod->id, $mod->section)) {
2295 echo $OUTPUT->notification("Could not delete module from existing section");
2298 // if moving to a hidden section then hide module
2299 if (!$section->visible && $mod->visible) {
2300 // Set this in the object because it is sent as a response to ajax calls.
2302 set_coursemodule_visible($mod->id, 0);
2303 // Set visibleold to 1 so module will be visible when section is made visible.
2304 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
2306 if ($section->visible && !$mod->visible) {
2307 set_coursemodule_visible($mod->id, $mod->visibleold);
2308 // Set this in the object because it is sent as a response to ajax calls.
2309 $mod->visible = $mod->visibleold;
2312 /// Add the module into the new section
2313 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
2318 * Returns the list of all editing actions that current user can perform on the module
2320 * @param cm_info $mod The module to produce editing buttons for
2321 * @param int $indent The current indenting (default -1 means no move left-right actions)
2322 * @param int $sr The section to link back to (used for creating the links)
2323 * @return array array of action_link or pix_icon objects
2325 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
2326 global $COURSE, $SITE;
2330 $coursecontext = context_course::instance($mod->course);
2331 $modcontext = context_module::instance($mod->id);
2333 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
2334 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
2336 // no permission to edit anything
2337 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
2341 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2344 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
2345 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
2346 $str->assign = get_string('assignroles', 'role');
2347 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
2348 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
2349 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
2350 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
2351 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
2352 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
2355 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2358 $baseurl->param('sr', $sr);
2363 if ($mod->has_view() && $hasmanageactivities &&
2364 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
2365 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
2366 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2367 $actions['title'] = new action_link(
2368 new moodle_url($baseurl, array('update' => $mod->id)),
2369 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2371 array('class' => 'editing_title', 'title' => $str->edittitle)
2376 if ($hasmanageactivities) {
2377 if (right_to_left()) { // Exchange arrows on RTL
2378 $rightarrow = 't/left';
2379 $leftarrow = 't/right';
2381 $rightarrow = 't/right';
2382 $leftarrow = 't/left';
2386 $actions['moveleft'] = new action_link(
2387 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
2388 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2390 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
2394 $actions['moveright'] = new action_link(
2395 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
2396 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2398 array('class' => 'editing_moveright', 'title' => $str->moveright)
2404 if ($hasmanageactivities) {
2405 $actions['move'] = new action_link(
2406 new moodle_url($baseurl, array('copy' => $mod->id)),
2407 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2409 array('class' => 'editing_move', 'title' => $str->move)
2414 if ($hasmanageactivities) {
2415 $actions['update'] = new action_link(
2416 new moodle_url($baseurl, array('update' => $mod->id)),
2417 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2419 array('class' => 'editing_update', 'title' => $str->update)
2423 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2424 // note that restoring on front page is never allowed
2425 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
2426 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
2427 $actions['duplicate'] = new action_link(
2428 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2429 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2431 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
2436 if ($hasmanageactivities) {
2437 $actions['delete'] = new action_link(
2438 new moodle_url($baseurl, array('delete' => $mod->id)),
2439 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2441 array('class' => 'editing_delete', 'title' => $str->delete)
2446 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2447 if ($mod->visible) {
2448 $actions['hide'] = new action_link(
2449 new moodle_url($baseurl, array('hide' => $mod->id)),
2450 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2452 array('class' => 'editing_hide', 'title' => $str->hide)
2455 $actions['show'] = new action_link(
2456 new moodle_url($baseurl, array('show' => $mod->id)),
2457 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2459 array('class' => 'editing_show', 'title' => $str->show)
2465 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2466 if ($mod->coursegroupmodeforce) {
2467 $modgroupmode = $mod->coursegroupmode;
2469 $modgroupmode = $mod->groupmode;
2471 if ($modgroupmode == SEPARATEGROUPS) {
2472 $groupmode = NOGROUPS;
2473 $grouptitle = $str->groupsseparate;
2474 $forcedgrouptitle = $str->forcedgroupsseparate;
2475 $actionname = 'groupsseparate';
2476 $groupimage = 't/groups';
2477 } else if ($modgroupmode == VISIBLEGROUPS) {
2478 $groupmode = SEPARATEGROUPS;
2479 $grouptitle = $str->groupsvisible;
2480 $forcedgrouptitle = $str->forcedgroupsvisible;
2481 $actionname = 'groupsvisible';
2482 $groupimage = 't/groupv';
2484 $groupmode = VISIBLEGROUPS;
2485 $grouptitle = $str->groupsnone;
2486 $forcedgrouptitle = $str->forcedgroupsnone;
2487 $actionname = 'groupsnone';
2488 $groupimage = 't/groupn';
2490 if (!$mod->coursegroupmodeforce) {
2491 $actions[$actionname] = new action_link(
2492 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
2493 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2495 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
2498 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
2503 if (has_capability('moodle/role:assign', $modcontext)){
2504 $actions['assign'] = new action_link(
2505 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2506 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2508 array('class' => 'editing_assign', 'title' => $str->assign)
2516 * given a course object with shortname & fullname, this function will
2517 * truncate the the number of chars allowed and add ... if it was too long
2519 function course_format_name ($course,$max=100) {
2521 $context = context_course::instance($course->id);
2522 $shortname = format_string($course->shortname, true, array('context' => $context));
2523 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2524 $str = $shortname.': '. $fullname;
2525 if (textlib::strlen($str) <= $max) {
2529 return textlib::substr($str,0,$max-3).'...';
2534 * Is the user allowed to add this type of module to this course?
2535 * @param object $course the course settings. Only $course->id is used.
2536 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2537 * @return bool whether the current user is allowed to add this type of module to this course.
2539 function course_allowed_module($course, $modname) {
2540 if (is_numeric($modname)) {
2541 throw new coding_exception('Function course_allowed_module no longer
2542 supports numeric module ids. Please update your code to pass the module name.');
2545 $capability = 'mod/' . $modname . ':addinstance';
2546 if (!get_capability_info($capability)) {
2547 // Debug warning that the capability does not exist, but no more than once per page.
2548 static $warned = array();
2549 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2550 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2551 debugging('The module ' . $modname . ' does not define the standard capability ' .
2552 $capability , DEBUG_DEVELOPER);
2553 $warned[$modname] = 1;
2556 // If the capability does not exist, the module can always be added.
2560 $coursecontext = context_course::instance($course->id);
2561 return has_capability($capability, $coursecontext);
2565 * Efficiently moves many courses around while maintaining
2566 * sortorder in order.
2568 * @param array $courseids is an array of course ids
2569 * @param int $categoryid
2570 * @return bool success
2572 function move_courses($courseids, $categoryid) {
2573 global $CFG, $DB, $OUTPUT;
2575 if (empty($courseids)) {
2580 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2584 $courseids = array_reverse($courseids);
2585 $newparent = context_coursecat::instance($category->id);
2588 foreach ($courseids as $courseid) {
2589 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2590 $course = new stdClass();
2591 $course->id = $courseid;
2592 $course->category = $category->id;
2593 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2594 if ($category->visible == 0) {
2595 // hide the course when moving into hidden category,
2596 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2597 $course->visible = 0;
2600 $DB->update_record('course', $course);
2601 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
2603 $context = context_course::instance($course->id);
2604 context_moved($context, $newparent);
2607 fix_course_sortorder();
2608 cache_helper::purge_by_event('changesincourse');
2614 * Returns the display name of the given section that the course prefers
2616 * Implementation of this function is provided by course format
2617 * @see format_base::get_section_name()
2619 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2620 * @param int|stdClass $section Section object from database or just field course_sections.section
2621 * @return string Display name that the course format prefers, e.g. "Week 2"
2623 function get_section_name($courseorid, $section) {
2624 return course_get_format($courseorid)->get_section_name($section);
2628 * Tells if current course format uses sections
2630 * @param string $format Course format ID e.g. 'weeks' $course->format
2633 function course_format_uses_sections($format) {
2634 $course = new stdClass();
2635 $course->format = $format;
2636 return course_get_format($course)->uses_sections();
2640 * Returns the information about the ajax support in the given source format
2642 * The returned object's property (boolean)capable indicates that
2643 * the course format supports Moodle course ajax features.
2644 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2646 * @param string $format
2649 function course_format_ajax_support($format) {
2650 $course = new stdClass();
2651 $course->format = $format;
2652 return course_get_format($course)->supports_ajax();
2656 * Can the current user delete this course?
2657 * Course creators have exception,
2658 * 1 day after the creation they can sill delete the course.
2659 * @param int $courseid
2662 function can_delete_course($courseid) {
2665 $context = context_course::instance($courseid);
2667 if (has_capability('moodle/course:delete', $context)) {
2671 // hack: now try to find out if creator created this course recently (1 day)
2672 if (!has_capability('moodle/course:create', $context)) {
2676 $since = time() - 60*60*24;
2678 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2679 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2681 return $DB->record_exists_select('log', $select, $params);
2685 * Save the Your name for 'Some role' strings.
2687 * @param integer $courseid the id of this course.
2688 * @param array $data the data that came from the course settings form.
2690 function save_local_role_names($courseid, $data) {
2692 $context = context_course::instance($courseid);
2694 foreach ($data as $fieldname => $value) {
2695 if (strpos($fieldname, 'role_') !== 0) {
2698 list($ignored, $roleid) = explode('_', $fieldname);
2700 // make up our mind whether we want to delete, update or insert
2702 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2704 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2705 $rolename->name = $value;
2706 $DB->update_record('role_names', $rolename);
2709 $rolename = new stdClass;
2710 $rolename->contextid = $context->id;
2711 $rolename->roleid = $roleid;
2712 $rolename->name = $value;
2713 $DB->insert_record('role_names', $rolename);
2719 * Create a course and either return a $course object
2721 * Please note this functions does not verify any access control,
2722 * the calling code is responsible for all validation (usually it is the form definition).
2724 * @param array $editoroptions course description editor options
2725 * @param object $data - all the data needed for an entry in the 'course' table
2726 * @return object new course instance
2728 function create_course($data, $editoroptions = NULL) {
2731 //check the categoryid - must be given for all new courses
2732 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2734 //check if the shortname already exist
2735 if (!empty($data->shortname)) {
2736 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2737 throw new moodle_exception('shortnametaken');
2741 //check if the id number already exist
2742 if (!empty($data->idnumber)) {
2743 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2744 throw new moodle_exception('idnumbertaken');
2748 $data->timecreated = time();
2749 $data->timemodified = $data->timecreated;
2751 // place at beginning of any category
2752 $data->sortorder = 0;
2754 if ($editoroptions) {
2755 // summary text is updated later, we need context to store the files first
2756 $data->summary = '';
2757 $data->summary_format = FORMAT_HTML;
2760 if (!isset($data->visible)) {
2761 // data not from form, add missing visibility info
2762 $data->visible = $category->visible;
2764 $data->visibleold = $data->visible;
2766 $newcourseid = $DB->insert_record('course', $data);
2767 $context = context_course::instance($newcourseid, MUST_EXIST);
2769 if ($editoroptions) {
2770 // Save the files used in the summary editor and store
2771 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2772 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2773 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2776 // update course format options
2777 course_get_format($newcourseid)->update_course_format_options($data);
2779 $course = course_get_format($newcourseid)->get_course();
2782 blocks_add_default_course_blocks($course);
2784 // Create a default section.
2785 course_create_sections_if_missing($course, 0);
2787 fix_course_sortorder();
2788 // purge appropriate caches in case fix_course_sortorder() did not change anything
2789 cache_helper::purge_by_event('changesincourse');
2791 // new context created - better mark it as dirty
2792 mark_context_dirty($context->path);
2794 // Save any custom role names.
2795 save_local_role_names($course->id, (array)$data);
2797 // set up enrolments
2798 enrol_course_updated(true, $course, $data);
2800 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2803 events_trigger('course_created', $course);
2811 * Please note this functions does not verify any access control,
2812 * the calling code is responsible for all validation (usually it is the form definition).
2814 * @param object $data - all the data needed for an entry in the 'course' table
2815 * @param array $editoroptions course description editor options
2818 function update_course($data, $editoroptions = NULL) {
2821 $data->timemodified = time();
2823 $oldcourse = course_get_format($data->id)->get_course();
2824 $context = context_course::instance($oldcourse->id);
2826 if ($editoroptions) {
2827 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2830 if (!isset($data->category) or empty($data->category)) {
2831 // prevent nulls and 0 in category field
2832 unset($data->category);
2834 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2836 if (!isset($data->visible)) {
2837 // data not from form, add missing visibility info
2838 $data->visible = $oldcourse->visible;
2841 if ($data->visible != $oldcourse->visible) {
2842 // reset the visibleold flag when manually hiding/unhiding course
2843 $data->visibleold = $data->visible;
2846 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2847 if (empty($newcategory->visible)) {
2848 // make sure when moving into hidden category the course is hidden automatically
2854 // Update with the new data
2855 $DB->update_record('course', $data);
2856 // make sure the modinfo cache is reset
2857 rebuild_course_cache($data->id);
2859 // update course format options with full course data
2860 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2862 $course = $DB->get_record('course', array('id'=>$data->id));
2865 $newparent = context_coursecat::instance($course->category);
2866 context_moved($context, $newparent);
2869 fix_course_sortorder();
2870 // purge appropriate caches in case fix_course_sortorder() did not change anything
2871 cache_helper::purge_by_event('changesincourse');
2873 // Test for and remove blocks which aren't appropriate anymore
2874 blocks_remove_inappropriate($course);
2876 // Save any custom role names.
2877 save_local_role_names($course->id, $data);
2879 // update enrol settings
2880 enrol_course_updated(false, $course, $data);
2882 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2885 events_trigger('course_updated', $course);
2887 if ($oldcourse->format !== $course->format) {
2888 // Remove all options stored for the previous format
2889 // We assume that new course format migrated everything it needed watching trigger
2890 // 'course_updated' and in method format_XXX::update_course_format_options()
2891 $DB->delete_records('course_format_options',
2892 array('courseid' => $course->id, 'format' => $oldcourse->format));
2897 * Average number of participants
2900 function average_number_of_participants() {
2903 //count total of enrolments for visible course (except front page)
2904 $sql = 'SELECT COUNT(*) FROM (
2905 SELECT DISTINCT ue.userid, e.courseid
2906 FROM {user_enrolments} ue, {enrol} e, {course} c
2907 WHERE ue.enrolid = e.id
2908 AND e.courseid <> :siteid
2909 AND c.id = e.courseid
2910 AND c.visible = 1) total';
2911 $params = array('siteid' => $SITE->id);
2912 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2915 //count total of visible courses (minus front page)
2916 $coursetotal = $DB->count_records('course', array('visible' => 1));
2917 $coursetotal = $coursetotal - 1 ;
2919 //average of enrolment
2920 if (empty($coursetotal)) {
2921 $participantaverage = 0;
2923 $participantaverage = $enrolmenttotal / $coursetotal;
2926 return $participantaverage;
2930 * Average number of course modules
2933 function average_number_of_courses_modules() {
2936 //count total of visible course module (except front page)
2937 $sql = 'SELECT COUNT(*) FROM (
2938 SELECT cm.course, cm.module
2939 FROM {course} c, {course_modules} cm
2940 WHERE c.id = cm.course
2943 AND c.visible = 1) total';
2944 $params = array('siteid' => $SITE->id);
2945 $moduletotal = $DB->count_records_sql($sql, $params);
2948 //count total of visible courses (minus front page)
2949 $coursetotal = $DB->count_records('course', array('visible' => 1));
2950 $coursetotal = $coursetotal - 1 ;
2952 //average of course module
2953 if (empty($coursetotal)) {
2954 $coursemoduleaverage = 0;
2956 $coursemoduleaverage = $moduletotal / $coursetotal;
2959 return $coursemoduleaverage;
2963 * This class pertains to course requests and contains methods associated with
2964 * create, approving, and removing course requests.
2966 * Please note we do not allow embedded images here because there is no context
2967 * to store them with proper access control.
2969 * @copyright 2009 Sam Hemelryk
2970 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2973 * @property-read int $id
2974 * @property-read string $fullname
2975 * @property-read string $shortname
2976 * @property-read string $summary
2977 * @property-read int $summaryformat
2978 * @property-read int $summarytrust
2979 * @property-read string $reason
2980 * @property-read int $requester
2982 class course_request {
2985 * This is the stdClass that stores the properties for the course request
2986 * and is externally accessed through the __get magic method
2989 protected $properties;
2992 * An array of options for the summary editor used by course request forms.
2993 * This is initially set by {@link summary_editor_options()}
2997 protected static $summaryeditoroptions;
3000 * Static function to prepare the summary editor for working with a course
3004 * @param null|stdClass $data Optional, an object containing the default values
3005 * for the form, these may be modified when preparing the
3006 * editor so this should be called before creating the form
3007 * @return stdClass An object that can be used to set the default values for
3010 public static function prepare($data=null) {
3011 if ($data === null) {
3012 $data = new stdClass;
3014 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
3019 * Static function to create a new course request when passed an array of properties
3022 * This function also handles saving any files that may have been used in the editor
3025 * @param stdClass $data
3026 * @return course_request The newly created course request
3028 public static function create($data) {
3029 global $USER, $DB, $CFG;
3030 $data->requester = $USER->id;
3032 // Setting the default category if none set.
3033 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
3034 $data->category = $CFG->defaultrequestcategory;
3037 // Summary is a required field so copy the text over
3038 $data->summary = $data->summary_editor['text'];
3039 $data->summaryformat = $data->summary_editor['format'];
3041 $data->id = $DB->insert_record('course_request', $data);
3043 // Create a new course_request object and return it
3044 $request = new course_request($data);
3046 // Notify the admin if required.
3047 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
3050 $a->link = "$CFG->wwwroot/course/pending.php";
3051 $a->user = fullname($USER);
3052 $subject = get_string('courserequest');
3053 $message = get_string('courserequestnotifyemail', 'admin', $a);
3054 foreach ($users as $user) {
3055 $request->notify($user, $USER, 'courserequested', $subject, $message);
3063 * Returns an array of options to use with a summary editor
3065 * @uses course_request::$summaryeditoroptions
3066 * @return array An array of options to use with the editor
3068 public static function summary_editor_options() {
3070 if (self::$summaryeditoroptions === null) {
3071 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
3073 return self::$summaryeditoroptions;
3077 * Loads the properties for this course request object. Id is required and if
3078 * only id is provided then we load the rest of the properties from the database
3080 * @param stdClass|int $properties Either an object containing properties
3081 * or the course_request id to load
3083 public function __construct($properties) {
3085 if (empty($properties->id)) {
3086 if (empty($properties)) {
3087 throw new coding_exception('You must provide a course request id when creating a course_request object');
3090 $properties = new stdClass;
3091 $properties->id = (int)$id;
3094 if (empty($properties->requester)) {
3095 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
3096 print_error('unknowncourserequest');
3099 $this->properties = $properties;
3101 $this->properties->collision = null;
3105 * Returns the requested property
3107 * @param string $key
3110 public function __get($key) {
3111 return $this->properties->$key;
3115 * Override this to ensure empty($request->blah) calls return a reliable answer...
3117 * This is required because we define the __get method
3120 * @return bool True is it not empty, false otherwise
3122 public function __isset($key) {
3123 return (!empty($this->properties->$key));
3127 * Returns the user who requested this course
3129 * Uses a static var to cache the results and cut down the number of db queries
3131 * @staticvar array $requesters An array of cached users
3132 * @return stdClass The user who requested the course
3134 public function get_requester() {
3136 static $requesters= array();
3137 if (!array_key_exists($this->properties->requester, $requesters)) {
3138 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
3140 return $requesters[$this->properties->requester];
3144 * Checks that the shortname used by the course does not conflict with any other
3145 * courses that exist
3147 * @param string|null $shortnamemark The string to append to the requests shortname
3148 * should a conflict be found
3149 * @return bool true is there is a conflict, false otherwise
3151 public function check_shortname_collision($shortnamemark = '[*]') {
3154 if ($this->properties->collision !== null) {
3155 return $this->properties->collision;
3158 if (empty($this->properties->shortname)) {
3159 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
3160 $this->properties->collision = false;
3161 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
3162 if (!empty($shortnamemark)) {
3163 $this->properties->shortname .= ' '.$shortnamemark;
3165 $this->properties->collision = true;
3167 $this->properties->collision = false;
3169 return $this->properties->collision;
3173 * Returns the category where this course request should be created
3175 * Note that we don't check here that user has a capability to view
3176 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
3177 * 'moodle/course:changecategory'
3181 public function get_category() {
3183 require_once($CFG->libdir.'/coursecatlib.php');
3184 // If the category is not set, if the current user does not have the rights to change the category, or if the
3185 // category does not exist, we set the default category to the course to be approved.
3186 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
3187 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
3188 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
3189 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
3192 $category = coursecat::get_default();
3198 * This function approves the request turning it into a course
3200 * This function converts the course request into a course, at the same time
3201 * transferring any files used in the summary to the new course and then removing
3202 * the course request and the files associated with it.
3204 * @return int The id of the course that was created from this request
3206 public function approve() {
3207 global $CFG, $DB, $USER;
3209 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
3211 $courseconfig = get_config('moodlecourse');
3213 // Transfer appropriate settings
3214 $data = clone($this->properties);
3216 unset($data->reason);
3217 unset($data->requester);
3220 $category = $this->get_category();
3221 $data->category = $category->id;
3222 // Set misc settings
3223 $data->requested = 1;
3225 // Apply course default settings
3226 $data->format = $courseconfig->format;
3227 $data->newsitems = $courseconfig->newsitems;
3228 $data->showgrades = $courseconfig->showgrades;
3229 $data->showreports = $courseconfig->showreports;
3230 $data->maxbytes = $courseconfig->maxbytes;
3231 $data->groupmode = $courseconfig->groupmode;
3232 $data->groupmodeforce = $courseconfig->groupmodeforce;
3233 $data->visible = $courseconfig->visible;
3234 $data->visibleold = $data->visible;
3235 $data->lang = $courseconfig->lang;
3237 $course = create_course($data);
3238 $context = context_course::instance($course->id, MUST_EXIST);
3240 // add enrol instances
3241 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3242 if ($manual = enrol_get_plugin('manual')) {
3243 $manual->add_default_instance($course);
3247 // enrol the requester as teacher if necessary
3248 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3249 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3254 $a = new stdClass();
3255 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3256 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3257 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3263 * Reject a course request
3265 * This function rejects a course request, emailing the requesting user the
3266 * provided notice and then removing the request from the database
3268 * @param string $notice The message to display to the user
3270 public function reject($notice) {
3272 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3273 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3278 * Deletes the course request and any associated files
3280 public function delete() {
3282 $DB->delete_records('course_request', array('id' => $this->properties->id));
3286 * Send a message from one user to another using events_trigger
3288 * @param object $touser
3289 * @param object $fromuser
3290 * @param string $name
3291 * @param string $subject
3292 * @param string $message
3294 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3295 $eventdata = new stdClass();
3296 $eventdata->component = 'moodle';
3297 $eventdata->name = $name;
3298 $eventdata->userfrom = $fromuser;
3299 $eventdata->userto = $touser;
3300 $eventdata->subject = $subject;
3301 $eventdata->fullmessage = $message;
3302 $eventdata->fullmessageformat = FORMAT_PLAIN;
3303 $eventdata->fullmessagehtml = '';
3304 $eventdata->smallmessage = '';
3305 $eventdata->notification = 1;
3306 message_send($eventdata);
3311 * Return a list of page types
3312 * @param string $pagetype current page type
3313 * @param stdClass $parentcontext Block's parent context
3314 * @param stdClass $currentcontext Current context of block
3316 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3317 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
3318 if (isset($currentcontext)) {
3319 // if above course context ,display all course fomats
3320 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
3321 if ($course->id == SITEID) {
3322 return array('*'=>get_string('page-x', 'pagetype'));
3325 return array('*'=>get_string('page-x', 'pagetype'),
3326 'course-*'=>get_string('page-course-x', 'pagetype'),
3327 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
3332 * Determine whether course ajax should be enabled for the specified course
3334 * @param stdClass $course The course to test against
3335 * @return boolean Whether course ajax is enabled or note
3337 function course_ajax_enabled($course) {
3338 global $CFG, $PAGE, $SITE;
3340 // Ajax must be enabled globally
3341 if (!$CFG->enableajax) {
3345 // The user must be editing for AJAX to be included
3346 if (!$PAGE->user_is_editing()) {
3350 // Check that the theme suports
3351 if (!$PAGE->theme->enablecourseajax) {
3355 // Check that the course format supports ajax functionality
3356 // The site 'format' doesn't have information on course format support
3357 if ($SITE->id !== $course->id) {
3358 $courseformatajaxsupport = course_format_ajax_support($course->format);
3359 if (!$courseformatajaxsupport->capable) {
3364 // All conditions have been met so course ajax should be enabled
3369 * Include the relevant javascript and language strings for the resource
3370 * toolbox YUI module
3372 * @param integer $id The ID of the course being applied to
3373 * @param array $usedmodules An array containing the names of the modules in use on the page
3374 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3375 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3376 * * resourceurl The URL to post changes to for resource changes
3377 * * sectionurl The URL to post changes to for section changes
3378 * * pageparams Additional parameters to pass through in the post
3381 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3382 global $PAGE, $SITE;
3384 // Ensure that ajax should be included
3385 if (!course_ajax_enabled($course)) {
3390 $config = new stdClass();
3393 // The URL to use for resource changes
3394 if (!isset($config->resourceurl)) {
3395 $config->resourceurl = '/course/rest.php';
3398 // The URL to use for section changes
3399 if (!isset($config->sectionurl)) {
3400 $config->sectionurl = '/course/rest.php';
3403 // Any additional parameters which need to be included on page submission
3404 if (!isset($config->pageparams)) {
3405 $config->pageparams = array();
3408 // Include toolboxes
3409 $PAGE->requires->yui_module('moodle-course-toolboxes',
3410 'M.course.init_resource_toolbox',
3412 'courseid' => $course->id,
3413 'ajaxurl' => $config->resourceurl,
3414 'config' => $config,
3417 $PAGE->requires->yui_module('moodle-course-toolboxes',
3418 'M.course.init_section_toolbox',
3420 'courseid' => $course->id,
3421 'format' => $course->format,
3422 'ajaxurl' => $config->sectionurl,
3423 'config' => $config,
3427 // Include course dragdrop
3428 if ($course->id != $SITE->id) {
3429 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3431 'courseid' => $course->id,
3432 'ajaxurl' => $config->sectionurl,
3433 'config' => $config,
3436 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3438 'courseid' => $course->id,
3439 'ajaxurl' => $config->resourceurl,
3440 'config' => $config,
3444 // Require various strings for the command toolbox
3445 $PAGE->requires->strings_for_js(array(
3448 'deletechecktypename',
3450 'edittitleinstructions',
3456 'clicktochangeinbrackets',
3463 // Include format-specific strings
3464 if ($course->id != $SITE->id) {
3465 $PAGE->requires->strings_for_js(array(
3468 ), 'format_' . $course->format);
3471 // For confirming resource deletion we need the name of the module in question
3472 foreach ($usedmodules as $module => $modname) {
3473 $PAGE->requires->string_for_js('pluginname', $module);
3476 // Load drag and drop upload AJAX.
3477 dndupload_add_to_course($course, $enabledmodules);
3483 * Returns the sorted list of available course formats, filtered by enabled if necessary
3485 * @param bool $enabledonly return only formats that are enabled
3486 * @return array array of sorted format names
3488 function get_sorted_course_formats($enabledonly = false) {
3490 $formats = get_plugin_list('format');
3492 if (!empty($CFG->format_plugins_sortorder)) {
3493 $order = explode(',', $CFG->format_plugins_sortorder);
3494 $order = array_merge(array_intersect($order, array_keys($formats)),
3495 array_diff(array_keys($formats), $order));
3497 $order = array_keys($formats);
3499 if (!$enabledonly) {
3502 $sortedformats = array();
3503 foreach ($order as $formatname) {
3504 if (!get_config('format_'.$formatname, 'disabled')) {
3505 $sortedformats[] = $formatname;
3508 return $sortedformats;
3512 * The URL to use for the specified course (with section)
3514 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3515 * @param int|stdClass $section Section object from database or just field course_sections.section
3516 * if omitted the course view page is returned
3517 * @param array $options options for view URL. At the moment core uses:
3518 * 'navigation' (bool) if true and section has no separate page, the function returns null
3519 * 'sr' (int) used by multipage formats to specify to which section to return
3520 * @return moodle_url The url of course
3522 function course_get_url($courseorid, $section = null, $options = array()) {
3523 return course_get_format($courseorid)->get_view_url($section, $options);
3530 * - capability checks and other checks
3531 * - create the module from the module info
3533 * @param object $module
3534 * @return object the created module info
3536 function create_module($moduleinfo) {
3539 require_once($CFG->dirroot . '/course/modlib.php');
3541 // Check manadatory attributs.
3542 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3543 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3544 $mandatoryfields[] = 'introeditor';
3546 foreach($mandatoryfields as $mandatoryfield) {
3547 if (!isset($moduleinfo->{$mandatoryfield})) {
3548 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3552 // Some additional checks (capability / existing instances).
3553 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3554 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3556 // Load module library.
3557 include_modulelib($module->name);
3560 $moduleinfo->module = $module->id;
3561 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3570 * - capability and other checks
3571 * - update the module
3573 * @param object $module
3574 * @return object the updated module info
3576 function update_module($moduleinfo) {
3579 require_once($CFG->dirroot . '/course/modlib.php');
3581 // Check the course module exists.
3582 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3584 // Check the course exists.
3585 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3587 // Some checks (capaibility / existing instances).
3588 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3590 // Load module library.
3591 include_modulelib($module->name);
3593 // Retrieve few information needed by update_moduleinfo.
3594 $moduleinfo->modulename = $cm->modname;
3595 if (!isset($moduleinfo->scale)) {
3596 $moduleinfo->scale = 0;
3598 $moduleinfo->type = 'mod';
3600 // Update the module.
3601 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3607 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3608 * Sorts by descending order of time.
3610 * @param stdClass $a First object
3611 * @param stdClass $b Second object
3612 * @return int 0,1,-1 representing the order
3614 function compare_activities_by_time_desc($a, $b) {
3615 // Make sure the activities actually have a timestamp property.
3616 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3619 // We treat instances without timestamp as if they have a timestamp of 0.
3620 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3623 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3626 if ($a->timestamp == $b->timestamp) {
3629 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3633 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3634 * Sorts by ascending order of time.
3636 * @param stdClass $a First object
3637 * @param stdClass $b Second object
3638 * @return int 0,1,-1 representing the order
3640 function compare_activities_by_time_asc($a, $b) {
3641 // Make sure the activities actually have a timestamp property.
3642 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3645 // We treat instances without timestamp as if they have a timestamp of 0.
3646 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3649 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3652 if ($a->timestamp == $b->timestamp) {
3655 return ($a->timestamp < $b->timestamp) ? -1 : 1;