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/format/lib.php');
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
37 * Number of courses to display when summaries are included.
39 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
41 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
43 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
44 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
45 define('FRONTPAGENEWS', '0');
46 define('FRONTPAGECOURSELIST', '1'); // Not used. TODO MDL-38832 remove
47 define('FRONTPAGECATEGORYNAMES', '2');
48 define('FRONTPAGETOPICONLY', '3'); // Not used. TODO MDL-38832 remove
49 define('FRONTPAGECATEGORYCOMBO', '4');
50 define('FRONTPAGEENROLLEDCOURSELIST', '5');
51 define('FRONTPAGEALLCOURSELIST', '6');
52 define('FRONTPAGECOURSESEARCH', '7');
53 define('FRONTPAGECOURSELIMIT', 200); // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage. TODO MDL-38832 remove
54 define('EXCELROWS', 65535);
55 define('FIRSTUSEDEXCELROW', 3);
57 define('MOD_CLASS_ACTIVITY', 0);
58 define('MOD_CLASS_RESOURCE', 1);
60 function make_log_url($module, $url) {
63 if (strpos($url, 'report/') === 0) {
64 // there is only one report type, course reports are deprecated
75 if (strpos($url, '../') === 0) {
76 $url = ltrim($url, '.');
78 $url = "/course/$url";
83 $url = "/$module/$url";
96 $url = "/message/$url";
108 $url = "/grade/$url";
111 $url = "/mod/$module/$url";
115 //now let's sanitise urls - there might be some ugly nasties:-(
116 $parts = explode('?', $url);
117 $script = array_shift($parts);
118 if (strpos($script, 'http') === 0) {
119 $script = clean_param($script, PARAM_URL);
121 $script = clean_param($script, PARAM_PATH);
126 $query = implode('', $parts);
127 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
128 $parts = explode('&', $query);
129 $eq = urlencode('=');
130 foreach ($parts as $key=>$part) {
131 $part = urlencode(urldecode($part));
132 $part = str_replace($eq, '=', $part);
133 $parts[$key] = $part;
135 $query = '?'.implode('&', $parts);
138 return $script.$query;
142 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
143 $modname="", $modid=0, $modaction="", $groupid=0) {
146 // It is assumed that $date is the GMT time of midnight for that day,
147 // and so the next 86400 seconds worth of logs are printed.
149 /// Setup for group handling.
151 // TODO: I don't understand group/context/etc. enough to be able to do
152 // something interesting with it here
153 // What is the context of a remote course?
155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
157 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
158 // $groupid = get_current_group($course->id);
160 /// If this course doesn't have groups, no groupid can be specified.
161 //else if (!$course->groupmode) {
170 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
172 LEFT JOIN {user} u ON l.userid = u.id
176 $where .= "l.hostid = :hostid";
177 $params['hostid'] = $hostid;
179 // TODO: Is 1 really a magic number referring to the sitename?
180 if ($course != SITEID || $modid != 0) {
181 $where .= " AND l.course=:courseid";
182 $params['courseid'] = $course;
186 $where .= " AND l.module = :modname";
187 $params['modname'] = $modname;
190 if ('site_errors' === $modid) {
191 $where .= " AND ( l.action='error' OR l.action='infected' )";
193 //TODO: This assumes that modids are the same across sites... probably
195 $where .= " AND l.cmid = :modid";
196 $params['modid'] = $modid;
200 $firstletter = substr($modaction, 0, 1);
201 if ($firstletter == '-') {
202 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
203 $params['modaction'] = '%'.substr($modaction, 1).'%';
205 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
206 $params['modaction'] = '%'.$modaction.'%';
211 $where .= " AND l.userid = :user";
212 $params['user'] = $user;
216 $enddate = $date + 86400;
217 $where .= " AND l.time > :date AND l.time < :enddate";
218 $params['date'] = $date;
219 $params['enddate'] = $enddate;
223 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
224 if(!empty($result['totalcount'])) {
225 $where .= " ORDER BY $order";
226 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
228 $result['logs'] = array();
233 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
234 $modname="", $modid=0, $modaction="", $groupid=0) {
235 global $DB, $SESSION, $USER;
236 // It is assumed that $date is the GMT time of midnight for that day,
237 // and so the next 86400 seconds worth of logs are printed.
239 /// Setup for group handling.
241 /// If the group mode is separate, and this user does not have editing privileges,
242 /// then only the user's group can be viewed.
243 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
244 if (isset($SESSION->currentgroup[$course->id])) {
245 $groupid = $SESSION->currentgroup[$course->id];
247 $groupid = groups_get_all_groups($course->id, $USER->id);
248 if (is_array($groupid)) {
249 $groupid = array_shift(array_keys($groupid));
250 $SESSION->currentgroup[$course->id] = $groupid;
256 /// If this course doesn't have groups, no groupid can be specified.
257 else if (!$course->groupmode) {
264 if ($course->id != SITEID || $modid != 0) {
265 $joins[] = "l.course = :courseid";
266 $params['courseid'] = $course->id;
270 $joins[] = "l.module = :modname";
271 $params['modname'] = $modname;
274 if ('site_errors' === $modid) {
275 $joins[] = "( l.action='error' OR l.action='infected' )";
277 $joins[] = "l.cmid = :modid";
278 $params['modid'] = $modid;
282 $firstletter = substr($modaction, 0, 1);
283 if ($firstletter == '-') {
284 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
285 $params['modaction'] = '%'.substr($modaction, 1).'%';
287 $joins[] = $DB->sql_like('l.action', ':modaction', false);
288 $params['modaction'] = '%'.$modaction.'%';
293 /// Getting all members of a group.
294 if ($groupid and !$user) {
295 if ($gusers = groups_get_members($groupid)) {
296 $gusers = array_keys($gusers);
297 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
299 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
303 $joins[] = "l.userid = :userid";
304 $params['userid'] = $user;
308 $enddate = $date + 86400;
309 $joins[] = "l.time > :date AND l.time < :enddate";
310 $params['date'] = $date;
311 $params['enddate'] = $enddate;
314 $selector = implode(' AND ', $joins);
316 $totalcount = 0; // Initialise
318 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
319 $result['totalcount'] = $totalcount;
324 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
325 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
327 global $CFG, $DB, $OUTPUT;
329 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
330 $modname, $modid, $modaction, $groupid)) {
331 echo $OUTPUT->notification("No logs found!");
332 echo $OUTPUT->footer();
338 if ($course->id == SITEID) {
340 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
341 foreach ($ccc as $cc) {
342 $courses[$cc->id] = $cc->shortname;
346 $courses[$course->id] = $course->shortname;
349 $totalcount = $logs['totalcount'];
352 $tt = getdate(time());
353 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
355 $strftimedatetime = get_string("strftimedatetime");
357 echo "<div class=\"info\">\n";
358 print_string("displayingrecords", "", $totalcount);
361 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
363 $table = new html_table();
364 $table->classes = array('logtable','generaltable');
365 $table->align = array('right', 'left', 'left');
366 $table->head = array(
368 get_string('ip_address'),
369 get_string('fullnameuser'),
370 get_string('action'),
373 $table->data = array();
375 if ($course->id == SITEID) {
376 array_unshift($table->align, 'left');
377 array_unshift($table->head, get_string('course'));
380 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
381 if (empty($logs['logs'])) {
382 $logs['logs'] = array();
385 foreach ($logs['logs'] as $log) {
387 if (isset($ldcache[$log->module][$log->action])) {
388 $ld = $ldcache[$log->module][$log->action];
390 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
391 $ldcache[$log->module][$log->action] = $ld;
393 if ($ld && is_numeric($log->info)) {
394 // ugly hack to make sure fullname is shown correctly
395 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
396 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
398 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
403 $log->info = format_string($log->info);
405 // If $log->url has been trimmed short by the db size restriction
406 // code in add_to_log, keep a note so we don't add a link to a broken url
407 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
410 if ($course->id == SITEID) {
411 if (empty($log->course)) {
412 $row[] = get_string('site');
414 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
418 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
420 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
421 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
423 $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))));
425 $displayaction="$log->module $log->action";
427 $row[] = $displayaction;
429 $link = make_log_url($log->module,$log->url);
430 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
433 $table->data[] = $row;
436 echo html_writer::table($table);
437 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
441 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
442 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
444 global $CFG, $DB, $OUTPUT;
446 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
447 $modname, $modid, $modaction, $groupid)) {
448 echo $OUTPUT->notification("No logs found!");
449 echo $OUTPUT->footer();
453 if ($course->id == SITEID) {
455 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
456 foreach ($ccc as $cc) {
457 $courses[$cc->id] = $cc->shortname;
462 $totalcount = $logs['totalcount'];
465 $tt = getdate(time());
466 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
468 $strftimedatetime = get_string("strftimedatetime");
470 echo "<div class=\"info\">\n";
471 print_string("displayingrecords", "", $totalcount);
474 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
476 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
478 if ($course->id == SITEID) {
479 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
481 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
482 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
483 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
484 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
485 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
488 if (empty($logs['logs'])) {
494 foreach ($logs['logs'] as $log) {
496 $log->info = $log->coursename;
497 $row = ($row + 1) % 2;
499 if (isset($ldcache[$log->module][$log->action])) {
500 $ld = $ldcache[$log->module][$log->action];
502 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
503 $ldcache[$log->module][$log->action] = $ld;
505 if (0 && $ld && !empty($log->info)) {
506 // ugly hack to make sure fullname is shown correctly
507 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
508 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
510 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
515 $log->info = format_string($log->info);
517 echo '<tr class="r'.$row.'">';
518 if ($course->id == SITEID) {
519 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
520 echo "<td class=\"r$row c0\" >\n";
521 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
524 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
525 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
526 echo "<td class=\"r$row c2\" >\n";
527 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
528 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
530 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
531 echo "<td class=\"r$row c3\" >\n";
532 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
534 echo "<td class=\"r$row c4\">\n";
535 echo $log->action .': '.$log->module;
537 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
542 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
546 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
547 $modid, $modaction, $groupid) {
550 require_once($CFG->libdir . '/csvlib.class.php');
552 $csvexporter = new csv_export_writer('tab');
555 $header[] = get_string('course');
556 $header[] = get_string('time');
557 $header[] = get_string('ip_address');
558 $header[] = get_string('fullnameuser');
559 $header[] = get_string('action');
560 $header[] = get_string('info');
562 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
563 $modname, $modid, $modaction, $groupid)) {
569 if ($course->id == SITEID) {
571 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
572 foreach ($ccc as $cc) {
573 $courses[$cc->id] = $cc->shortname;
577 $courses[$course->id] = $course->shortname;
582 $tt = getdate(time());
583 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
585 $strftimedatetime = get_string("strftimedatetime");
587 $csvexporter->set_filename('logs', '.txt');
588 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
589 $csvexporter->add_data($title);
590 $csvexporter->add_data($header);
592 if (empty($logs['logs'])) {
596 foreach ($logs['logs'] as $log) {
597 if (isset($ldcache[$log->module][$log->action])) {
598 $ld = $ldcache[$log->module][$log->action];
600 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
601 $ldcache[$log->module][$log->action] = $ld;
603 if ($ld && is_numeric($log->info)) {
604 // ugly hack to make sure fullname is shown correctly
605 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
606 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
608 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
613 $log->info = format_string($log->info);
614 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
616 $coursecontext = context_course::instance($course->id);
617 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
618 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
619 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
620 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
621 $csvexporter->add_data($row);
623 $csvexporter->download_file();
628 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
629 $modid, $modaction, $groupid) {
633 require_once("$CFG->libdir/excellib.class.php");
635 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
636 $modname, $modid, $modaction, $groupid)) {
642 if ($course->id == SITEID) {
644 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
645 foreach ($ccc as $cc) {
646 $courses[$cc->id] = $cc->shortname;
650 $courses[$course->id] = $course->shortname;
655 $tt = getdate(time());
656 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
658 $strftimedatetime = get_string("strftimedatetime");
660 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
661 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
664 $workbook = new MoodleExcelWorkbook('-');
665 $workbook->send($filename);
667 $worksheet = array();
668 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
669 get_string('fullnameuser'), get_string('action'), get_string('info'));
671 // Creating worksheets
672 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
673 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
674 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
675 $worksheet[$wsnumber]->set_column(1, 1, 30);
676 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
677 userdate(time(), $strftimedatetime));
679 foreach ($headers as $item) {
680 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
685 if (empty($logs['logs'])) {
690 $formatDate =& $workbook->add_format();
691 $formatDate->set_num_format(get_string('log_excel_date_format'));
693 $row = FIRSTUSEDEXCELROW;
695 $myxls =& $worksheet[$wsnumber];
696 foreach ($logs['logs'] as $log) {
697 if (isset($ldcache[$log->module][$log->action])) {
698 $ld = $ldcache[$log->module][$log->action];
700 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
701 $ldcache[$log->module][$log->action] = $ld;
703 if ($ld && is_numeric($log->info)) {
704 // ugly hack to make sure fullname is shown correctly
705 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
706 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
708 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
713 $log->info = format_string($log->info);
714 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
717 if ($row > EXCELROWS) {
719 $myxls =& $worksheet[$wsnumber];
720 $row = FIRSTUSEDEXCELROW;
724 $coursecontext = context_course::instance($course->id);
726 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
727 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
728 $myxls->write($row, 2, $log->ip, '');
729 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
730 $myxls->write($row, 3, $fullname, '');
731 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
732 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
733 $myxls->write($row, 5, $log->info, '');
742 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
743 $modid, $modaction, $groupid) {
747 require_once("$CFG->libdir/odslib.class.php");
749 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
750 $modname, $modid, $modaction, $groupid)) {
756 if ($course->id == SITEID) {
758 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
759 foreach ($ccc as $cc) {
760 $courses[$cc->id] = $cc->shortname;
764 $courses[$course->id] = $course->shortname;
769 $tt = getdate(time());
770 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
772 $strftimedatetime = get_string("strftimedatetime");
774 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
775 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
778 $workbook = new MoodleODSWorkbook('-');
779 $workbook->send($filename);
781 $worksheet = array();
782 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
783 get_string('fullnameuser'), get_string('action'), get_string('info'));
785 // Creating worksheets
786 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
787 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
788 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
789 $worksheet[$wsnumber]->set_column(1, 1, 30);
790 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
791 userdate(time(), $strftimedatetime));
793 foreach ($headers as $item) {
794 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
799 if (empty($logs['logs'])) {
804 $formatDate =& $workbook->add_format();
805 $formatDate->set_num_format(get_string('log_excel_date_format'));
807 $row = FIRSTUSEDEXCELROW;
809 $myxls =& $worksheet[$wsnumber];
810 foreach ($logs['logs'] as $log) {
811 if (isset($ldcache[$log->module][$log->action])) {
812 $ld = $ldcache[$log->module][$log->action];
814 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
815 $ldcache[$log->module][$log->action] = $ld;
817 if ($ld && is_numeric($log->info)) {
818 // ugly hack to make sure fullname is shown correctly
819 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
820 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
822 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
827 $log->info = format_string($log->info);
828 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
831 if ($row > EXCELROWS) {
833 $myxls =& $worksheet[$wsnumber];
834 $row = FIRSTUSEDEXCELROW;
838 $coursecontext = context_course::instance($course->id);
840 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
841 $myxls->write_date($row, 1, $log->time);
842 $myxls->write_string($row, 2, $log->ip);
843 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
844 $myxls->write_string($row, 3, $fullname);
845 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
846 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
847 $myxls->write_string($row, 5, $log->info);
857 * For a given course, returns an array of course activity objects
858 * Each item in the array contains he following properties:
860 function get_array_of_activities($courseid) {
861 // cm - course module id
862 // mod - name of the module (eg forum)
863 // section - the number of the section (eg week or topic)
864 // name - the name of the instance
865 // visible - is the instance visible or not
866 // groupingid - grouping id
867 // groupmembersonly - is this instance visible to group members only
868 // extra - contains extra string to include in any link
870 if(!empty($CFG->enableavailability)) {
871 require_once($CFG->libdir.'/conditionlib.php');
874 $course = $DB->get_record('course', array('id'=>$courseid));
876 if (empty($course)) {
877 throw new moodle_exception('courseidnotfound');
882 $rawmods = get_course_mods($courseid);
883 if (empty($rawmods)) {
884 return $mod; // always return array
887 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
888 foreach ($sections as $section) {
889 if (!empty($section->sequence)) {
890 $sequence = explode(",", $section->sequence);
891 foreach ($sequence as $seq) {
892 if (empty($rawmods[$seq])) {
895 $mod[$seq] = new stdClass();
896 $mod[$seq]->id = $rawmods[$seq]->instance;
897 $mod[$seq]->cm = $rawmods[$seq]->id;
898 $mod[$seq]->mod = $rawmods[$seq]->modname;
900 // Oh dear. Inconsistent names left here for backward compatibility.
901 $mod[$seq]->section = $section->section;
902 $mod[$seq]->sectionid = $rawmods[$seq]->section;
904 $mod[$seq]->module = $rawmods[$seq]->module;
905 $mod[$seq]->added = $rawmods[$seq]->added;
906 $mod[$seq]->score = $rawmods[$seq]->score;
907 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
908 $mod[$seq]->visible = $rawmods[$seq]->visible;
909 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
910 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
911 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
912 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
913 $mod[$seq]->indent = $rawmods[$seq]->indent;
914 $mod[$seq]->completion = $rawmods[$seq]->completion;
915 $mod[$seq]->extra = "";
916 $mod[$seq]->completiongradeitemnumber =
917 $rawmods[$seq]->completiongradeitemnumber;
918 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
919 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
920 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
921 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
922 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
923 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
924 if (!empty($CFG->enableavailability)) {
925 condition_info::fill_availability_conditions($rawmods[$seq]);
926 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
927 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
928 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
931 $modname = $mod[$seq]->mod;
932 $functionname = $modname."_get_coursemodule_info";
934 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
938 include_once("$CFG->dirroot/mod/$modname/lib.php");
940 if ($hasfunction = function_exists($functionname)) {
941 if ($info = $functionname($rawmods[$seq])) {
942 if (!empty($info->icon)) {
943 $mod[$seq]->icon = $info->icon;
945 if (!empty($info->iconcomponent)) {
946 $mod[$seq]->iconcomponent = $info->iconcomponent;
948 if (!empty($info->name)) {
949 $mod[$seq]->name = $info->name;
951 if ($info instanceof cached_cm_info) {
952 // When using cached_cm_info you can include three new fields
953 // that aren't available for legacy code
954 if (!empty($info->content)) {
955 $mod[$seq]->content = $info->content;
957 if (!empty($info->extraclasses)) {
958 $mod[$seq]->extraclasses = $info->extraclasses;
960 if (!empty($info->iconurl)) {
961 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
962 $url = new moodle_url($info->iconurl);
963 $mod[$seq]->iconurl = $url->out(false);
965 if (!empty($info->onclick)) {
966 $mod[$seq]->onclick = $info->onclick;
968 if (!empty($info->customdata)) {
969 $mod[$seq]->customdata = $info->customdata;
972 // When using a stdclass, the (horrible) deprecated ->extra field
973 // is available for BC
974 if (!empty($info->extra)) {
975 $mod[$seq]->extra = $info->extra;
980 // When there is no modname_get_coursemodule_info function,
981 // but showdescriptions is enabled, then we use the 'intro'
982 // and 'introformat' fields in the module table
983 if (!$hasfunction && $rawmods[$seq]->showdescription) {
984 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
985 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
986 // Set content from intro and introformat. Filters are disabled
987 // because we filter it with format_text at display time
988 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
989 $modvalues, $rawmods[$seq]->id, false);
991 // To save making another query just below, put name in here
992 $mod[$seq]->name = $modvalues->name;
995 if (!isset($mod[$seq]->name)) {
996 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
999 // Minimise the database size by unsetting default options when they are
1000 // 'empty'. This list corresponds to code in the cm_info constructor.
1001 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1002 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1003 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1004 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1005 'completionview', 'completionexpected', 'score', 'showdescription')
1007 if (property_exists($mod[$seq], $property) &&
1008 empty($mod[$seq]->{$property})) {
1009 unset($mod[$seq]->{$property});
1012 // Special case: this value is usually set to null, but may be 0
1013 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1014 is_null($mod[$seq]->completiongradeitemnumber)) {
1015 unset($mod[$seq]->completiongradeitemnumber);
1025 * Returns the localised human-readable names of all used modules
1027 * @param bool $plural if true returns the plural forms of the names
1028 * @return array where key is the module name (component name without 'mod_') and
1029 * the value is the human-readable string. Array sorted alphabetically by value
1031 function get_module_types_names($plural = false) {
1032 static $modnames = null;
1034 if ($modnames === null) {
1035 $modnames = array(0 => array(), 1 => array());
1036 if ($allmods = $DB->get_records("modules")) {
1037 foreach ($allmods as $mod) {
1038 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1039 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1040 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1043 core_collator::asort($modnames[0]);
1044 core_collator::asort($modnames[1]);
1047 return $modnames[(int)$plural];
1051 * Set highlighted section. Only one section can be highlighted at the time.
1053 * @param int $courseid course id
1054 * @param int $marker highlight section with this number, 0 means remove higlightin
1057 function course_set_marker($courseid, $marker) {
1059 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1060 format_base::reset_course_cache($courseid);
1064 * For a given course section, marks it visible or hidden,
1065 * and does the same for every activity in that section
1067 * @param int $courseid course id
1068 * @param int $sectionnumber The section number to adjust
1069 * @param int $visibility The new visibility
1070 * @return array A list of resources which were hidden in the section
1072 function set_section_visible($courseid, $sectionnumber, $visibility) {
1075 $resourcestotoggle = array();
1076 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1077 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1078 if (!empty($section->sequence)) {
1079 $modules = explode(",", $section->sequence);
1080 foreach ($modules as $moduleid) {
1081 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1083 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1084 set_coursemodule_visible($moduleid, $cm->visibleold);
1086 // We hide the section, so we hide the module but we store the original state in visibleold.
1087 set_coursemodule_visible($moduleid, 0);
1088 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1093 rebuild_course_cache($courseid, true);
1095 // Determine which modules are visible for AJAX update
1096 if (!empty($modules)) {
1097 list($insql, $params) = $DB->get_in_or_equal($modules);
1098 $select = 'id ' . $insql . ' AND visible = ?';
1099 array_push($params, $visibility);
1101 $select .= ' AND visibleold = 1';
1103 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1106 return $resourcestotoggle;
1110 * Retrieve all metadata for the requested modules
1112 * @param object $course The Course
1113 * @param array $modnames An array containing the list of modules and their
1115 * @param int $sectionreturn The section to return to
1116 * @return array A list of stdClass objects containing metadata about each
1119 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1120 global $CFG, $OUTPUT;
1122 // get_module_metadata will be called once per section on the page and courses may show
1123 // different modules to one another
1124 static $modlist = array();
1125 if (!isset($modlist[$course->id])) {
1126 $modlist[$course->id] = array();
1130 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1131 if ($sectionreturn !== null) {
1132 $urlbase->param('sr', $sectionreturn);
1134 foreach($modnames as $modname => $modnamestr) {
1135 if (!course_allowed_module($course, $modname)) {
1138 if (isset($modlist[$course->id][$modname])) {
1139 // This module is already cached
1140 $return[$modname] = $modlist[$course->id][$modname];
1144 // Include the module lib
1145 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1146 if (!file_exists($libfile)) {
1149 include_once($libfile);
1151 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1152 $gettypesfunc = $modname.'_get_types';
1153 if (function_exists($gettypesfunc)) {
1154 $types = $gettypesfunc();
1155 if (is_array($types) && count($types) > 0) {
1156 $group = new stdClass();
1157 $group->name = $modname;
1158 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1159 foreach($types as $type) {
1160 if ($type->typestr === '--') {
1163 if (strpos($type->typestr, '--') === 0) {
1164 $group->title = str_replace('--', '', $type->typestr);
1167 // Set the Sub Type metadata
1168 $subtype = new stdClass();
1169 $subtype->title = $type->typestr;
1170 $subtype->type = str_replace('&', '&', $type->type);
1171 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1172 $subtype->archetype = $type->modclass;
1174 // The group archetype should match the subtype archetypes and all subtypes
1175 // should have the same archetype
1176 $group->archetype = $subtype->archetype;
1178 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1179 $subtype->help = get_string('help' . $subtype->name, $modname);
1181 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1182 $group->types[] = $subtype;
1184 $modlist[$course->id][$modname] = $group;
1187 $module = new stdClass();
1188 $module->title = $modnamestr;
1189 $module->name = $modname;
1190 $module->link = new moodle_url($urlbase, array('add' => $modname));
1191 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1192 $sm = get_string_manager();
1193 if ($sm->string_exists('modulename_help', $modname)) {
1194 $module->help = get_string('modulename_help', $modname);
1195 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1196 $link = get_string('modulename_link', $modname);
1197 $linktext = get_string('morehelp');
1198 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1201 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1202 $modlist[$course->id][$modname] = $module;
1204 if (isset($modlist[$course->id][$modname])) {
1205 $return[$modname] = $modlist[$course->id][$modname];
1207 debugging("Invalid module metadata configuration for {$modname}");
1215 * Return the course category context for the category with id $categoryid, except
1216 * that if $categoryid is 0, return the system context.
1218 * @param integer $categoryid a category id or 0.
1219 * @return object the corresponding context
1221 function get_category_or_system_context($categoryid) {
1223 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1225 return context_system::instance();
1230 * Returns full course categories trees to be used in html_writer::select()
1232 * Calls {@link coursecat::make_categories_list()} to build the tree and
1233 * adds whitespace to denote nesting
1235 * @return array array mapping coursecat id to the display name
1237 function make_categories_options() {
1239 require_once($CFG->libdir. '/coursecatlib.php');
1240 $cats = coursecat::make_categories_list('', 0, ' / ');
1241 foreach ($cats as $key => $value) {
1242 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
1243 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
1249 * Print the buttons relating to course requests.
1251 * @param object $context current page context.
1253 function print_course_request_buttons($context) {
1254 global $CFG, $DB, $OUTPUT;
1255 if (empty($CFG->enablecourserequests)) {
1258 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1259 /// Print a button to request a new course
1260 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1262 /// Print a button to manage pending requests
1263 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1264 $disabled = !$DB->record_exists('course_request', array());
1265 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1270 * Does the user have permission to edit things in this category?
1272 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1273 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1275 function can_edit_in_category($categoryid = 0) {
1276 $context = get_category_or_system_context($categoryid);
1277 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1280 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1282 function add_course_module($mod) {
1285 $mod->added = time();
1288 $cmid = $DB->insert_record("course_modules", $mod);
1289 rebuild_course_cache($mod->course, true);
1294 * Creates missing course section(s) and rebuilds course cache
1296 * @param int|stdClass $courseorid course id or course object
1297 * @param int|array $sections list of relative section numbers to create
1298 * @return bool if there were any sections created
1300 function course_create_sections_if_missing($courseorid, $sections) {
1302 if (!is_array($sections)) {
1303 $sections = array($sections);
1305 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1306 if (is_object($courseorid)) {
1307 $courseorid = $courseorid->id;
1309 $coursechanged = false;
1310 foreach ($sections as $sectionnum) {
1311 if (!in_array($sectionnum, $existing)) {
1312 $cw = new stdClass();
1313 $cw->course = $courseorid;
1314 $cw->section = $sectionnum;
1316 $cw->summaryformat = FORMAT_HTML;
1318 $id = $DB->insert_record("course_sections", $cw);
1319 $coursechanged = true;
1322 if ($coursechanged) {
1323 rebuild_course_cache($courseorid, true);
1325 return $coursechanged;
1329 * Adds an existing module to the section
1331 * Updates both tables {course_sections} and {course_modules}
1333 * Note: This function does not use modinfo PROVIDED that the section you are
1334 * adding the module to already exists. If the section does not exist, it will
1335 * build modinfo if necessary and create the section.
1337 * @param int|stdClass $courseorid course id or course object
1338 * @param int $cmid id of the module already existing in course_modules table
1339 * @param int $sectionnum relative number of the section (field course_sections.section)
1340 * If section does not exist it will be created
1341 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1342 * before which the module needs to be included. Null for inserting in the
1343 * end of the section
1344 * @return int The course_sections ID where the module is inserted
1346 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1347 global $DB, $COURSE;
1348 if (is_object($beforemod)) {
1349 $beforemod = $beforemod->id;
1351 if (is_object($courseorid)) {
1352 $courseid = $courseorid->id;
1354 $courseid = $courseorid;
1356 // Do not try to use modinfo here, there is no guarantee it is valid!
1357 $section = $DB->get_record('course_sections',
1358 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
1360 // This function call requires modinfo.
1361 course_create_sections_if_missing($courseorid, $sectionnum);
1362 $section = $DB->get_record('course_sections',
1363 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
1366 $modarray = explode(",", trim($section->sequence));
1367 if (empty($section->sequence)) {
1368 $newsequence = "$cmid";
1369 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1370 $insertarray = array($cmid, $beforemod);
1371 array_splice($modarray, $key[0], 1, $insertarray);
1372 $newsequence = implode(",", $modarray);
1374 $newsequence = "$section->sequence,$cmid";
1376 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1377 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1378 if (is_object($courseorid)) {
1379 rebuild_course_cache($courseorid->id, true);
1381 rebuild_course_cache($courseorid, true);
1383 return $section->id; // Return course_sections ID that was used.
1386 function set_coursemodule_groupmode($id, $groupmode) {
1388 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1389 if ($cm->groupmode != $groupmode) {
1390 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1391 rebuild_course_cache($cm->course, true);
1393 return ($cm->groupmode != $groupmode);
1396 function set_coursemodule_idnumber($id, $idnumber) {
1398 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1399 if ($cm->idnumber != $idnumber) {
1400 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1401 rebuild_course_cache($cm->course, true);
1403 return ($cm->idnumber != $idnumber);
1407 * Set the visibility of a module and inherent properties.
1409 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1410 * has been moved to {@link set_section_visible()} which was the only place from which
1411 * the parameter was used.
1413 * @param int $id of the module
1414 * @param int $visible state of the module
1415 * @return bool false when the module was not found, true otherwise
1417 function set_coursemodule_visible($id, $visible) {
1419 require_once($CFG->libdir.'/gradelib.php');
1420 require_once($CFG->dirroot.'/calendar/lib.php');
1422 // Trigger developer's attention when using the previously removed argument.
1423 if (func_num_args() > 2) {
1424 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1425 has been removed.', DEBUG_DEVELOPER);
1428 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1432 // Create events and propagate visibility to associated grade items if the value has changed.
1433 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1434 if ($cm->visible == $visible) {
1438 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1441 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1442 foreach($events as $event) {
1444 $event = new calendar_event($event);
1445 $event->toggle_visibility(true);
1447 $event = new calendar_event($event);
1448 $event->toggle_visibility(false);
1453 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1454 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1456 foreach ($grade_items as $grade_item) {
1457 $grade_item->set_hidden(!$visible);
1461 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1462 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1463 $cminfo = new stdClass();
1465 $cminfo->visible = $visible;
1466 $cminfo->visibleold = $visible;
1467 $DB->update_record('course_modules', $cminfo);
1469 rebuild_course_cache($cm->course, true);
1474 * This function will handles the whole deletion process of a module. This includes calling
1475 * the modules delete_instance function, deleting files, events, grades, conditional data,
1476 * the data in the course_module and course_sections table and adding a module deletion
1479 * @param int $cmid the course module id
1482 function course_delete_module($cmid) {
1483 global $CFG, $DB, $USER;
1485 require_once($CFG->libdir.'/gradelib.php');
1486 require_once($CFG->dirroot.'/blog/lib.php');
1487 require_once($CFG->dirroot.'/calendar/lib.php');
1489 // Get the course module.
1490 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1494 // Get the module context.
1495 $modcontext = context_module::instance($cm->id);
1497 // Get the course module name.
1498 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1500 // Get the file location of the delete_instance function for this module.
1501 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1503 // Include the file required to call the delete_instance function for this module.
1504 if (file_exists($modlib)) {
1505 require_once($modlib);
1507 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1508 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1511 $deleteinstancefunction = $modulename . '_delete_instance';
1513 // Ensure the delete_instance function exists for this module.
1514 if (!function_exists($deleteinstancefunction)) {
1515 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1516 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1519 // Call the delete_instance function, if it returns false throw an exception.
1520 if (!$deleteinstancefunction($cm->instance)) {
1521 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1522 "Cannot delete the module $modulename (instance).");
1525 // Remove all module files in case modules forget to do that.
1526 $fs = get_file_storage();
1527 $fs->delete_area_files($modcontext->id);
1529 // Delete events from calendar.
1530 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1531 foreach($events as $event) {
1532 $calendarevent = calendar_event::load($event->id);
1533 $calendarevent->delete();
1537 // Delete grade items, outcome items and grades attached to modules.
1538 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1539 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1540 foreach ($grade_items as $grade_item) {
1541 $grade_item->delete('moddelete');
1545 // Delete completion and availability data; it is better to do this even if the
1546 // features are not turned on, in case they were turned on previously (these will be
1547 // very quick on an empty table).
1548 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1549 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
1550 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
1551 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1552 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1554 // Delete the context.
1555 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1557 // Delete the module from the course_modules table.
1558 $DB->delete_records('course_modules', array('id' => $cm->id));
1560 // Delete module from that section.
1561 if (!delete_mod_from_section($cm->id, $cm->section)) {
1562 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1563 "Cannot delete the module $modulename (instance) from section.");
1566 // Trigger a mod_deleted event with information about this module.
1567 $eventdata = new stdClass();
1568 $eventdata->modulename = $modulename;
1569 $eventdata->cmid = $cm->id;
1570 $eventdata->courseid = $cm->course;
1571 $eventdata->userid = $USER->id;
1572 events_trigger('mod_deleted', $eventdata);
1574 add_to_log($cm->course, 'course', "delete mod",
1575 "view.php?id=$cm->course",
1576 "$modulename $cm->instance", $cm->id);
1578 rebuild_course_cache($cm->course, true);
1581 function delete_mod_from_section($modid, $sectionid) {
1584 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1586 $modarray = explode(",", $section->sequence);
1588 if ($key = array_keys ($modarray, $modid)) {
1589 array_splice($modarray, $key[0], 1);
1590 $newsequence = implode(",", $modarray);
1591 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1592 rebuild_course_cache($section->course, true);
1603 * Moves a section within a course, from a position to another.
1604 * Be very careful: $section and $destination refer to section number,
1607 * @param object $course
1608 * @param int $section Section number (not id!!!)
1609 * @param int $destination
1610 * @return boolean Result
1612 function move_section_to($course, $section, $destination) {
1613 /// Moves a whole course section up and down within the course
1616 if (!$destination && $destination != 0) {
1620 // compartibility with course formats using field 'numsections'
1621 $courseformatoptions = course_get_format($course)->get_format_options();
1622 if ((array_key_exists('numsections', $courseformatoptions) &&
1623 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1627 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1628 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1629 'section ASC, id ASC', 'id, section')) {
1633 $movedsections = reorder_sections($sections, $section, $destination);
1635 // Update all sections. Do this in 2 steps to avoid breaking database
1636 // uniqueness constraint
1637 $transaction = $DB->start_delegated_transaction();
1638 foreach ($movedsections as $id => $position) {
1639 if ($sections[$id] !== $position) {
1640 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1643 foreach ($movedsections as $id => $position) {
1644 if ($sections[$id] !== $position) {
1645 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1649 // If we move the highlighted section itself, then just highlight the destination.
1650 // Adjust the higlighted section location if we move something over it either direction.
1651 if ($section == $course->marker) {
1652 course_set_marker($course->id, $destination);
1653 } elseif ($section > $course->marker && $course->marker >= $destination) {
1654 course_set_marker($course->id, $course->marker+1);
1655 } elseif ($section < $course->marker && $course->marker <= $destination) {
1656 course_set_marker($course->id, $course->marker-1);
1659 $transaction->allow_commit();
1660 rebuild_course_cache($course->id, true);
1665 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1666 * an original position number and a target position number, rebuilds the array so that the
1667 * move is made without any duplication of section positions.
1668 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1669 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1671 * @param array $sections
1672 * @param int $origin_position
1673 * @param int $target_position
1676 function reorder_sections($sections, $origin_position, $target_position) {
1677 if (!is_array($sections)) {
1681 // We can't move section position 0
1682 if ($origin_position < 1) {
1683 echo "We can't move section position 0";
1687 // Locate origin section in sections array
1688 if (!$origin_key = array_search($origin_position, $sections)) {
1689 echo "searched position not in sections array";
1690 return false; // searched position not in sections array
1693 // Extract origin section
1694 $origin_section = $sections[$origin_key];
1695 unset($sections[$origin_key]);
1697 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1699 $append_array = array();
1700 foreach ($sections as $id => $position) {
1702 $append_array[$id] = $position;
1703 unset($sections[$id]);
1705 if ($position == $target_position) {
1706 if ($target_position < $origin_position) {
1707 $append_array[$id] = $position;
1708 unset($sections[$id]);
1714 // Append moved section
1715 $sections[$origin_key] = $origin_section;
1717 // Append rest of array (if applicable)
1718 if (!empty($append_array)) {
1719 foreach ($append_array as $id => $position) {
1720 $sections[$id] = $position;
1724 // Renumber positions
1726 foreach ($sections as $id => $p) {
1727 $sections[$id] = $position;
1736 * Move the module object $mod to the specified $section
1737 * If $beforemod exists then that is the module
1738 * before which $modid should be inserted
1740 * @param stdClass|cm_info $mod
1741 * @param stdClass|section_info $section
1742 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1743 * before which the module needs to be included. Null for inserting in the
1744 * end of the section
1745 * @return int new value for module visibility (0 or 1)
1747 function moveto_module($mod, $section, $beforemod=NULL) {
1748 global $OUTPUT, $DB;
1750 // Current module visibility state - return value of this function.
1751 $modvisible = $mod->visible;
1753 // Remove original module from original section.
1754 if (! delete_mod_from_section($mod->id, $mod->section)) {
1755 echo $OUTPUT->notification("Could not delete module from existing section");
1758 // If moving to a hidden section then hide module.
1759 if ($mod->section != $section->id) {
1760 if (!$section->visible && $mod->visible) {
1761 // Module was visible but must become hidden after moving to hidden section.
1763 set_coursemodule_visible($mod->id, 0);
1764 // Set visibleold to 1 so module will be visible when section is made visible.
1765 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1767 if ($section->visible && !$mod->visible) {
1768 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1769 set_coursemodule_visible($mod->id, $mod->visibleold);
1770 $modvisible = $mod->visibleold;
1774 // Add the module into the new section.
1775 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1780 * Returns the list of all editing actions that current user can perform on the module
1782 * @param cm_info $mod The module to produce editing buttons for
1783 * @param int $indent The current indenting (default -1 means no move left-right actions)
1784 * @param int $sr The section to link back to (used for creating the links)
1785 * @return array array of action_link or pix_icon objects
1787 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1788 global $COURSE, $SITE;
1792 $coursecontext = context_course::instance($mod->course);
1793 $modcontext = context_module::instance($mod->id);
1795 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1796 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1798 // No permission to edit anything.
1799 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1803 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1806 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1807 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
1808 $str->assign = get_string('assignroles', 'role');
1809 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1810 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1811 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1812 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
1813 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
1814 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1817 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1820 $baseurl->param('sr', $sr);
1825 if ($mod->has_view() && $hasmanageactivities &&
1826 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
1827 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
1828 // we will not display link if we are on some other-course page (where we should not see this module anyway)
1829 $actions['title'] = new action_menu_link_secondary(
1830 new moodle_url($baseurl, array('update' => $mod->id)),
1831 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
1833 array('class' => 'editing_title', 'data-action' => 'edittitle')
1838 if ($hasmanageactivities) {
1839 if (right_to_left()) { // Exchange arrows on RTL
1840 $rightarrow = 't/left';
1841 $leftarrow = 't/right';
1843 $rightarrow = 't/right';
1844 $leftarrow = 't/left';
1847 $hiddenclass = 'hidden';
1851 $actions['moveleft'] = new action_menu_link_secondary(
1852 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1853 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1855 array('class' => 'editing_moveleft ' . $hiddenclass, 'data-action' => 'moveleft')
1857 $hiddenclass = 'hidden';
1861 $actions['moveright'] = new action_menu_link_secondary(
1862 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1863 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1865 array('class' => 'editing_moveright ' . $hiddenclass, 'data-action' => 'moveright')
1870 if ($hasmanageactivities) {
1871 $actions['move'] = new action_menu_link_primary(
1872 new moodle_url($baseurl, array('copy' => $mod->id)),
1873 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1875 array('class' => 'editing_move status', 'data-action' => 'move')
1880 if ($hasmanageactivities) {
1881 $actions['update'] = new action_menu_link_secondary(
1882 new moodle_url($baseurl, array('update' => $mod->id)),
1883 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1885 array('class' => 'editing_update', 'data-action' => 'update')
1889 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1890 // Note that restoring on front page is never allowed.
1891 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
1892 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
1893 $actions['duplicate'] = new action_menu_link_secondary(
1894 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1895 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1897 array('class' => 'editing_duplicate', 'data-action' => 'duplicate')
1902 if ($hasmanageactivities) {
1903 $actions['delete'] = new action_menu_link_secondary(
1904 new moodle_url($baseurl, array('delete' => $mod->id)),
1905 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1907 array('class' => 'editing_delete', 'data-action' => 'delete')
1912 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1913 if ($mod->visible) {
1914 $actions['hide'] = new action_menu_link_primary(
1915 new moodle_url($baseurl, array('hide' => $mod->id)),
1916 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1918 array('class' => 'editing_hide', 'data-action' => 'hide')
1921 $actions['show'] = new action_menu_link_primary(
1922 new moodle_url($baseurl, array('show' => $mod->id)),
1923 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1925 array('class' => 'editing_show', 'data-action' => 'show')
1931 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1932 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1933 $nextgroupmode = VISIBLEGROUPS;
1934 $grouptitle = $str->groupsseparate;
1935 $forcedgrouptitle = $str->forcedgroupsseparate;
1936 $actionname = 'groupsseparate';
1937 $groupimage = 't/groups';
1938 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1939 $nextgroupmode = NOGROUPS;
1940 $grouptitle = $str->groupsvisible;
1941 $forcedgrouptitle = $str->forcedgroupsvisible;
1942 $actionname = 'groupsvisible';
1943 $groupimage = 't/groupv';
1945 $nextgroupmode = SEPARATEGROUPS;
1946 $grouptitle = $str->groupsnone;
1947 $forcedgrouptitle = $str->forcedgroupsnone;
1948 $actionname = 'groupsnone';
1949 $groupimage = 't/groupn';
1951 if (!$mod->coursegroupmodeforce) {
1952 $actions[$actionname] = new action_menu_link_primary(
1953 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1954 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1956 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode)
1959 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('class' => 'iconsmall'));
1964 if (has_capability('moodle/role:assign', $modcontext)){
1965 $actions['assign'] = new action_menu_link_secondary(
1966 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1967 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1969 array('class' => 'editing_assign', 'data-action' => 'assignroles')
1977 * given a course object with shortname & fullname, this function will
1978 * truncate the the number of chars allowed and add ... if it was too long
1980 function course_format_name ($course,$max=100) {
1982 $context = context_course::instance($course->id);
1983 $shortname = format_string($course->shortname, true, array('context' => $context));
1984 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1985 $str = $shortname.': '. $fullname;
1986 if (core_text::strlen($str) <= $max) {
1990 return core_text::substr($str,0,$max-3).'...';
1995 * Is the user allowed to add this type of module to this course?
1996 * @param object $course the course settings. Only $course->id is used.
1997 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
1998 * @return bool whether the current user is allowed to add this type of module to this course.
2000 function course_allowed_module($course, $modname) {
2001 if (is_numeric($modname)) {
2002 throw new coding_exception('Function course_allowed_module no longer
2003 supports numeric module ids. Please update your code to pass the module name.');
2006 $capability = 'mod/' . $modname . ':addinstance';
2007 if (!get_capability_info($capability)) {
2008 // Debug warning that the capability does not exist, but no more than once per page.
2009 static $warned = array();
2010 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2011 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2012 debugging('The module ' . $modname . ' does not define the standard capability ' .
2013 $capability , DEBUG_DEVELOPER);
2014 $warned[$modname] = 1;
2017 // If the capability does not exist, the module can always be added.
2021 $coursecontext = context_course::instance($course->id);
2022 return has_capability($capability, $coursecontext);
2026 * Efficiently moves many courses around while maintaining
2027 * sortorder in order.
2029 * @param array $courseids is an array of course ids
2030 * @param int $categoryid
2031 * @return bool success
2033 function move_courses($courseids, $categoryid) {
2036 if (empty($courseids)) {
2041 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2045 $courseids = array_reverse($courseids);
2046 $newparent = context_coursecat::instance($category->id);
2049 list($where, $params) = $DB->get_in_or_equal($courseids);
2050 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params);
2051 foreach ($dbcourses as $dbcourse) {
2052 $course = new stdClass();
2053 $course->id = $dbcourse->id;
2054 $course->category = $category->id;
2055 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2056 if ($category->visible == 0) {
2057 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2058 // to previous state if somebody unhides the category.
2059 $course->visible = 0;
2062 $DB->update_record('course', $course);
2064 // Store the context.
2065 $context = context_course::instance($course->id);
2067 // Update the course object we are passing to the event.
2068 $dbcourse->category = $course->category;
2069 $dbcourse->sortorder = $course->sortorder;
2070 if (isset($course->visible)) {
2071 $dbcourse->visible = $course->visible;
2074 // Trigger a course updated event.
2075 $event = \core\event\course_updated::create(array(
2076 'objectid' => $course->id,
2077 'context' => $context,
2078 'other' => array('shortname' => $dbcourse->shortname,
2079 'fullname' => $dbcourse->fullname)
2081 $event->add_record_snapshot('course', $dbcourse);
2082 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2085 $context->update_moved($newparent);
2087 fix_course_sortorder();
2088 cache_helper::purge_by_event('changesincourse');
2094 * Returns the display name of the given section that the course prefers
2096 * Implementation of this function is provided by course format
2097 * @see format_base::get_section_name()
2099 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2100 * @param int|stdClass $section Section object from database or just field course_sections.section
2101 * @return string Display name that the course format prefers, e.g. "Week 2"
2103 function get_section_name($courseorid, $section) {
2104 return course_get_format($courseorid)->get_section_name($section);
2108 * Tells if current course format uses sections
2110 * @param string $format Course format ID e.g. 'weeks' $course->format
2113 function course_format_uses_sections($format) {
2114 $course = new stdClass();
2115 $course->format = $format;
2116 return course_get_format($course)->uses_sections();
2120 * Returns the information about the ajax support in the given source format
2122 * The returned object's property (boolean)capable indicates that
2123 * the course format supports Moodle course ajax features.
2124 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2126 * @param string $format
2129 function course_format_ajax_support($format) {
2130 $course = new stdClass();
2131 $course->format = $format;
2132 return course_get_format($course)->supports_ajax();
2136 * Can the current user delete this course?
2137 * Course creators have exception,
2138 * 1 day after the creation they can sill delete the course.
2139 * @param int $courseid
2142 function can_delete_course($courseid) {
2145 $context = context_course::instance($courseid);
2147 if (has_capability('moodle/course:delete', $context)) {
2151 // hack: now try to find out if creator created this course recently (1 day)
2152 if (!has_capability('moodle/course:create', $context)) {
2156 $since = time() - 60*60*24;
2158 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2159 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2161 return $DB->record_exists_select('log', $select, $params);
2165 * Save the Your name for 'Some role' strings.
2167 * @param integer $courseid the id of this course.
2168 * @param array $data the data that came from the course settings form.
2170 function save_local_role_names($courseid, $data) {
2172 $context = context_course::instance($courseid);
2174 foreach ($data as $fieldname => $value) {
2175 if (strpos($fieldname, 'role_') !== 0) {
2178 list($ignored, $roleid) = explode('_', $fieldname);
2180 // make up our mind whether we want to delete, update or insert
2182 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2184 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2185 $rolename->name = $value;
2186 $DB->update_record('role_names', $rolename);
2189 $rolename = new stdClass;
2190 $rolename->contextid = $context->id;
2191 $rolename->roleid = $roleid;
2192 $rolename->name = $value;
2193 $DB->insert_record('role_names', $rolename);
2199 * Returns options to use in course overviewfiles filemanager
2201 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2202 * may be empty if course does not exist yet (course create form)
2203 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2204 * or null if overviewfiles are disabled
2206 function course_overviewfiles_options($course) {
2208 if (empty($CFG->courseoverviewfileslimit)) {
2211 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2212 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2213 $accepted_types = '*';
2215 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2216 // Make sure extensions are prefixed with dot unless they are valid typegroups
2217 foreach ($accepted_types as $i => $type) {
2218 if (substr($type, 0, 1) !== '.') {
2219 require_once($CFG->libdir. '/filelib.php');
2220 if (!count(file_get_typegroup('extension', $type))) {
2221 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2222 $accepted_types[$i] = '.'. $type;
2227 if (!empty($corrected)) {
2228 set_config('courseoverviewfilesext', join(',', $accepted_types));
2232 'maxfiles' => $CFG->courseoverviewfileslimit,
2233 'maxbytes' => $CFG->maxbytes,
2235 'accepted_types' => $accepted_types
2237 if (!empty($course->id)) {
2238 $options['context'] = context_course::instance($course->id);
2239 } else if (is_int($course) && $course > 0) {
2240 $options['context'] = context_course::instance($course);
2246 * Create a course and either return a $course object
2248 * Please note this functions does not verify any access control,
2249 * the calling code is responsible for all validation (usually it is the form definition).
2251 * @param array $editoroptions course description editor options
2252 * @param object $data - all the data needed for an entry in the 'course' table
2253 * @return object new course instance
2255 function create_course($data, $editoroptions = NULL) {
2258 //check the categoryid - must be given for all new courses
2259 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2261 // Check if the shortname already exists.
2262 if (!empty($data->shortname)) {
2263 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2264 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2268 // Check if the idnumber already exists.
2269 if (!empty($data->idnumber)) {
2270 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2271 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2275 $data->timecreated = time();
2276 $data->timemodified = $data->timecreated;
2278 // place at beginning of any category
2279 $data->sortorder = 0;
2281 if ($editoroptions) {
2282 // summary text is updated later, we need context to store the files first
2283 $data->summary = '';
2284 $data->summary_format = FORMAT_HTML;
2287 if (!isset($data->visible)) {
2288 // data not from form, add missing visibility info
2289 $data->visible = $category->visible;
2291 $data->visibleold = $data->visible;
2293 $newcourseid = $DB->insert_record('course', $data);
2294 $context = context_course::instance($newcourseid, MUST_EXIST);
2296 if ($editoroptions) {
2297 // Save the files used in the summary editor and store
2298 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2299 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2300 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2302 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2303 // Save the course overviewfiles
2304 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2307 // update course format options
2308 course_get_format($newcourseid)->update_course_format_options($data);
2310 $course = course_get_format($newcourseid)->get_course();
2313 blocks_add_default_course_blocks($course);
2315 // Create a default section.
2316 course_create_sections_if_missing($course, 0);
2318 fix_course_sortorder();
2319 // purge appropriate caches in case fix_course_sortorder() did not change anything
2320 cache_helper::purge_by_event('changesincourse');
2322 // new context created - better mark it as dirty
2323 $context->mark_dirty();
2325 // Save any custom role names.
2326 save_local_role_names($course->id, (array)$data);
2328 // set up enrolments
2329 enrol_course_updated(true, $course, $data);
2331 // Trigger a course created event.
2332 $event = \core\event\course_created::create(array(
2333 'objectid' => $course->id,
2334 'context' => context_course::instance($course->id),
2335 'other' => array('shortname' => $course->shortname,
2336 'fullname' => $course->fullname)
2338 $event->add_record_snapshot('course', $course);
2347 * Please note this functions does not verify any access control,
2348 * the calling code is responsible for all validation (usually it is the form definition).
2350 * @param object $data - all the data needed for an entry in the 'course' table
2351 * @param array $editoroptions course description editor options
2354 function update_course($data, $editoroptions = NULL) {
2357 $data->timemodified = time();
2359 $oldcourse = course_get_format($data->id)->get_course();
2360 $context = context_course::instance($oldcourse->id);
2362 if ($editoroptions) {
2363 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2365 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2366 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2369 // Check we don't have a duplicate shortname.
2370 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2371 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2372 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2376 // Check we don't have a duplicate idnumber.
2377 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2378 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2379 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2383 if (!isset($data->category) or empty($data->category)) {
2384 // prevent nulls and 0 in category field
2385 unset($data->category);
2387 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2389 if (!isset($data->visible)) {
2390 // data not from form, add missing visibility info
2391 $data->visible = $oldcourse->visible;
2394 if ($data->visible != $oldcourse->visible) {
2395 // reset the visibleold flag when manually hiding/unhiding course
2396 $data->visibleold = $data->visible;
2397 $changesincoursecat = true;
2400 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2401 if (empty($newcategory->visible)) {
2402 // make sure when moving into hidden category the course is hidden automatically
2408 // Update with the new data
2409 $DB->update_record('course', $data);
2410 // make sure the modinfo cache is reset
2411 rebuild_course_cache($data->id);
2413 // update course format options with full course data
2414 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2416 $course = $DB->get_record('course', array('id'=>$data->id));
2419 $newparent = context_coursecat::instance($course->category);
2420 $context->update_moved($newparent);
2423 if ($movecat || (isset($data->sortorder) && $oldcourse->sortorder != $data->sortorder)) {
2424 fix_course_sortorder();
2427 // purge appropriate caches in case fix_course_sortorder() did not change anything
2428 cache_helper::purge_by_event('changesincourse');
2429 if ($changesincoursecat) {
2430 cache_helper::purge_by_event('changesincoursecat');
2433 // Test for and remove blocks which aren't appropriate anymore
2434 blocks_remove_inappropriate($course);
2436 // Save any custom role names.
2437 save_local_role_names($course->id, $data);
2439 // update enrol settings
2440 enrol_course_updated(false, $course, $data);
2442 // Trigger a course updated event.
2443 $event = \core\event\course_updated::create(array(
2444 'objectid' => $course->id,
2445 'context' => $context,
2446 'other' => array('shortname' => $course->shortname,
2447 'fullname' => $course->fullname)
2449 $event->add_record_snapshot('course', $course);
2450 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2453 if ($oldcourse->format !== $course->format) {
2454 // Remove all options stored for the previous format
2455 // We assume that new course format migrated everything it needed watching trigger
2456 // 'course_updated' and in method format_XXX::update_course_format_options()
2457 $DB->delete_records('course_format_options',
2458 array('courseid' => $course->id, 'format' => $oldcourse->format));
2463 * Average number of participants
2466 function average_number_of_participants() {
2469 //count total of enrolments for visible course (except front page)
2470 $sql = 'SELECT COUNT(*) FROM (
2471 SELECT DISTINCT ue.userid, e.courseid
2472 FROM {user_enrolments} ue, {enrol} e, {course} c
2473 WHERE ue.enrolid = e.id
2474 AND e.courseid <> :siteid
2475 AND c.id = e.courseid
2476 AND c.visible = 1) total';
2477 $params = array('siteid' => $SITE->id);
2478 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2481 //count total of visible courses (minus front page)
2482 $coursetotal = $DB->count_records('course', array('visible' => 1));
2483 $coursetotal = $coursetotal - 1 ;
2485 //average of enrolment
2486 if (empty($coursetotal)) {
2487 $participantaverage = 0;
2489 $participantaverage = $enrolmenttotal / $coursetotal;
2492 return $participantaverage;
2496 * Average number of course modules
2499 function average_number_of_courses_modules() {
2502 //count total of visible course module (except front page)
2503 $sql = 'SELECT COUNT(*) FROM (
2504 SELECT cm.course, cm.module
2505 FROM {course} c, {course_modules} cm
2506 WHERE c.id = cm.course
2509 AND c.visible = 1) total';
2510 $params = array('siteid' => $SITE->id);
2511 $moduletotal = $DB->count_records_sql($sql, $params);
2514 //count total of visible courses (minus front page)
2515 $coursetotal = $DB->count_records('course', array('visible' => 1));
2516 $coursetotal = $coursetotal - 1 ;
2518 //average of course module
2519 if (empty($coursetotal)) {
2520 $coursemoduleaverage = 0;
2522 $coursemoduleaverage = $moduletotal / $coursetotal;
2525 return $coursemoduleaverage;
2529 * This class pertains to course requests and contains methods associated with
2530 * create, approving, and removing course requests.
2532 * Please note we do not allow embedded images here because there is no context
2533 * to store them with proper access control.
2535 * @copyright 2009 Sam Hemelryk
2536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2539 * @property-read int $id
2540 * @property-read string $fullname
2541 * @property-read string $shortname
2542 * @property-read string $summary
2543 * @property-read int $summaryformat
2544 * @property-read int $summarytrust
2545 * @property-read string $reason
2546 * @property-read int $requester
2548 class course_request {
2551 * This is the stdClass that stores the properties for the course request
2552 * and is externally accessed through the __get magic method
2555 protected $properties;
2558 * An array of options for the summary editor used by course request forms.
2559 * This is initially set by {@link summary_editor_options()}
2563 protected static $summaryeditoroptions;
2566 * Static function to prepare the summary editor for working with a course
2570 * @param null|stdClass $data Optional, an object containing the default values
2571 * for the form, these may be modified when preparing the
2572 * editor so this should be called before creating the form
2573 * @return stdClass An object that can be used to set the default values for
2576 public static function prepare($data=null) {
2577 if ($data === null) {
2578 $data = new stdClass;
2580 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2585 * Static function to create a new course request when passed an array of properties
2588 * This function also handles saving any files that may have been used in the editor
2591 * @param stdClass $data
2592 * @return course_request The newly created course request
2594 public static function create($data) {
2595 global $USER, $DB, $CFG;
2596 $data->requester = $USER->id;
2598 // Setting the default category if none set.
2599 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2600 $data->category = $CFG->defaultrequestcategory;
2603 // Summary is a required field so copy the text over
2604 $data->summary = $data->summary_editor['text'];
2605 $data->summaryformat = $data->summary_editor['format'];
2607 $data->id = $DB->insert_record('course_request', $data);
2609 // Create a new course_request object and return it
2610 $request = new course_request($data);
2612 // Notify the admin if required.
2613 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2616 $a->link = "$CFG->wwwroot/course/pending.php";
2617 $a->user = fullname($USER);
2618 $subject = get_string('courserequest');
2619 $message = get_string('courserequestnotifyemail', 'admin', $a);
2620 foreach ($users as $user) {
2621 $request->notify($user, $USER, 'courserequested', $subject, $message);
2629 * Returns an array of options to use with a summary editor
2631 * @uses course_request::$summaryeditoroptions
2632 * @return array An array of options to use with the editor
2634 public static function summary_editor_options() {
2636 if (self::$summaryeditoroptions === null) {
2637 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2639 return self::$summaryeditoroptions;
2643 * Loads the properties for this course request object. Id is required and if
2644 * only id is provided then we load the rest of the properties from the database
2646 * @param stdClass|int $properties Either an object containing properties
2647 * or the course_request id to load
2649 public function __construct($properties) {
2651 if (empty($properties->id)) {
2652 if (empty($properties)) {
2653 throw new coding_exception('You must provide a course request id when creating a course_request object');
2656 $properties = new stdClass;
2657 $properties->id = (int)$id;
2660 if (empty($properties->requester)) {
2661 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2662 print_error('unknowncourserequest');
2665 $this->properties = $properties;
2667 $this->properties->collision = null;
2671 * Returns the requested property
2673 * @param string $key
2676 public function __get($key) {
2677 return $this->properties->$key;
2681 * Override this to ensure empty($request->blah) calls return a reliable answer...
2683 * This is required because we define the __get method
2686 * @return bool True is it not empty, false otherwise
2688 public function __isset($key) {
2689 return (!empty($this->properties->$key));
2693 * Returns the user who requested this course
2695 * Uses a static var to cache the results and cut down the number of db queries
2697 * @staticvar array $requesters An array of cached users
2698 * @return stdClass The user who requested the course
2700 public function get_requester() {
2702 static $requesters= array();
2703 if (!array_key_exists($this->properties->requester, $requesters)) {
2704 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2706 return $requesters[$this->properties->requester];
2710 * Checks that the shortname used by the course does not conflict with any other
2711 * courses that exist
2713 * @param string|null $shortnamemark The string to append to the requests shortname
2714 * should a conflict be found
2715 * @return bool true is there is a conflict, false otherwise
2717 public function check_shortname_collision($shortnamemark = '[*]') {
2720 if ($this->properties->collision !== null) {
2721 return $this->properties->collision;
2724 if (empty($this->properties->shortname)) {
2725 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2726 $this->properties->collision = false;
2727 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2728 if (!empty($shortnamemark)) {
2729 $this->properties->shortname .= ' '.$shortnamemark;
2731 $this->properties->collision = true;
2733 $this->properties->collision = false;
2735 return $this->properties->collision;
2739 * Returns the category where this course request should be created
2741 * Note that we don't check here that user has a capability to view
2742 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2743 * 'moodle/course:changecategory'
2747 public function get_category() {
2749 require_once($CFG->libdir.'/coursecatlib.php');
2750 // If the category is not set, if the current user does not have the rights to change the category, or if the
2751 // category does not exist, we set the default category to the course to be approved.
2752 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2753 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2754 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2755 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2758 $category = coursecat::get_default();
2764 * This function approves the request turning it into a course
2766 * This function converts the course request into a course, at the same time
2767 * transferring any files used in the summary to the new course and then removing
2768 * the course request and the files associated with it.
2770 * @return int The id of the course that was created from this request
2772 public function approve() {
2773 global $CFG, $DB, $USER;
2775 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2777 $courseconfig = get_config('moodlecourse');
2779 // Transfer appropriate settings
2780 $data = clone($this->properties);
2782 unset($data->reason);
2783 unset($data->requester);
2786 $category = $this->get_category();
2787 $data->category = $category->id;
2788 // Set misc settings
2789 $data->requested = 1;
2791 // Apply course default settings
2792 $data->format = $courseconfig->format;
2793 $data->newsitems = $courseconfig->newsitems;
2794 $data->showgrades = $courseconfig->showgrades;
2795 $data->showreports = $courseconfig->showreports;
2796 $data->maxbytes = $courseconfig->maxbytes;
2797 $data->groupmode = $courseconfig->groupmode;
2798 $data->groupmodeforce = $courseconfig->groupmodeforce;
2799 $data->visible = $courseconfig->visible;
2800 $data->visibleold = $data->visible;
2801 $data->lang = $courseconfig->lang;
2803 $course = create_course($data);
2804 $context = context_course::instance($course->id, MUST_EXIST);
2806 // add enrol instances
2807 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2808 if ($manual = enrol_get_plugin('manual')) {
2809 $manual->add_default_instance($course);
2813 // enrol the requester as teacher if necessary
2814 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2815 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2820 $a = new stdClass();
2821 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2822 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2823 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
2829 * Reject a course request
2831 * This function rejects a course request, emailing the requesting user the
2832 * provided notice and then removing the request from the database
2834 * @param string $notice The message to display to the user
2836 public function reject($notice) {
2838 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2839 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2844 * Deletes the course request and any associated files
2846 public function delete() {
2848 $DB->delete_records('course_request', array('id' => $this->properties->id));
2852 * Send a message from one user to another using events_trigger
2854 * @param object $touser
2855 * @param object $fromuser
2856 * @param string $name
2857 * @param string $subject
2858 * @param string $message
2860 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
2861 $eventdata = new stdClass();
2862 $eventdata->component = 'moodle';
2863 $eventdata->name = $name;
2864 $eventdata->userfrom = $fromuser;
2865 $eventdata->userto = $touser;
2866 $eventdata->subject = $subject;
2867 $eventdata->fullmessage = $message;
2868 $eventdata->fullmessageformat = FORMAT_PLAIN;
2869 $eventdata->fullmessagehtml = '';
2870 $eventdata->smallmessage = '';
2871 $eventdata->notification = 1;
2872 message_send($eventdata);
2877 * Return a list of page types
2878 * @param string $pagetype current page type
2879 * @param context $parentcontext Block's parent context
2880 * @param context $currentcontext Current context of block
2881 * @return array array of page types
2883 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2884 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2885 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2886 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2887 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2889 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2890 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2891 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2893 // Otherwise consider it a page inside a course even if $currentcontext is null
2894 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2895 'course-*' => get_string('page-course-x', 'pagetype'),
2896 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2903 * Determine whether course ajax should be enabled for the specified course
2905 * @param stdClass $course The course to test against
2906 * @return boolean Whether course ajax is enabled or note
2908 function course_ajax_enabled($course) {
2909 global $CFG, $PAGE, $SITE;
2911 // Ajax must be enabled globally
2912 if (!$CFG->enableajax) {
2916 // The user must be editing for AJAX to be included
2917 if (!$PAGE->user_is_editing()) {
2921 // Check that the theme suports
2922 if (!$PAGE->theme->enablecourseajax) {
2926 // Check that the course format supports ajax functionality
2927 // The site 'format' doesn't have information on course format support
2928 if ($SITE->id !== $course->id) {
2929 $courseformatajaxsupport = course_format_ajax_support($course->format);
2930 if (!$courseformatajaxsupport->capable) {
2935 // All conditions have been met so course ajax should be enabled
2940 * Include the relevant javascript and language strings for the resource
2941 * toolbox YUI module
2943 * @param integer $id The ID of the course being applied to
2944 * @param array $usedmodules An array containing the names of the modules in use on the page
2945 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
2946 * @param stdClass $config An object containing configuration parameters for ajax modules including:
2947 * * resourceurl The URL to post changes to for resource changes
2948 * * sectionurl The URL to post changes to for section changes
2949 * * pageparams Additional parameters to pass through in the post
2952 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
2953 global $CFG, $PAGE, $SITE;
2955 // Ensure that ajax should be included
2956 if (!course_ajax_enabled($course)) {
2961 $config = new stdClass();
2964 // The URL to use for resource changes
2965 if (!isset($config->resourceurl)) {
2966 $config->resourceurl = '/course/rest.php';
2969 // The URL to use for section changes
2970 if (!isset($config->sectionurl)) {
2971 $config->sectionurl = '/course/rest.php';
2974 // Any additional parameters which need to be included on page submission
2975 if (!isset($config->pageparams)) {
2976 $config->pageparams = array();
2979 // Include toolboxes
2980 $PAGE->requires->yui_module('moodle-course-toolboxes',
2981 'M.course.init_resource_toolbox',
2983 'courseid' => $course->id,
2984 'ajaxurl' => $config->resourceurl,
2985 'config' => $config,
2988 $PAGE->requires->yui_module('moodle-course-toolboxes',
2989 'M.course.init_section_toolbox',
2991 'courseid' => $course->id,
2992 'format' => $course->format,
2993 'ajaxurl' => $config->sectionurl,
2994 'config' => $config,
2998 // Include course dragdrop
2999 if ($course->id != $SITE->id) {
3000 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3002 'courseid' => $course->id,
3003 'ajaxurl' => $config->sectionurl,
3004 'config' => $config,
3007 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3009 'courseid' => $course->id,
3010 'ajaxurl' => $config->resourceurl,
3011 'config' => $config,
3015 // Require various strings for the command toolbox
3016 $PAGE->requires->strings_for_js(array(
3019 'deletechecktypename',
3021 'edittitleinstructions',
3027 'clicktochangeinbrackets',
3034 'emptydragdropregion'
3037 // Include format-specific strings
3038 if ($course->id != $SITE->id) {
3039 $PAGE->requires->strings_for_js(array(
3042 ), 'format_' . $course->format);
3045 // For confirming resource deletion we need the name of the module in question
3046 foreach ($usedmodules as $module => $modname) {
3047 $PAGE->requires->string_for_js('pluginname', $module);
3050 // Load drag and drop upload AJAX.
3051 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3052 dndupload_add_to_course($course, $enabledmodules);
3058 * Returns the sorted list of available course formats, filtered by enabled if necessary
3060 * @param bool $enabledonly return only formats that are enabled
3061 * @return array array of sorted format names
3063 function get_sorted_course_formats($enabledonly = false) {
3065 $formats = core_component::get_plugin_list('format');
3067 if (!empty($CFG->format_plugins_sortorder)) {
3068 $order = explode(',', $CFG->format_plugins_sortorder);
3069 $order = array_merge(array_intersect($order, array_keys($formats)),
3070 array_diff(array_keys($formats), $order));
3072 $order = array_keys($formats);
3074 if (!$enabledonly) {
3077 $sortedformats = array();
3078 foreach ($order as $formatname) {
3079 if (!get_config('format_'.$formatname, 'disabled')) {
3080 $sortedformats[] = $formatname;
3083 return $sortedformats;
3087 * The URL to use for the specified course (with section)
3089 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3090 * @param int|stdClass $section Section object from database or just field course_sections.section
3091 * if omitted the course view page is returned
3092 * @param array $options options for view URL. At the moment core uses:
3093 * 'navigation' (bool) if true and section has no separate page, the function returns null
3094 * 'sr' (int) used by multipage formats to specify to which section to return
3095 * @return moodle_url The url of course
3097 function course_get_url($courseorid, $section = null, $options = array()) {
3098 return course_get_format($courseorid)->get_view_url($section, $options);
3105 * - capability checks and other checks
3106 * - create the module from the module info
3108 * @param object $module
3109 * @return object the created module info
3111 function create_module($moduleinfo) {
3114 require_once($CFG->dirroot . '/course/modlib.php');
3116 // Check manadatory attributs.
3117 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3118 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3119 $mandatoryfields[] = 'introeditor';
3121 foreach($mandatoryfields as $mandatoryfield) {
3122 if (!isset($moduleinfo->{$mandatoryfield})) {
3123 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3127 // Some additional checks (capability / existing instances).
3128 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3129 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3131 // Load module library.
3132 include_modulelib($module->name);
3135 $moduleinfo->module = $module->id;
3136 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3145 * - capability and other checks
3146 * - update the module
3148 * @param object $module
3149 * @return object the updated module info
3151 function update_module($moduleinfo) {
3154 require_once($CFG->dirroot . '/course/modlib.php');
3156 // Check the course module exists.
3157 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3159 // Check the course exists.
3160 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3162 // Some checks (capaibility / existing instances).
3163 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3165 // Load module library.
3166 include_modulelib($module->name);
3168 // Retrieve few information needed by update_moduleinfo.
3169 $moduleinfo->modulename = $cm->modname;
3170 if (!isset($moduleinfo->scale)) {
3171 $moduleinfo->scale = 0;
3173 $moduleinfo->type = 'mod';
3175 // Update the module.
3176 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3182 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3183 * Sorts by descending order of time.
3185 * @param stdClass $a First object
3186 * @param stdClass $b Second object
3187 * @return int 0,1,-1 representing the order
3189 function compare_activities_by_time_desc($a, $b) {
3190 // Make sure the activities actually have a timestamp property.
3191 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3194 // We treat instances without timestamp as if they have a timestamp of 0.
3195 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3198 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3201 if ($a->timestamp == $b->timestamp) {
3204 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3208 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3209 * Sorts by ascending order of time.
3211 * @param stdClass $a First object
3212 * @param stdClass $b Second object
3213 * @return int 0,1,-1 representing the order
3215 function compare_activities_by_time_asc($a, $b) {
3216 // Make sure the activities actually have a timestamp property.
3217 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3220 // We treat instances without timestamp as if they have a timestamp of 0.
3221 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3224 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3227 if ($a->timestamp == $b->timestamp) {
3230 return ($a->timestamp < $b->timestamp) ? -1 : 1;