2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of useful functions
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_course
25 defined('MOODLE_INTERNAL') || die;
27 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->dirroot.'/course/format/lib.php');
31 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
32 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
35 * Number of courses to display when summaries are included.
37 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41 // Max courses in log dropdown before switching to optional.
42 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
43 // Max users in log dropdown before switching to optional.
44 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
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 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
54 define('FRONTPAGECOURSELIMIT', 200); // TODO MDL-38832 remove.
55 define('EXCELROWS', 65535);
56 define('FIRSTUSEDEXCELROW', 3);
58 define('MOD_CLASS_ACTIVITY', 0);
59 define('MOD_CLASS_RESOURCE', 1);
61 function make_log_url($module, $url) {
64 if (strpos($url, 'report/') === 0) {
65 // there is only one report type, course reports are deprecated
76 if (strpos($url, '../') === 0) {
77 $url = ltrim($url, '.');
79 $url = "/course/$url";
84 $url = "/$module/$url";
97 $url = "/message/$url";
100 $url = "/notes/$url";
109 $url = "/grade/$url";
112 $url = "/mod/$module/$url";
116 //now let's sanitise urls - there might be some ugly nasties:-(
117 $parts = explode('?', $url);
118 $script = array_shift($parts);
119 if (strpos($script, 'http') === 0) {
120 $script = clean_param($script, PARAM_URL);
122 $script = clean_param($script, PARAM_PATH);
127 $query = implode('', $parts);
128 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
129 $parts = explode('&', $query);
130 $eq = urlencode('=');
131 foreach ($parts as $key=>$part) {
132 $part = urlencode(urldecode($part));
133 $part = str_replace($eq, '=', $part);
134 $parts[$key] = $part;
136 $query = '?'.implode('&', $parts);
139 return $script.$query;
143 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
144 $modname="", $modid=0, $modaction="", $groupid=0) {
147 // It is assumed that $date is the GMT time of midnight for that day,
148 // and so the next 86400 seconds worth of logs are printed.
150 /// Setup for group handling.
152 // TODO: I don't understand group/context/etc. enough to be able to do
153 // something interesting with it here
154 // What is the context of a remote course?
156 /// If the group mode is separate, and this user does not have editing privileges,
157 /// then only the user's group can be viewed.
158 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
159 // $groupid = get_current_group($course->id);
161 /// If this course doesn't have groups, no groupid can be specified.
162 //else if (!$course->groupmode) {
171 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
173 LEFT JOIN {user} u ON l.userid = u.id
177 $where .= "l.hostid = :hostid";
178 $params['hostid'] = $hostid;
180 // TODO: Is 1 really a magic number referring to the sitename?
181 if ($course != SITEID || $modid != 0) {
182 $where .= " AND l.course=:courseid";
183 $params['courseid'] = $course;
187 $where .= " AND l.module = :modname";
188 $params['modname'] = $modname;
191 if ('site_errors' === $modid) {
192 $where .= " AND ( l.action='error' OR l.action='infected' )";
194 //TODO: This assumes that modids are the same across sites... probably
196 $where .= " AND l.cmid = :modid";
197 $params['modid'] = $modid;
201 $firstletter = substr($modaction, 0, 1);
202 if ($firstletter == '-') {
203 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
204 $params['modaction'] = '%'.substr($modaction, 1).'%';
206 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
207 $params['modaction'] = '%'.$modaction.'%';
212 $where .= " AND l.userid = :user";
213 $params['user'] = $user;
217 $enddate = $date + 86400;
218 $where .= " AND l.time > :date AND l.time < :enddate";
219 $params['date'] = $date;
220 $params['enddate'] = $enddate;
224 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
225 if(!empty($result['totalcount'])) {
226 $where .= " ORDER BY $order";
227 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
229 $result['logs'] = array();
234 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
235 $modname="", $modid=0, $modaction="", $groupid=0) {
236 global $DB, $SESSION, $USER;
237 // It is assumed that $date is the GMT time of midnight for that day,
238 // and so the next 86400 seconds worth of logs are printed.
240 /// Setup for group handling.
242 /// If the group mode is separate, and this user does not have editing privileges,
243 /// then only the user's group can be viewed.
244 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
245 if (isset($SESSION->currentgroup[$course->id])) {
246 $groupid = $SESSION->currentgroup[$course->id];
248 $groupid = groups_get_all_groups($course->id, $USER->id);
249 if (is_array($groupid)) {
250 $groupid = array_shift(array_keys($groupid));
251 $SESSION->currentgroup[$course->id] = $groupid;
257 /// If this course doesn't have groups, no groupid can be specified.
258 else if (!$course->groupmode) {
265 if ($course->id != SITEID || $modid != 0) {
266 $joins[] = "l.course = :courseid";
267 $params['courseid'] = $course->id;
271 $joins[] = "l.module = :modname";
272 $params['modname'] = $modname;
275 if ('site_errors' === $modid) {
276 $joins[] = "( l.action='error' OR l.action='infected' )";
278 $joins[] = "l.cmid = :modid";
279 $params['modid'] = $modid;
283 $firstletter = substr($modaction, 0, 1);
284 if ($firstletter == '-') {
285 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
286 $params['modaction'] = '%'.substr($modaction, 1).'%';
288 $joins[] = $DB->sql_like('l.action', ':modaction', false);
289 $params['modaction'] = '%'.$modaction.'%';
294 /// Getting all members of a group.
295 if ($groupid and !$user) {
296 if ($gusers = groups_get_members($groupid)) {
297 $gusers = array_keys($gusers);
298 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
300 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
304 $joins[] = "l.userid = :userid";
305 $params['userid'] = $user;
309 $enddate = $date + 86400;
310 $joins[] = "l.time > :date AND l.time < :enddate";
311 $params['date'] = $date;
312 $params['enddate'] = $enddate;
315 $selector = implode(' AND ', $joins);
317 $totalcount = 0; // Initialise
319 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
320 $result['totalcount'] = $totalcount;
325 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
326 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
328 global $CFG, $DB, $OUTPUT;
330 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
331 $modname, $modid, $modaction, $groupid)) {
332 echo $OUTPUT->notification("No logs found!");
333 echo $OUTPUT->footer();
339 if ($course->id == SITEID) {
341 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
342 foreach ($ccc as $cc) {
343 $courses[$cc->id] = $cc->shortname;
347 $courses[$course->id] = $course->shortname;
350 $totalcount = $logs['totalcount'];
353 $tt = getdate(time());
354 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
356 $strftimedatetime = get_string("strftimedatetime");
358 echo "<div class=\"info\">\n";
359 print_string("displayingrecords", "", $totalcount);
362 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
364 $table = new html_table();
365 $table->classes = array('logtable','generaltable');
366 $table->align = array('right', 'left', 'left');
367 $table->head = array(
369 get_string('ip_address'),
370 get_string('fullnameuser'),
371 get_string('action'),
374 $table->data = array();
376 if ($course->id == SITEID) {
377 array_unshift($table->align, 'left');
378 array_unshift($table->head, get_string('course'));
381 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
382 if (empty($logs['logs'])) {
383 $logs['logs'] = array();
386 foreach ($logs['logs'] as $log) {
388 if (isset($ldcache[$log->module][$log->action])) {
389 $ld = $ldcache[$log->module][$log->action];
391 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
392 $ldcache[$log->module][$log->action] = $ld;
394 if ($ld && is_numeric($log->info)) {
395 // ugly hack to make sure fullname is shown correctly
396 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
397 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
399 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
404 $log->info = format_string($log->info);
406 // If $log->url has been trimmed short by the db size restriction
407 // code in add_to_log, keep a note so we don't add a link to a broken url
408 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
411 if ($course->id == SITEID) {
412 if (empty($log->course)) {
413 $row[] = get_string('site');
415 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
419 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
421 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
422 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
424 $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))));
426 $displayaction="$log->module $log->action";
428 $row[] = $displayaction;
430 $link = make_log_url($log->module,$log->url);
431 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
434 $table->data[] = $row;
437 echo html_writer::table($table);
438 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
442 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
443 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
445 global $CFG, $DB, $OUTPUT;
447 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
448 $modname, $modid, $modaction, $groupid)) {
449 echo $OUTPUT->notification("No logs found!");
450 echo $OUTPUT->footer();
454 if ($course->id == SITEID) {
456 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
457 foreach ($ccc as $cc) {
458 $courses[$cc->id] = $cc->shortname;
463 $totalcount = $logs['totalcount'];
466 $tt = getdate(time());
467 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
469 $strftimedatetime = get_string("strftimedatetime");
471 echo "<div class=\"info\">\n";
472 print_string("displayingrecords", "", $totalcount);
475 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
477 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
479 if ($course->id == SITEID) {
480 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
482 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
483 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
484 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
485 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
486 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
489 if (empty($logs['logs'])) {
495 foreach ($logs['logs'] as $log) {
497 $log->info = $log->coursename;
498 $row = ($row + 1) % 2;
500 if (isset($ldcache[$log->module][$log->action])) {
501 $ld = $ldcache[$log->module][$log->action];
503 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
504 $ldcache[$log->module][$log->action] = $ld;
506 if (0 && $ld && !empty($log->info)) {
507 // ugly hack to make sure fullname is shown correctly
508 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
509 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
511 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
516 $log->info = format_string($log->info);
518 echo '<tr class="r'.$row.'">';
519 if ($course->id == SITEID) {
520 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
521 echo "<td class=\"r$row c0\" >\n";
522 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
525 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
526 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
527 echo "<td class=\"r$row c2\" >\n";
528 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
529 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
531 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
532 echo "<td class=\"r$row c3\" >\n";
533 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
535 echo "<td class=\"r$row c4\">\n";
536 echo $log->action .': '.$log->module;
538 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
543 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
547 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
548 $modid, $modaction, $groupid) {
551 require_once($CFG->libdir . '/csvlib.class.php');
553 $csvexporter = new csv_export_writer('tab');
556 $header[] = get_string('course');
557 $header[] = get_string('time');
558 $header[] = get_string('ip_address');
559 $header[] = get_string('fullnameuser');
560 $header[] = get_string('action');
561 $header[] = get_string('info');
563 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
564 $modname, $modid, $modaction, $groupid)) {
570 if ($course->id == SITEID) {
572 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
573 foreach ($ccc as $cc) {
574 $courses[$cc->id] = $cc->shortname;
578 $courses[$course->id] = $course->shortname;
583 $tt = getdate(time());
584 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
586 $strftimedatetime = get_string("strftimedatetime");
588 $csvexporter->set_filename('logs', '.txt');
589 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
590 $csvexporter->add_data($title);
591 $csvexporter->add_data($header);
593 if (empty($logs['logs'])) {
597 foreach ($logs['logs'] as $log) {
598 if (isset($ldcache[$log->module][$log->action])) {
599 $ld = $ldcache[$log->module][$log->action];
601 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
602 $ldcache[$log->module][$log->action] = $ld;
604 if ($ld && is_numeric($log->info)) {
605 // ugly hack to make sure fullname is shown correctly
606 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
607 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
609 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
614 $log->info = format_string($log->info);
615 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
617 $coursecontext = context_course::instance($course->id);
618 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
619 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
620 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
621 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
622 $csvexporter->add_data($row);
624 $csvexporter->download_file();
629 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
630 $modid, $modaction, $groupid) {
634 require_once("$CFG->libdir/excellib.class.php");
636 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
637 $modname, $modid, $modaction, $groupid)) {
643 if ($course->id == SITEID) {
645 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
646 foreach ($ccc as $cc) {
647 $courses[$cc->id] = $cc->shortname;
651 $courses[$course->id] = $course->shortname;
656 $tt = getdate(time());
657 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
659 $strftimedatetime = get_string("strftimedatetime");
661 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
662 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
665 $workbook = new MoodleExcelWorkbook('-');
666 $workbook->send($filename);
668 $worksheet = array();
669 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
670 get_string('fullnameuser'), get_string('action'), get_string('info'));
672 // Creating worksheets
673 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
674 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
675 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
676 $worksheet[$wsnumber]->set_column(1, 1, 30);
677 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
678 userdate(time(), $strftimedatetime));
680 foreach ($headers as $item) {
681 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
686 if (empty($logs['logs'])) {
691 $formatDate =& $workbook->add_format();
692 $formatDate->set_num_format(get_string('log_excel_date_format'));
694 $row = FIRSTUSEDEXCELROW;
696 $myxls =& $worksheet[$wsnumber];
697 foreach ($logs['logs'] as $log) {
698 if (isset($ldcache[$log->module][$log->action])) {
699 $ld = $ldcache[$log->module][$log->action];
701 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
702 $ldcache[$log->module][$log->action] = $ld;
704 if ($ld && is_numeric($log->info)) {
705 // ugly hack to make sure fullname is shown correctly
706 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
707 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
709 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
714 $log->info = format_string($log->info);
715 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
718 if ($row > EXCELROWS) {
720 $myxls =& $worksheet[$wsnumber];
721 $row = FIRSTUSEDEXCELROW;
725 $coursecontext = context_course::instance($course->id);
727 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
728 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
729 $myxls->write($row, 2, $log->ip, '');
730 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
731 $myxls->write($row, 3, $fullname, '');
732 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
733 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
734 $myxls->write($row, 5, $log->info, '');
743 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
744 $modid, $modaction, $groupid) {
748 require_once("$CFG->libdir/odslib.class.php");
750 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
751 $modname, $modid, $modaction, $groupid)) {
757 if ($course->id == SITEID) {
759 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
760 foreach ($ccc as $cc) {
761 $courses[$cc->id] = $cc->shortname;
765 $courses[$course->id] = $course->shortname;
770 $tt = getdate(time());
771 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
773 $strftimedatetime = get_string("strftimedatetime");
775 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
776 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
779 $workbook = new MoodleODSWorkbook('-');
780 $workbook->send($filename);
782 $worksheet = array();
783 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
784 get_string('fullnameuser'), get_string('action'), get_string('info'));
786 // Creating worksheets
787 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
788 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
789 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
790 $worksheet[$wsnumber]->set_column(1, 1, 30);
791 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
792 userdate(time(), $strftimedatetime));
794 foreach ($headers as $item) {
795 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
800 if (empty($logs['logs'])) {
805 $formatDate =& $workbook->add_format();
806 $formatDate->set_num_format(get_string('log_excel_date_format'));
808 $row = FIRSTUSEDEXCELROW;
810 $myxls =& $worksheet[$wsnumber];
811 foreach ($logs['logs'] as $log) {
812 if (isset($ldcache[$log->module][$log->action])) {
813 $ld = $ldcache[$log->module][$log->action];
815 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
816 $ldcache[$log->module][$log->action] = $ld;
818 if ($ld && is_numeric($log->info)) {
819 // ugly hack to make sure fullname is shown correctly
820 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
821 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
823 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
828 $log->info = format_string($log->info);
829 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
832 if ($row > EXCELROWS) {
834 $myxls =& $worksheet[$wsnumber];
835 $row = FIRSTUSEDEXCELROW;
839 $coursecontext = context_course::instance($course->id);
841 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
842 $myxls->write_date($row, 1, $log->time);
843 $myxls->write_string($row, 2, $log->ip);
844 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
845 $myxls->write_string($row, 3, $fullname);
846 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
847 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
848 $myxls->write_string($row, 5, $log->info);
858 * Checks the integrity of the course data.
860 * In summary - compares course_sections.sequence and course_modules.section.
862 * More detailed, checks that:
863 * - course_sections.sequence contains each module id not more than once in the course
864 * - for each moduleid from course_sections.sequence the field course_modules.section
865 * refers to the same section id (this means course_sections.sequence is more
866 * important if they are different)
867 * - ($fullcheck only) each module in the course is present in one of
868 * course_sections.sequence
869 * - ($fullcheck only) removes non-existing course modules from section sequences
871 * If there are any mismatches, the changes are made and records are updated in DB.
873 * Course cache is NOT rebuilt if there are any errors!
875 * This function is used each time when course cache is being rebuilt with $fullcheck = false
876 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
878 * @param int $courseid id of the course
879 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
880 * the list of enabled course modules in the course. Retrieved from DB if not specified.
881 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
882 * @param array $sections records from course_sections table for this course.
883 * Retrieved from DB if not specified
884 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
885 * course modules from sequences. Only to be used in site maintenance mode when we are
886 * sure that another user is not in the middle of the process of moving/removing a module.
887 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
888 * @return array array of messages with found problems. Empty output means everything is ok
890 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
893 if ($sections === null) {
894 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
897 // Retrieve all records from course_modules regardless of module type visibility.
898 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
900 if ($rawmods === null) {
901 $rawmods = get_course_mods($courseid);
903 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
904 // If either of the arrays is empty, no modules are displayed anyway.
907 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
909 // First make sure that each module id appears in section sequences only once.
910 // If it appears in several section sequences the last section wins.
911 // If it appears twice in one section sequence, the first occurence wins.
912 $modsection = array();
913 foreach ($sections as $sectionid => $section) {
914 $sections[$sectionid]->newsequence = $section->sequence;
915 if (!empty($section->sequence)) {
916 $sequence = explode(",", $section->sequence);
917 $sequenceunique = array_unique($sequence);
918 if (count($sequenceunique) != count($sequence)) {
919 // Some course module id appears in this section sequence more than once.
920 ksort($sequenceunique); // Preserve initial order of modules.
921 $sequence = array_values($sequenceunique);
922 $sections[$sectionid]->newsequence = join(',', $sequence);
923 $messages[] = $debuggingprefix.'Sequence for course section ['.
924 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
926 foreach ($sequence as $cmid) {
927 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
928 // Some course module id appears to be in more than one section's sequences.
929 $wrongsectionid = $modsection[$cmid];
930 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
931 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
932 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
934 $modsection[$cmid] = $sectionid;
939 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
941 foreach ($rawmods as $cmid => $mod) {
942 if (!isset($modsection[$cmid])) {
943 // This is a module that is not mentioned in course_section.sequence at all.
944 // Add it to the section $mod->section or to the last available section.
945 if ($mod->section && isset($sections[$mod->section])) {
946 $modsection[$cmid] = $mod->section;
948 $firstsection = reset($sections);
949 $modsection[$cmid] = $firstsection->id;
951 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
952 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
953 $modsection[$cmid].']';
956 foreach ($modsection as $cmid => $sectionid) {
957 if (!isset($rawmods[$cmid])) {
958 // Section $sectionid refers to module id that does not exist.
959 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
960 $messages[] = $debuggingprefix.'Course module ['.$cmid.
961 '] does not exist but is present in the sequence of section ['.$sectionid.']';
966 // Update changed sections.
967 if (!$checkonly && !empty($messages)) {
968 foreach ($sections as $sectionid => $section) {
969 if ($section->newsequence !== $section->sequence) {
970 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
975 // Now make sure that all modules point to the correct sections.
976 foreach ($rawmods as $cmid => $mod) {
977 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
979 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
981 $messages[] = $debuggingprefix.'Course module ['.$cmid.
982 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
990 * For a given course, returns an array of course activity objects
991 * Each item in the array contains he following properties:
993 function get_array_of_activities($courseid) {
994 // cm - course module id
995 // mod - name of the module (eg forum)
996 // section - the number of the section (eg week or topic)
997 // name - the name of the instance
998 // visible - is the instance visible or not
999 // groupingid - grouping id
1000 // groupmembersonly - is this instance visible to group members only
1001 // extra - contains extra string to include in any link
1003 if(!empty($CFG->enableavailability)) {
1004 require_once($CFG->libdir.'/conditionlib.php');
1007 $course = $DB->get_record('course', array('id'=>$courseid));
1009 if (empty($course)) {
1010 throw new moodle_exception('courseidnotfound');
1015 $rawmods = get_course_mods($courseid);
1016 if (empty($rawmods)) {
1017 return $mod; // always return array
1020 if ($sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence')) {
1021 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
1022 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
1023 debugging(join('<br>', $errormessages));
1024 $rawmods = get_course_mods($courseid);
1025 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence');
1027 // Build array of activities.
1028 foreach ($sections as $section) {
1029 if (!empty($section->sequence)) {
1030 $sequence = explode(",", $section->sequence);
1031 foreach ($sequence as $seq) {
1032 if (empty($rawmods[$seq])) {
1035 $mod[$seq] = new stdClass();
1036 $mod[$seq]->id = $rawmods[$seq]->instance;
1037 $mod[$seq]->cm = $rawmods[$seq]->id;
1038 $mod[$seq]->mod = $rawmods[$seq]->modname;
1040 // Oh dear. Inconsistent names left here for backward compatibility.
1041 $mod[$seq]->section = $section->section;
1042 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1044 $mod[$seq]->module = $rawmods[$seq]->module;
1045 $mod[$seq]->added = $rawmods[$seq]->added;
1046 $mod[$seq]->score = $rawmods[$seq]->score;
1047 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1048 $mod[$seq]->visible = $rawmods[$seq]->visible;
1049 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1050 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1051 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1052 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1053 $mod[$seq]->indent = $rawmods[$seq]->indent;
1054 $mod[$seq]->completion = $rawmods[$seq]->completion;
1055 $mod[$seq]->extra = "";
1056 $mod[$seq]->completiongradeitemnumber =
1057 $rawmods[$seq]->completiongradeitemnumber;
1058 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1059 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1060 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1061 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1062 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1063 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1064 if (!empty($CFG->enableavailability)) {
1065 condition_info::fill_availability_conditions($rawmods[$seq]);
1066 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1067 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1068 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1071 $modname = $mod[$seq]->mod;
1072 $functionname = $modname."_get_coursemodule_info";
1074 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1078 include_once("$CFG->dirroot/mod/$modname/lib.php");
1080 if ($hasfunction = function_exists($functionname)) {
1081 if ($info = $functionname($rawmods[$seq])) {
1082 if (!empty($info->icon)) {
1083 $mod[$seq]->icon = $info->icon;
1085 if (!empty($info->iconcomponent)) {
1086 $mod[$seq]->iconcomponent = $info->iconcomponent;
1088 if (!empty($info->name)) {
1089 $mod[$seq]->name = $info->name;
1091 if ($info instanceof cached_cm_info) {
1092 // When using cached_cm_info you can include three new fields
1093 // that aren't available for legacy code
1094 if (!empty($info->content)) {
1095 $mod[$seq]->content = $info->content;
1097 if (!empty($info->extraclasses)) {
1098 $mod[$seq]->extraclasses = $info->extraclasses;
1100 if (!empty($info->iconurl)) {
1101 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
1102 $url = new moodle_url($info->iconurl);
1103 $mod[$seq]->iconurl = $url->out(false);
1105 if (!empty($info->onclick)) {
1106 $mod[$seq]->onclick = $info->onclick;
1108 if (!empty($info->customdata)) {
1109 $mod[$seq]->customdata = $info->customdata;
1112 // When using a stdclass, the (horrible) deprecated ->extra field
1113 // is available for BC
1114 if (!empty($info->extra)) {
1115 $mod[$seq]->extra = $info->extra;
1120 // When there is no modname_get_coursemodule_info function,
1121 // but showdescriptions is enabled, then we use the 'intro'
1122 // and 'introformat' fields in the module table
1123 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1124 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1125 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1126 // Set content from intro and introformat. Filters are disabled
1127 // because we filter it with format_text at display time
1128 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1129 $modvalues, $rawmods[$seq]->id, false);
1131 // To save making another query just below, put name in here
1132 $mod[$seq]->name = $modvalues->name;
1135 if (!isset($mod[$seq]->name)) {
1136 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1139 // Minimise the database size by unsetting default options when they are
1140 // 'empty'. This list corresponds to code in the cm_info constructor.
1141 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1142 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1143 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1144 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1145 'completionview', 'completionexpected', 'score', 'showdescription')
1147 if (property_exists($mod[$seq], $property) &&
1148 empty($mod[$seq]->{$property})) {
1149 unset($mod[$seq]->{$property});
1152 // Special case: this value is usually set to null, but may be 0
1153 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1154 is_null($mod[$seq]->completiongradeitemnumber)) {
1155 unset($mod[$seq]->completiongradeitemnumber);
1165 * Returns the localised human-readable names of all used modules
1167 * @param bool $plural if true returns the plural forms of the names
1168 * @return array where key is the module name (component name without 'mod_') and
1169 * the value is the human-readable string. Array sorted alphabetically by value
1171 function get_module_types_names($plural = false) {
1172 static $modnames = null;
1174 if ($modnames === null) {
1175 $modnames = array(0 => array(), 1 => array());
1176 if ($allmods = $DB->get_records("modules")) {
1177 foreach ($allmods as $mod) {
1178 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1179 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1180 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1183 core_collator::asort($modnames[0]);
1184 core_collator::asort($modnames[1]);
1187 return $modnames[(int)$plural];
1191 * Set highlighted section. Only one section can be highlighted at the time.
1193 * @param int $courseid course id
1194 * @param int $marker highlight section with this number, 0 means remove higlightin
1197 function course_set_marker($courseid, $marker) {
1199 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1200 format_base::reset_course_cache($courseid);
1204 * For a given course section, marks it visible or hidden,
1205 * and does the same for every activity in that section
1207 * @param int $courseid course id
1208 * @param int $sectionnumber The section number to adjust
1209 * @param int $visibility The new visibility
1210 * @return array A list of resources which were hidden in the section
1212 function set_section_visible($courseid, $sectionnumber, $visibility) {
1215 $resourcestotoggle = array();
1216 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1217 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1218 if (!empty($section->sequence)) {
1219 $modules = explode(",", $section->sequence);
1220 foreach ($modules as $moduleid) {
1221 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1223 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1224 set_coursemodule_visible($moduleid, $cm->visibleold);
1226 // We hide the section, so we hide the module but we store the original state in visibleold.
1227 set_coursemodule_visible($moduleid, 0);
1228 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1233 rebuild_course_cache($courseid, true);
1235 // Determine which modules are visible for AJAX update
1236 if (!empty($modules)) {
1237 list($insql, $params) = $DB->get_in_or_equal($modules);
1238 $select = 'id ' . $insql . ' AND visible = ?';
1239 array_push($params, $visibility);
1241 $select .= ' AND visibleold = 1';
1243 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1246 return $resourcestotoggle;
1250 * Retrieve all metadata for the requested modules
1252 * @param object $course The Course
1253 * @param array $modnames An array containing the list of modules and their
1255 * @param int $sectionreturn The section to return to
1256 * @return array A list of stdClass objects containing metadata about each
1259 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1260 global $CFG, $OUTPUT;
1262 // get_module_metadata will be called once per section on the page and courses may show
1263 // different modules to one another
1264 static $modlist = array();
1265 if (!isset($modlist[$course->id])) {
1266 $modlist[$course->id] = array();
1270 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1271 if ($sectionreturn !== null) {
1272 $urlbase->param('sr', $sectionreturn);
1274 foreach($modnames as $modname => $modnamestr) {
1275 if (!course_allowed_module($course, $modname)) {
1278 if (isset($modlist[$course->id][$modname])) {
1279 // This module is already cached
1280 $return[$modname] = $modlist[$course->id][$modname];
1284 // Include the module lib
1285 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1286 if (!file_exists($libfile)) {
1289 include_once($libfile);
1291 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1292 $gettypesfunc = $modname.'_get_types';
1293 $types = MOD_SUBTYPE_NO_CHILDREN;
1294 if (function_exists($gettypesfunc)) {
1295 $types = $gettypesfunc();
1297 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
1298 if (is_array($types) && count($types) > 0) {
1299 $group = new stdClass();
1300 $group->name = $modname;
1301 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1302 foreach($types as $type) {
1303 if ($type->typestr === '--') {
1306 if (strpos($type->typestr, '--') === 0) {
1307 $group->title = str_replace('--', '', $type->typestr);
1310 // Set the Sub Type metadata
1311 $subtype = new stdClass();
1312 $subtype->title = $type->typestr;
1313 $subtype->type = str_replace('&', '&', $type->type);
1314 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1315 $subtype->archetype = $type->modclass;
1317 // The group archetype should match the subtype archetypes and all subtypes
1318 // should have the same archetype
1319 $group->archetype = $subtype->archetype;
1321 if (!empty($type->help)) {
1322 $subtype->help = $type->help;
1323 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1324 $subtype->help = get_string('help' . $subtype->name, $modname);
1326 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1327 $group->types[] = $subtype;
1329 $modlist[$course->id][$modname] = $group;
1332 $module = new stdClass();
1333 $module->title = $modnamestr;
1334 $module->name = $modname;
1335 $module->link = new moodle_url($urlbase, array('add' => $modname));
1336 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1337 $sm = get_string_manager();
1338 if ($sm->string_exists('modulename_help', $modname)) {
1339 $module->help = get_string('modulename_help', $modname);
1340 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1341 $link = get_string('modulename_link', $modname);
1342 $linktext = get_string('morehelp');
1343 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1346 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1347 $modlist[$course->id][$modname] = $module;
1349 if (isset($modlist[$course->id][$modname])) {
1350 $return[$modname] = $modlist[$course->id][$modname];
1352 debugging("Invalid module metadata configuration for {$modname}");
1360 * Return the course category context for the category with id $categoryid, except
1361 * that if $categoryid is 0, return the system context.
1363 * @param integer $categoryid a category id or 0.
1364 * @return context the corresponding context
1366 function get_category_or_system_context($categoryid) {
1368 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1370 return context_system::instance();
1375 * Returns full course categories trees to be used in html_writer::select()
1377 * Calls {@link coursecat::make_categories_list()} to build the tree and
1378 * adds whitespace to denote nesting
1380 * @return array array mapping coursecat id to the display name
1382 function make_categories_options() {
1384 require_once($CFG->libdir. '/coursecatlib.php');
1385 $cats = coursecat::make_categories_list('', 0, ' / ');
1386 foreach ($cats as $key => $value) {
1387 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
1388 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
1394 * Print the buttons relating to course requests.
1396 * @param object $context current page context.
1398 function print_course_request_buttons($context) {
1399 global $CFG, $DB, $OUTPUT;
1400 if (empty($CFG->enablecourserequests)) {
1403 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1404 /// Print a button to request a new course
1405 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1407 /// Print a button to manage pending requests
1408 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1409 $disabled = !$DB->record_exists('course_request', array());
1410 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1415 * Does the user have permission to edit things in this category?
1417 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1418 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1420 function can_edit_in_category($categoryid = 0) {
1421 $context = get_category_or_system_context($categoryid);
1422 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1425 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1427 function add_course_module($mod) {
1430 $mod->added = time();
1433 $cmid = $DB->insert_record("course_modules", $mod);
1434 rebuild_course_cache($mod->course, true);
1439 * Creates missing course section(s) and rebuilds course cache
1441 * @param int|stdClass $courseorid course id or course object
1442 * @param int|array $sections list of relative section numbers to create
1443 * @return bool if there were any sections created
1445 function course_create_sections_if_missing($courseorid, $sections) {
1447 if (!is_array($sections)) {
1448 $sections = array($sections);
1450 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1451 if (is_object($courseorid)) {
1452 $courseorid = $courseorid->id;
1454 $coursechanged = false;
1455 foreach ($sections as $sectionnum) {
1456 if (!in_array($sectionnum, $existing)) {
1457 $cw = new stdClass();
1458 $cw->course = $courseorid;
1459 $cw->section = $sectionnum;
1461 $cw->summaryformat = FORMAT_HTML;
1463 $id = $DB->insert_record("course_sections", $cw);
1464 $coursechanged = true;
1467 if ($coursechanged) {
1468 rebuild_course_cache($courseorid, true);
1470 return $coursechanged;
1474 * Adds an existing module to the section
1476 * Updates both tables {course_sections} and {course_modules}
1478 * Note: This function does not use modinfo PROVIDED that the section you are
1479 * adding the module to already exists. If the section does not exist, it will
1480 * build modinfo if necessary and create the section.
1482 * @param int|stdClass $courseorid course id or course object
1483 * @param int $cmid id of the module already existing in course_modules table
1484 * @param int $sectionnum relative number of the section (field course_sections.section)
1485 * If section does not exist it will be created
1486 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1487 * before which the module needs to be included. Null for inserting in the
1488 * end of the section
1489 * @return int The course_sections ID where the module is inserted
1491 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1492 global $DB, $COURSE;
1493 if (is_object($beforemod)) {
1494 $beforemod = $beforemod->id;
1496 if (is_object($courseorid)) {
1497 $courseid = $courseorid->id;
1499 $courseid = $courseorid;
1501 // Do not try to use modinfo here, there is no guarantee it is valid!
1502 $section = $DB->get_record('course_sections',
1503 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
1505 // This function call requires modinfo.
1506 course_create_sections_if_missing($courseorid, $sectionnum);
1507 $section = $DB->get_record('course_sections',
1508 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
1511 $modarray = explode(",", trim($section->sequence));
1512 if (empty($section->sequence)) {
1513 $newsequence = "$cmid";
1514 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1515 $insertarray = array($cmid, $beforemod);
1516 array_splice($modarray, $key[0], 1, $insertarray);
1517 $newsequence = implode(",", $modarray);
1519 $newsequence = "$section->sequence,$cmid";
1521 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1522 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1523 if (is_object($courseorid)) {
1524 rebuild_course_cache($courseorid->id, true);
1526 rebuild_course_cache($courseorid, true);
1528 return $section->id; // Return course_sections ID that was used.
1531 function set_coursemodule_groupmode($id, $groupmode) {
1533 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1534 if ($cm->groupmode != $groupmode) {
1535 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1536 rebuild_course_cache($cm->course, true);
1538 return ($cm->groupmode != $groupmode);
1541 function set_coursemodule_idnumber($id, $idnumber) {
1543 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1544 if ($cm->idnumber != $idnumber) {
1545 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1546 rebuild_course_cache($cm->course, true);
1548 return ($cm->idnumber != $idnumber);
1552 * Set the visibility of a module and inherent properties.
1554 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1555 * has been moved to {@link set_section_visible()} which was the only place from which
1556 * the parameter was used.
1558 * @param int $id of the module
1559 * @param int $visible state of the module
1560 * @return bool false when the module was not found, true otherwise
1562 function set_coursemodule_visible($id, $visible) {
1564 require_once($CFG->libdir.'/gradelib.php');
1565 require_once($CFG->dirroot.'/calendar/lib.php');
1567 // Trigger developer's attention when using the previously removed argument.
1568 if (func_num_args() > 2) {
1569 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1570 has been removed.', DEBUG_DEVELOPER);
1573 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1577 // Create events and propagate visibility to associated grade items if the value has changed.
1578 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1579 if ($cm->visible == $visible) {
1583 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1586 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1587 foreach($events as $event) {
1589 $event = new calendar_event($event);
1590 $event->toggle_visibility(true);
1592 $event = new calendar_event($event);
1593 $event->toggle_visibility(false);
1598 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1599 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1600 $cminfo = new stdClass();
1602 $cminfo->visible = $visible;
1603 $cminfo->visibleold = $visible;
1604 $DB->update_record('course_modules', $cminfo);
1606 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1607 // Note that this must be done after updating the row in course_modules, in case
1608 // the modules grade_item_update function needs to access $cm->visible.
1609 if (plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1610 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1611 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1612 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1614 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1616 foreach ($grade_items as $grade_item) {
1617 $grade_item->set_hidden(!$visible);
1622 rebuild_course_cache($cm->course, true);
1627 * This function will handles the whole deletion process of a module. This includes calling
1628 * the modules delete_instance function, deleting files, events, grades, conditional data,
1629 * the data in the course_module and course_sections table and adding a module deletion
1632 * @param int $cmid the course module id
1635 function course_delete_module($cmid) {
1638 require_once($CFG->libdir.'/gradelib.php');
1639 require_once($CFG->dirroot.'/blog/lib.php');
1640 require_once($CFG->dirroot.'/calendar/lib.php');
1642 // Get the course module.
1643 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1647 // Get the module context.
1648 $modcontext = context_module::instance($cm->id);
1650 // Get the course module name.
1651 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1653 // Get the file location of the delete_instance function for this module.
1654 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1656 // Include the file required to call the delete_instance function for this module.
1657 if (file_exists($modlib)) {
1658 require_once($modlib);
1660 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1661 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1664 $deleteinstancefunction = $modulename . '_delete_instance';
1666 // Ensure the delete_instance function exists for this module.
1667 if (!function_exists($deleteinstancefunction)) {
1668 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1669 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1672 // Call the delete_instance function, if it returns false throw an exception.
1673 if (!$deleteinstancefunction($cm->instance)) {
1674 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1675 "Cannot delete the module $modulename (instance).");
1678 // Remove all module files in case modules forget to do that.
1679 $fs = get_file_storage();
1680 $fs->delete_area_files($modcontext->id);
1682 // Delete events from calendar.
1683 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1684 foreach($events as $event) {
1685 $calendarevent = calendar_event::load($event->id);
1686 $calendarevent->delete();
1690 // Delete grade items, outcome items and grades attached to modules.
1691 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1692 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1693 foreach ($grade_items as $grade_item) {
1694 $grade_item->delete('moddelete');
1698 // Delete completion and availability data; it is better to do this even if the
1699 // features are not turned on, in case they were turned on previously (these will be
1700 // very quick on an empty table).
1701 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1702 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
1703 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
1704 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1705 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1707 // Delete the context.
1708 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1710 // Delete the module from the course_modules table.
1711 $DB->delete_records('course_modules', array('id' => $cm->id));
1713 // Delete module from that section.
1714 if (!delete_mod_from_section($cm->id, $cm->section)) {
1715 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1716 "Cannot delete the module $modulename (instance) from section.");
1719 // Trigger event for course module delete action.
1720 $event = \core\event\course_module_deleted::create(array(
1721 'courseid' => $cm->course,
1722 'context' => $modcontext,
1723 'objectid' => $cm->id,
1725 'modulename' => $modulename,
1726 'instanceid' => $cm->instance,
1729 $event->add_record_snapshot('course_modules', $cm);
1731 rebuild_course_cache($cm->course, true);
1734 function delete_mod_from_section($modid, $sectionid) {
1737 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1739 $modarray = explode(",", $section->sequence);
1741 if ($key = array_keys ($modarray, $modid)) {
1742 array_splice($modarray, $key[0], 1);
1743 $newsequence = implode(",", $modarray);
1744 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1745 rebuild_course_cache($section->course, true);
1756 * Moves a section within a course, from a position to another.
1757 * Be very careful: $section and $destination refer to section number,
1760 * @param object $course
1761 * @param int $section Section number (not id!!!)
1762 * @param int $destination
1763 * @return boolean Result
1765 function move_section_to($course, $section, $destination) {
1766 /// Moves a whole course section up and down within the course
1769 if (!$destination && $destination != 0) {
1773 // compartibility with course formats using field 'numsections'
1774 $courseformatoptions = course_get_format($course)->get_format_options();
1775 if ((array_key_exists('numsections', $courseformatoptions) &&
1776 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1780 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1781 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1782 'section ASC, id ASC', 'id, section')) {
1786 $movedsections = reorder_sections($sections, $section, $destination);
1788 // Update all sections. Do this in 2 steps to avoid breaking database
1789 // uniqueness constraint
1790 $transaction = $DB->start_delegated_transaction();
1791 foreach ($movedsections as $id => $position) {
1792 if ($sections[$id] !== $position) {
1793 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1796 foreach ($movedsections as $id => $position) {
1797 if ($sections[$id] !== $position) {
1798 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1802 // If we move the highlighted section itself, then just highlight the destination.
1803 // Adjust the higlighted section location if we move something over it either direction.
1804 if ($section == $course->marker) {
1805 course_set_marker($course->id, $destination);
1806 } elseif ($section > $course->marker && $course->marker >= $destination) {
1807 course_set_marker($course->id, $course->marker+1);
1808 } elseif ($section < $course->marker && $course->marker <= $destination) {
1809 course_set_marker($course->id, $course->marker-1);
1812 $transaction->allow_commit();
1813 rebuild_course_cache($course->id, true);
1818 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1819 * an original position number and a target position number, rebuilds the array so that the
1820 * move is made without any duplication of section positions.
1821 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1822 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1824 * @param array $sections
1825 * @param int $origin_position
1826 * @param int $target_position
1829 function reorder_sections($sections, $origin_position, $target_position) {
1830 if (!is_array($sections)) {
1834 // We can't move section position 0
1835 if ($origin_position < 1) {
1836 echo "We can't move section position 0";
1840 // Locate origin section in sections array
1841 if (!$origin_key = array_search($origin_position, $sections)) {
1842 echo "searched position not in sections array";
1843 return false; // searched position not in sections array
1846 // Extract origin section
1847 $origin_section = $sections[$origin_key];
1848 unset($sections[$origin_key]);
1850 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1852 $append_array = array();
1853 foreach ($sections as $id => $position) {
1855 $append_array[$id] = $position;
1856 unset($sections[$id]);
1858 if ($position == $target_position) {
1859 if ($target_position < $origin_position) {
1860 $append_array[$id] = $position;
1861 unset($sections[$id]);
1867 // Append moved section
1868 $sections[$origin_key] = $origin_section;
1870 // Append rest of array (if applicable)
1871 if (!empty($append_array)) {
1872 foreach ($append_array as $id => $position) {
1873 $sections[$id] = $position;
1877 // Renumber positions
1879 foreach ($sections as $id => $p) {
1880 $sections[$id] = $position;
1889 * Move the module object $mod to the specified $section
1890 * If $beforemod exists then that is the module
1891 * before which $modid should be inserted
1893 * @param stdClass|cm_info $mod
1894 * @param stdClass|section_info $section
1895 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1896 * before which the module needs to be included. Null for inserting in the
1897 * end of the section
1898 * @return int new value for module visibility (0 or 1)
1900 function moveto_module($mod, $section, $beforemod=NULL) {
1901 global $OUTPUT, $DB;
1903 // Current module visibility state - return value of this function.
1904 $modvisible = $mod->visible;
1906 // Remove original module from original section.
1907 if (! delete_mod_from_section($mod->id, $mod->section)) {
1908 echo $OUTPUT->notification("Could not delete module from existing section");
1911 // If moving to a hidden section then hide module.
1912 if ($mod->section != $section->id) {
1913 if (!$section->visible && $mod->visible) {
1914 // Module was visible but must become hidden after moving to hidden section.
1916 set_coursemodule_visible($mod->id, 0);
1917 // Set visibleold to 1 so module will be visible when section is made visible.
1918 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1920 if ($section->visible && !$mod->visible) {
1921 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1922 set_coursemodule_visible($mod->id, $mod->visibleold);
1923 $modvisible = $mod->visibleold;
1927 // Add the module into the new section.
1928 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1933 * Returns the list of all editing actions that current user can perform on the module
1935 * @param cm_info $mod The module to produce editing buttons for
1936 * @param int $indent The current indenting (default -1 means no move left-right actions)
1937 * @param int $sr The section to link back to (used for creating the links)
1938 * @return array array of action_link or pix_icon objects
1940 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1941 global $COURSE, $SITE;
1945 $coursecontext = context_course::instance($mod->course);
1946 $modcontext = context_module::instance($mod->id);
1948 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1949 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1951 // No permission to edit anything.
1952 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1956 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1959 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1960 'editsettings', 'duplicate', 'hide', 'show'), 'moodle');
1961 $str->assign = get_string('assignroles', 'role');
1962 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1963 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1964 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1967 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1970 $baseurl->param('sr', $sr);
1975 if ($hasmanageactivities) {
1976 $actions['update'] = new action_menu_link_secondary(
1977 new moodle_url($baseurl, array('update' => $mod->id)),
1978 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1980 array('class' => 'editing_update', 'data-action' => 'update')
1985 if ($hasmanageactivities) {
1986 $indentlimits = new stdClass();
1987 $indentlimits->min = 0;
1988 $indentlimits->max = 16;
1989 if (right_to_left()) { // Exchange arrows on RTL
1990 $rightarrow = 't/left';
1991 $leftarrow = 't/right';
1993 $rightarrow = 't/right';
1994 $leftarrow = 't/left';
1997 if ($indent >= $indentlimits->max) {
1998 $enabledclass = 'hidden';
2002 $actions['moveright'] = new action_menu_link_secondary(
2003 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
2004 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2006 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright', 'data-keepopen' => true)
2009 if ($indent <= $indentlimits->min) {
2010 $enabledclass = 'hidden';
2014 $actions['moveleft'] = new action_menu_link_secondary(
2015 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
2016 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2018 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft', 'data-keepopen' => true)
2024 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2025 if ($mod->visible) {
2026 $actions['hide'] = new action_menu_link_secondary(
2027 new moodle_url($baseurl, array('hide' => $mod->id)),
2028 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2030 array('class' => 'editing_hide', 'data-action' => 'hide')
2033 $actions['show'] = new action_menu_link_secondary(
2034 new moodle_url($baseurl, array('show' => $mod->id)),
2035 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2037 array('class' => 'editing_show', 'data-action' => 'show')
2042 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2043 // Note that restoring on front page is never allowed.
2044 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
2045 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
2046 $actions['duplicate'] = new action_menu_link_secondary(
2047 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2048 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2050 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sr' => $sr)
2055 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2056 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2057 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2058 $nextgroupmode = VISIBLEGROUPS;
2059 $grouptitle = $str->groupsseparate;
2060 $actionname = 'groupsseparate';
2061 $groupimage = 'i/groups';
2062 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2063 $nextgroupmode = NOGROUPS;
2064 $grouptitle = $str->groupsvisible;
2065 $actionname = 'groupsvisible';
2066 $groupimage = 'i/groupv';
2068 $nextgroupmode = SEPARATEGROUPS;
2069 $grouptitle = $str->groupsnone;
2070 $actionname = 'groupsnone';
2071 $groupimage = 'i/groupn';
2074 $actions[$actionname] = new action_menu_link_primary(
2075 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2076 new pix_icon($groupimage, null, 'moodle', array('class' => 'iconsmall')),
2078 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode, 'aria-live' => 'assertive')
2081 $actions['nogroupsupport'] = new action_menu_filler();
2086 if (has_capability('moodle/role:assign', $modcontext)){
2087 $actions['assign'] = new action_menu_link_secondary(
2088 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2089 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2091 array('class' => 'editing_assign', 'data-action' => 'assignroles')
2096 if ($hasmanageactivities) {
2097 $actions['delete'] = new action_menu_link_secondary(
2098 new moodle_url($baseurl, array('delete' => $mod->id)),
2099 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2101 array('class' => 'editing_delete', 'data-action' => 'delete')
2109 * Returns the rename action.
2111 * @param cm_info $mod The module to produce editing buttons for
2112 * @param int $sr The section to link back to (used for creating the links)
2113 * @return The markup for the rename action, or an empty string if not available.
2115 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
2116 global $COURSE, $OUTPUT;
2121 $modcontext = context_module::instance($mod->id);
2122 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2125 $str = get_strings(array('edittitle'));
2128 if (!isset($baseurl)) {
2129 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2133 $baseurl->param('sr', $sr);
2137 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
2138 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
2139 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2140 return html_writer::span(
2142 new moodle_url($baseurl, array('update' => $mod->id)),
2143 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2145 'class' => 'editing_title',
2146 'data-action' => 'edittitle',
2147 'title' => $str->edittitle,
2156 * Returns the move action.
2158 * @param cm_info $mod The module to produce a move button for
2159 * @param int $sr The section to link back to (used for creating the links)
2160 * @return The markup for the move action, or an empty string if not available.
2162 function course_get_cm_move(cm_info $mod, $sr = null) {
2168 $modcontext = context_module::instance($mod->id);
2169 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2172 $str = get_strings(array('move'));
2175 if (!isset($baseurl)) {
2176 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2179 $baseurl->param('sr', $sr);
2183 if ($hasmanageactivities) {
2184 $pixicon = 'i/dragdrop';
2186 if (!course_ajax_enabled($mod->get_course())) {
2187 // Override for course frontpage until we get drag/drop working there.
2188 $pixicon = 't/move';
2191 return html_writer::link(
2192 new moodle_url($baseurl, array('copy' => $mod->id)),
2193 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2194 array('class' => 'editing_move', 'data-action' => 'move')
2201 * given a course object with shortname & fullname, this function will
2202 * truncate the the number of chars allowed and add ... if it was too long
2204 function course_format_name ($course,$max=100) {
2206 $context = context_course::instance($course->id);
2207 $shortname = format_string($course->shortname, true, array('context' => $context));
2208 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2209 $str = $shortname.': '. $fullname;
2210 if (core_text::strlen($str) <= $max) {
2214 return core_text::substr($str,0,$max-3).'...';
2219 * Is the user allowed to add this type of module to this course?
2220 * @param object $course the course settings. Only $course->id is used.
2221 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2222 * @return bool whether the current user is allowed to add this type of module to this course.
2224 function course_allowed_module($course, $modname) {
2225 if (is_numeric($modname)) {
2226 throw new coding_exception('Function course_allowed_module no longer
2227 supports numeric module ids. Please update your code to pass the module name.');
2230 $capability = 'mod/' . $modname . ':addinstance';
2231 if (!get_capability_info($capability)) {
2232 // Debug warning that the capability does not exist, but no more than once per page.
2233 static $warned = array();
2234 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2235 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2236 debugging('The module ' . $modname . ' does not define the standard capability ' .
2237 $capability , DEBUG_DEVELOPER);
2238 $warned[$modname] = 1;
2241 // If the capability does not exist, the module can always be added.
2245 $coursecontext = context_course::instance($course->id);
2246 return has_capability($capability, $coursecontext);
2250 * Efficiently moves many courses around while maintaining
2251 * sortorder in order.
2253 * @param array $courseids is an array of course ids
2254 * @param int $categoryid
2255 * @return bool success
2257 function move_courses($courseids, $categoryid) {
2260 if (empty($courseids)) {
2265 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2269 $courseids = array_reverse($courseids);
2270 $newparent = context_coursecat::instance($category->id);
2273 list($where, $params) = $DB->get_in_or_equal($courseids);
2274 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2275 foreach ($dbcourses as $dbcourse) {
2276 $course = new stdClass();
2277 $course->id = $dbcourse->id;
2278 $course->category = $category->id;
2279 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2280 if ($category->visible == 0) {
2281 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2282 // to previous state if somebody unhides the category.
2283 $course->visible = 0;
2286 $DB->update_record('course', $course);
2288 // Update context, so it can be passed to event.
2289 $context = context_course::instance($course->id);
2290 $context->update_moved($newparent);
2292 // Trigger a course updated event.
2293 $event = \core\event\course_updated::create(array(
2294 'objectid' => $course->id,
2295 'context' => context_course::instance($course->id),
2296 'other' => array('shortname' => $dbcourse->shortname,
2297 'fullname' => $dbcourse->fullname)
2299 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2302 fix_course_sortorder();
2303 cache_helper::purge_by_event('changesincourse');
2309 * Returns the display name of the given section that the course prefers
2311 * Implementation of this function is provided by course format
2312 * @see format_base::get_section_name()
2314 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2315 * @param int|stdClass $section Section object from database or just field course_sections.section
2316 * @return string Display name that the course format prefers, e.g. "Week 2"
2318 function get_section_name($courseorid, $section) {
2319 return course_get_format($courseorid)->get_section_name($section);
2323 * Tells if current course format uses sections
2325 * @param string $format Course format ID e.g. 'weeks' $course->format
2328 function course_format_uses_sections($format) {
2329 $course = new stdClass();
2330 $course->format = $format;
2331 return course_get_format($course)->uses_sections();
2335 * Returns the information about the ajax support in the given source format
2337 * The returned object's property (boolean)capable indicates that
2338 * the course format supports Moodle course ajax features.
2339 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2341 * @param string $format
2344 function course_format_ajax_support($format) {
2345 $course = new stdClass();
2346 $course->format = $format;
2347 return course_get_format($course)->supports_ajax();
2351 * Can the current user delete this course?
2352 * Course creators have exception,
2353 * 1 day after the creation they can sill delete the course.
2354 * @param int $courseid
2357 function can_delete_course($courseid) {
2360 $context = context_course::instance($courseid);
2362 if (has_capability('moodle/course:delete', $context)) {
2366 // hack: now try to find out if creator created this course recently (1 day)
2367 if (!has_capability('moodle/course:create', $context)) {
2371 $since = time() - 60*60*24;
2373 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2374 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2376 return $DB->record_exists_select('log', $select, $params);
2380 * Save the Your name for 'Some role' strings.
2382 * @param integer $courseid the id of this course.
2383 * @param array $data the data that came from the course settings form.
2385 function save_local_role_names($courseid, $data) {
2387 $context = context_course::instance($courseid);
2389 foreach ($data as $fieldname => $value) {
2390 if (strpos($fieldname, 'role_') !== 0) {
2393 list($ignored, $roleid) = explode('_', $fieldname);
2395 // make up our mind whether we want to delete, update or insert
2397 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2399 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2400 $rolename->name = $value;
2401 $DB->update_record('role_names', $rolename);
2404 $rolename = new stdClass;
2405 $rolename->contextid = $context->id;
2406 $rolename->roleid = $roleid;
2407 $rolename->name = $value;
2408 $DB->insert_record('role_names', $rolename);
2414 * Returns options to use in course overviewfiles filemanager
2416 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2417 * may be empty if course does not exist yet (course create form)
2418 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2419 * or null if overviewfiles are disabled
2421 function course_overviewfiles_options($course) {
2423 if (empty($CFG->courseoverviewfileslimit)) {
2426 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2427 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2428 $accepted_types = '*';
2430 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2431 // Make sure extensions are prefixed with dot unless they are valid typegroups
2432 foreach ($accepted_types as $i => $type) {
2433 if (substr($type, 0, 1) !== '.') {
2434 require_once($CFG->libdir. '/filelib.php');
2435 if (!count(file_get_typegroup('extension', $type))) {
2436 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2437 $accepted_types[$i] = '.'. $type;
2442 if (!empty($corrected)) {
2443 set_config('courseoverviewfilesext', join(',', $accepted_types));
2447 'maxfiles' => $CFG->courseoverviewfileslimit,
2448 'maxbytes' => $CFG->maxbytes,
2450 'accepted_types' => $accepted_types
2452 if (!empty($course->id)) {
2453 $options['context'] = context_course::instance($course->id);
2454 } else if (is_int($course) && $course > 0) {
2455 $options['context'] = context_course::instance($course);
2461 * Create a course and either return a $course object
2463 * Please note this functions does not verify any access control,
2464 * the calling code is responsible for all validation (usually it is the form definition).
2466 * @param array $editoroptions course description editor options
2467 * @param object $data - all the data needed for an entry in the 'course' table
2468 * @return object new course instance
2470 function create_course($data, $editoroptions = NULL) {
2473 //check the categoryid - must be given for all new courses
2474 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2476 // Check if the shortname already exists.
2477 if (!empty($data->shortname)) {
2478 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2479 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2483 // Check if the idnumber already exists.
2484 if (!empty($data->idnumber)) {
2485 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2486 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2490 $data->timecreated = time();
2491 $data->timemodified = $data->timecreated;
2493 // place at beginning of any category
2494 $data->sortorder = 0;
2496 if ($editoroptions) {
2497 // summary text is updated later, we need context to store the files first
2498 $data->summary = '';
2499 $data->summary_format = FORMAT_HTML;
2502 if (!isset($data->visible)) {
2503 // data not from form, add missing visibility info
2504 $data->visible = $category->visible;
2506 $data->visibleold = $data->visible;
2508 $newcourseid = $DB->insert_record('course', $data);
2509 $context = context_course::instance($newcourseid, MUST_EXIST);
2511 if ($editoroptions) {
2512 // Save the files used in the summary editor and store
2513 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2514 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2515 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2517 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2518 // Save the course overviewfiles
2519 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2522 // update course format options
2523 course_get_format($newcourseid)->update_course_format_options($data);
2525 $course = course_get_format($newcourseid)->get_course();
2528 blocks_add_default_course_blocks($course);
2530 // Create a default section.
2531 course_create_sections_if_missing($course, 0);
2533 fix_course_sortorder();
2534 // purge appropriate caches in case fix_course_sortorder() did not change anything
2535 cache_helper::purge_by_event('changesincourse');
2537 // new context created - better mark it as dirty
2538 $context->mark_dirty();
2540 // Save any custom role names.
2541 save_local_role_names($course->id, (array)$data);
2543 // set up enrolments
2544 enrol_course_updated(true, $course, $data);
2546 // Trigger a course created event.
2547 $event = \core\event\course_created::create(array(
2548 'objectid' => $course->id,
2549 'context' => context_course::instance($course->id),
2550 'other' => array('shortname' => $course->shortname,
2551 'fullname' => $course->fullname)
2561 * Please note this functions does not verify any access control,
2562 * the calling code is responsible for all validation (usually it is the form definition).
2564 * @param object $data - all the data needed for an entry in the 'course' table
2565 * @param array $editoroptions course description editor options
2568 function update_course($data, $editoroptions = NULL) {
2571 $data->timemodified = time();
2573 $oldcourse = course_get_format($data->id)->get_course();
2574 $context = context_course::instance($oldcourse->id);
2576 if ($editoroptions) {
2577 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2579 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2580 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2583 // Check we don't have a duplicate shortname.
2584 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2585 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2586 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2590 // Check we don't have a duplicate idnumber.
2591 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2592 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2593 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2597 if (!isset($data->category) or empty($data->category)) {
2598 // prevent nulls and 0 in category field
2599 unset($data->category);
2601 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2603 if (!isset($data->visible)) {
2604 // data not from form, add missing visibility info
2605 $data->visible = $oldcourse->visible;
2608 if ($data->visible != $oldcourse->visible) {
2609 // reset the visibleold flag when manually hiding/unhiding course
2610 $data->visibleold = $data->visible;
2611 $changesincoursecat = true;
2614 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2615 if (empty($newcategory->visible)) {
2616 // make sure when moving into hidden category the course is hidden automatically
2622 // Update with the new data
2623 $DB->update_record('course', $data);
2624 // make sure the modinfo cache is reset
2625 rebuild_course_cache($data->id);
2627 // update course format options with full course data
2628 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2630 $course = $DB->get_record('course', array('id'=>$data->id));
2633 $newparent = context_coursecat::instance($course->category);
2634 $context->update_moved($newparent);
2636 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2637 if ($fixcoursesortorder) {
2638 fix_course_sortorder();
2641 // purge appropriate caches in case fix_course_sortorder() did not change anything
2642 cache_helper::purge_by_event('changesincourse');
2643 if ($changesincoursecat) {
2644 cache_helper::purge_by_event('changesincoursecat');
2647 // Test for and remove blocks which aren't appropriate anymore
2648 blocks_remove_inappropriate($course);
2650 // Save any custom role names.
2651 save_local_role_names($course->id, $data);
2653 // update enrol settings
2654 enrol_course_updated(false, $course, $data);
2656 // Trigger a course updated event.
2657 $event = \core\event\course_updated::create(array(
2658 'objectid' => $course->id,
2659 'context' => context_course::instance($course->id),
2660 'other' => array('shortname' => $course->shortname,
2661 'fullname' => $course->fullname)
2664 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2667 if ($oldcourse->format !== $course->format) {
2668 // Remove all options stored for the previous format
2669 // We assume that new course format migrated everything it needed watching trigger
2670 // 'course_updated' and in method format_XXX::update_course_format_options()
2671 $DB->delete_records('course_format_options',
2672 array('courseid' => $course->id, 'format' => $oldcourse->format));
2677 * Average number of participants
2680 function average_number_of_participants() {
2683 //count total of enrolments for visible course (except front page)
2684 $sql = 'SELECT COUNT(*) FROM (
2685 SELECT DISTINCT ue.userid, e.courseid
2686 FROM {user_enrolments} ue, {enrol} e, {course} c
2687 WHERE ue.enrolid = e.id
2688 AND e.courseid <> :siteid
2689 AND c.id = e.courseid
2690 AND c.visible = 1) total';
2691 $params = array('siteid' => $SITE->id);
2692 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2695 //count total of visible courses (minus front page)
2696 $coursetotal = $DB->count_records('course', array('visible' => 1));
2697 $coursetotal = $coursetotal - 1 ;
2699 //average of enrolment
2700 if (empty($coursetotal)) {
2701 $participantaverage = 0;
2703 $participantaverage = $enrolmenttotal / $coursetotal;
2706 return $participantaverage;
2710 * Average number of course modules
2713 function average_number_of_courses_modules() {
2716 //count total of visible course module (except front page)
2717 $sql = 'SELECT COUNT(*) FROM (
2718 SELECT cm.course, cm.module
2719 FROM {course} c, {course_modules} cm
2720 WHERE c.id = cm.course
2723 AND c.visible = 1) total';
2724 $params = array('siteid' => $SITE->id);
2725 $moduletotal = $DB->count_records_sql($sql, $params);
2728 //count total of visible courses (minus front page)
2729 $coursetotal = $DB->count_records('course', array('visible' => 1));
2730 $coursetotal = $coursetotal - 1 ;
2732 //average of course module
2733 if (empty($coursetotal)) {
2734 $coursemoduleaverage = 0;
2736 $coursemoduleaverage = $moduletotal / $coursetotal;
2739 return $coursemoduleaverage;
2743 * This class pertains to course requests and contains methods associated with
2744 * create, approving, and removing course requests.
2746 * Please note we do not allow embedded images here because there is no context
2747 * to store them with proper access control.
2749 * @copyright 2009 Sam Hemelryk
2750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2753 * @property-read int $id
2754 * @property-read string $fullname
2755 * @property-read string $shortname
2756 * @property-read string $summary
2757 * @property-read int $summaryformat
2758 * @property-read int $summarytrust
2759 * @property-read string $reason
2760 * @property-read int $requester
2762 class course_request {
2765 * This is the stdClass that stores the properties for the course request
2766 * and is externally accessed through the __get magic method
2769 protected $properties;
2772 * An array of options for the summary editor used by course request forms.
2773 * This is initially set by {@link summary_editor_options()}
2777 protected static $summaryeditoroptions;
2780 * Static function to prepare the summary editor for working with a course
2784 * @param null|stdClass $data Optional, an object containing the default values
2785 * for the form, these may be modified when preparing the
2786 * editor so this should be called before creating the form
2787 * @return stdClass An object that can be used to set the default values for
2790 public static function prepare($data=null) {
2791 if ($data === null) {
2792 $data = new stdClass;
2794 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2799 * Static function to create a new course request when passed an array of properties
2802 * This function also handles saving any files that may have been used in the editor
2805 * @param stdClass $data
2806 * @return course_request The newly created course request
2808 public static function create($data) {
2809 global $USER, $DB, $CFG;
2810 $data->requester = $USER->id;
2812 // Setting the default category if none set.
2813 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2814 $data->category = $CFG->defaultrequestcategory;
2817 // Summary is a required field so copy the text over
2818 $data->summary = $data->summary_editor['text'];
2819 $data->summaryformat = $data->summary_editor['format'];
2821 $data->id = $DB->insert_record('course_request', $data);
2823 // Create a new course_request object and return it
2824 $request = new course_request($data);
2826 // Notify the admin if required.
2827 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2830 $a->link = "$CFG->wwwroot/course/pending.php";
2831 $a->user = fullname($USER);
2832 $subject = get_string('courserequest');
2833 $message = get_string('courserequestnotifyemail', 'admin', $a);
2834 foreach ($users as $user) {
2835 $request->notify($user, $USER, 'courserequested', $subject, $message);
2843 * Returns an array of options to use with a summary editor
2845 * @uses course_request::$summaryeditoroptions
2846 * @return array An array of options to use with the editor
2848 public static function summary_editor_options() {
2850 if (self::$summaryeditoroptions === null) {
2851 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2853 return self::$summaryeditoroptions;
2857 * Loads the properties for this course request object. Id is required and if
2858 * only id is provided then we load the rest of the properties from the database
2860 * @param stdClass|int $properties Either an object containing properties
2861 * or the course_request id to load
2863 public function __construct($properties) {
2865 if (empty($properties->id)) {
2866 if (empty($properties)) {
2867 throw new coding_exception('You must provide a course request id when creating a course_request object');
2870 $properties = new stdClass;
2871 $properties->id = (int)$id;
2874 if (empty($properties->requester)) {
2875 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2876 print_error('unknowncourserequest');
2879 $this->properties = $properties;
2881 $this->properties->collision = null;
2885 * Returns the requested property
2887 * @param string $key
2890 public function __get($key) {
2891 return $this->properties->$key;
2895 * Override this to ensure empty($request->blah) calls return a reliable answer...
2897 * This is required because we define the __get method
2900 * @return bool True is it not empty, false otherwise
2902 public function __isset($key) {
2903 return (!empty($this->properties->$key));
2907 * Returns the user who requested this course
2909 * Uses a static var to cache the results and cut down the number of db queries
2911 * @staticvar array $requesters An array of cached users
2912 * @return stdClass The user who requested the course
2914 public function get_requester() {
2916 static $requesters= array();
2917 if (!array_key_exists($this->properties->requester, $requesters)) {
2918 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2920 return $requesters[$this->properties->requester];
2924 * Checks that the shortname used by the course does not conflict with any other
2925 * courses that exist
2927 * @param string|null $shortnamemark The string to append to the requests shortname
2928 * should a conflict be found
2929 * @return bool true is there is a conflict, false otherwise
2931 public function check_shortname_collision($shortnamemark = '[*]') {
2934 if ($this->properties->collision !== null) {
2935 return $this->properties->collision;
2938 if (empty($this->properties->shortname)) {
2939 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2940 $this->properties->collision = false;
2941 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2942 if (!empty($shortnamemark)) {
2943 $this->properties->shortname .= ' '.$shortnamemark;
2945 $this->properties->collision = true;
2947 $this->properties->collision = false;
2949 return $this->properties->collision;
2953 * Returns the category where this course request should be created
2955 * Note that we don't check here that user has a capability to view
2956 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2957 * 'moodle/course:changecategory'
2961 public function get_category() {
2963 require_once($CFG->libdir.'/coursecatlib.php');
2964 // If the category is not set, if the current user does not have the rights to change the category, or if the
2965 // category does not exist, we set the default category to the course to be approved.
2966 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2967 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2968 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2969 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2972 $category = coursecat::get_default();
2978 * This function approves the request turning it into a course
2980 * This function converts the course request into a course, at the same time
2981 * transferring any files used in the summary to the new course and then removing
2982 * the course request and the files associated with it.
2984 * @return int The id of the course that was created from this request
2986 public function approve() {
2987 global $CFG, $DB, $USER;
2989 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2991 $courseconfig = get_config('moodlecourse');
2993 // Transfer appropriate settings
2994 $data = clone($this->properties);
2996 unset($data->reason);
2997 unset($data->requester);
3000 $category = $this->get_category();
3001 $data->category = $category->id;
3002 // Set misc settings
3003 $data->requested = 1;
3005 // Apply course default settings
3006 $data->format = $courseconfig->format;
3007 $data->newsitems = $courseconfig->newsitems;
3008 $data->showgrades = $courseconfig->showgrades;
3009 $data->showreports = $courseconfig->showreports;
3010 $data->maxbytes = $courseconfig->maxbytes;
3011 $data->groupmode = $courseconfig->groupmode;
3012 $data->groupmodeforce = $courseconfig->groupmodeforce;
3013 $data->visible = $courseconfig->visible;
3014 $data->visibleold = $data->visible;
3015 $data->lang = $courseconfig->lang;
3017 $course = create_course($data);
3018 $context = context_course::instance($course->id, MUST_EXIST);
3020 // add enrol instances
3021 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3022 if ($manual = enrol_get_plugin('manual')) {
3023 $manual->add_default_instance($course);
3027 // enrol the requester as teacher if necessary
3028 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3029 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3034 $a = new stdClass();
3035 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3036 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3037 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3043 * Reject a course request
3045 * This function rejects a course request, emailing the requesting user the
3046 * provided notice and then removing the request from the database
3048 * @param string $notice The message to display to the user
3050 public function reject($notice) {
3052 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3053 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3058 * Deletes the course request and any associated files
3060 public function delete() {
3062 $DB->delete_records('course_request', array('id' => $this->properties->id));
3066 * Send a message from one user to another using events_trigger
3068 * @param object $touser
3069 * @param object $fromuser
3070 * @param string $name
3071 * @param string $subject
3072 * @param string $message
3074 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3075 $eventdata = new stdClass();
3076 $eventdata->component = 'moodle';
3077 $eventdata->name = $name;
3078 $eventdata->userfrom = $fromuser;
3079 $eventdata->userto = $touser;
3080 $eventdata->subject = $subject;
3081 $eventdata->fullmessage = $message;
3082 $eventdata->fullmessageformat = FORMAT_PLAIN;
3083 $eventdata->fullmessagehtml = '';
3084 $eventdata->smallmessage = '';
3085 $eventdata->notification = 1;
3086 message_send($eventdata);
3091 * Return a list of page types
3092 * @param string $pagetype current page type
3093 * @param context $parentcontext Block's parent context
3094 * @param context $currentcontext Current context of block
3095 * @return array array of page types
3097 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3098 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3099 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3100 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3101 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3103 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3104 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3105 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3107 // Otherwise consider it a page inside a course even if $currentcontext is null
3108 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3109 'course-*' => get_string('page-course-x', 'pagetype'),
3110 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3117 * Determine whether course ajax should be enabled for the specified course
3119 * @param stdClass $course The course to test against
3120 * @return boolean Whether course ajax is enabled or note
3122 function course_ajax_enabled($course) {
3123 global $CFG, $PAGE, $SITE;
3125 // Ajax must be enabled globally
3126 if (!$CFG->enableajax) {
3130 // The user must be editing for AJAX to be included
3131 if (!$PAGE->user_is_editing()) {
3135 // Check that the theme suports
3136 if (!$PAGE->theme->enablecourseajax) {
3140 // Check that the course format supports ajax functionality
3141 // The site 'format' doesn't have information on course format support
3142 if ($SITE->id !== $course->id) {
3143 $courseformatajaxsupport = course_format_ajax_support($course->format);
3144 if (!$courseformatajaxsupport->capable) {
3149 // All conditions have been met so course ajax should be enabled
3154 * Include the relevant javascript and language strings for the resource
3155 * toolbox YUI module
3157 * @param integer $id The ID of the course being applied to
3158 * @param array $usedmodules An array containing the names of the modules in use on the page
3159 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3160 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3161 * * resourceurl The URL to post changes to for resource changes
3162 * * sectionurl The URL to post changes to for section changes
3163 * * pageparams Additional parameters to pass through in the post
3166 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3167 global $CFG, $PAGE, $SITE;
3169 // Ensure that ajax should be included
3170 if (!course_ajax_enabled($course)) {
3175 $config = new stdClass();
3178 // The URL to use for resource changes
3179 if (!isset($config->resourceurl)) {
3180 $config->resourceurl = '/course/rest.php';
3183 // The URL to use for section changes
3184 if (!isset($config->sectionurl)) {
3185 $config->sectionurl = '/course/rest.php';
3188 // Any additional parameters which need to be included on page submission
3189 if (!isset($config->pageparams)) {
3190 $config->pageparams = array();
3193 // Include toolboxes
3194 $PAGE->requires->yui_module('moodle-course-toolboxes',
3195 'M.course.init_resource_toolbox',
3197 'courseid' => $course->id,
3198 'ajaxurl' => $config->resourceurl,
3199 'config' => $config,
3202 $PAGE->requires->yui_module('moodle-course-toolboxes',
3203 'M.course.init_section_toolbox',
3205 'courseid' => $course->id,
3206 'format' => $course->format,
3207 'ajaxurl' => $config->sectionurl,
3208 'config' => $config,
3212 // Include course dragdrop
3213 if ($course->id != $SITE->id) {
3214 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3216 'courseid' => $course->id,
3217 'ajaxurl' => $config->sectionurl,
3218 'config' => $config,
3221 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3223 'courseid' => $course->id,
3224 'ajaxurl' => $config->resourceurl,
3225 'config' => $config,
3229 // Require various strings for the command toolbox
3230 $PAGE->requires->strings_for_js(array(
3233 'deletechecktypename',
3235 'edittitleinstructions',
3241 'clicktochangeinbrackets',
3248 'emptydragdropregion'
3251 // Include format-specific strings
3252 if ($course->id != $SITE->id) {
3253 $PAGE->requires->strings_for_js(array(
3256 ), 'format_' . $course->format);
3259 // For confirming resource deletion we need the name of the module in question
3260 foreach ($usedmodules as $module => $modname) {
3261 $PAGE->requires->string_for_js('pluginname', $module);
3264 // Load drag and drop upload AJAX.
3265 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3266 dndupload_add_to_course($course, $enabledmodules);
3272 * Returns the sorted list of available course formats, filtered by enabled if necessary
3274 * @param bool $enabledonly return only formats that are enabled
3275 * @return array array of sorted format names
3277 function get_sorted_course_formats($enabledonly = false) {
3279 $formats = core_component::get_plugin_list('format');
3281 if (!empty($CFG->format_plugins_sortorder)) {
3282 $order = explode(',', $CFG->format_plugins_sortorder);
3283 $order = array_merge(array_intersect($order, array_keys($formats)),
3284 array_diff(array_keys($formats), $order));
3286 $order = array_keys($formats);
3288 if (!$enabledonly) {
3291 $sortedformats = array();
3292 foreach ($order as $formatname) {
3293 if (!get_config('format_'.$formatname, 'disabled')) {
3294 $sortedformats[] = $formatname;
3297 return $sortedformats;
3301 * The URL to use for the specified course (with section)
3303 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3304 * @param int|stdClass $section Section object from database or just field course_sections.section
3305 * if omitted the course view page is returned
3306 * @param array $options options for view URL. At the moment core uses:
3307 * 'navigation' (bool) if true and section has no separate page, the function returns null
3308 * 'sr' (int) used by multipage formats to specify to which section to return
3309 * @return moodle_url The url of course
3311 function course_get_url($courseorid, $section = null, $options = array()) {
3312 return course_get_format($courseorid)->get_view_url($section, $options);
3319 * - capability checks and other checks
3320 * - create the module from the module info
3322 * @param object $module
3323 * @return object the created module info
3324 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3326 function create_module($moduleinfo) {
3329 require_once($CFG->dirroot . '/course/modlib.php');
3331 // Check manadatory attributs.
3332 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3333 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3334 $mandatoryfields[] = 'introeditor';
3336 foreach($mandatoryfields as $mandatoryfield) {
3337 if (!isset($moduleinfo->{$mandatoryfield})) {
3338 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3342 // Some additional checks (capability / existing instances).
3343 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3344 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3347 $moduleinfo->module = $module->id;
3348 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3357 * - capability and other checks
3358 * - update the module
3360 * @param object $module
3361 * @return object the updated module info
3362 * @throws moodle_exception if current user is not allowed to update the module
3364 function update_module($moduleinfo) {
3367 require_once($CFG->dirroot . '/course/modlib.php');
3369 // Check the course module exists.
3370 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3372 // Check the course exists.
3373 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3375 // Some checks (capaibility / existing instances).
3376 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3378 // Retrieve few information needed by update_moduleinfo.
3379 $moduleinfo->modulename = $cm->modname;
3380 if (!isset($moduleinfo->scale)) {
3381 $moduleinfo->scale = 0;
3383 $moduleinfo->type = 'mod';
3385 // Update the module.
3386 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3392 * Duplicate a module on the course.
3394 * @param object $course The course
3395 * @param object $cm The course module to duplicate
3396 * @throws moodle_exception if the plugin doesn't support duplication
3397 * @return Object containing:
3398 * - fullcontent: The HTML markup for the created CM
3399 * - cmid: The CMID of the newly created CM
3400 * - redirect: Whether to trigger a redirect following this change
3402 function mod_duplicate_activity($course, $cm, $sr = null) {
3403 global $CFG, $USER, $PAGE, $DB;
3405 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3406 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3407 require_once($CFG->libdir . '/filelib.php');
3409 $a = new stdClass();
3410 $a->modtype = get_string('modulename', $cm->modname);
3411 $a->modname = format_string($cm->name);
3413 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3414 throw new moodle_exception('duplicatenosupport', 'error');
3417 // backup the activity
3419 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3420 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3422 $backupid = $bc->get_backupid();
3423 $backupbasepath = $bc->get_plan()->get_basepath();
3425 $bc->execute_plan();
3429 // restore the backup immediately
3431 $rc = new restore_controller($backupid, $course->id,
3432 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3434 $cmcontext = context_module::instance($cm->id);
3435 if (!$rc->execute_precheck()) {
3436 $precheckresults = $rc->get_precheck_results();
3437 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3438 if (empty($CFG->keeptempdirectoriesonbackup)) {
3439 fulldelete($backupbasepath);
3444 $rc->execute_plan();
3446 // now a bit hacky part follows - we try to get the cmid of the newly
3447 // restored copy of the module
3449 $tasks = $rc->get_plan()->get_tasks();
3450 foreach ($tasks as $task) {
3451 error_log("Looking at a task");
3452 if (is_subclass_of($task, 'restore_activity_task')) {
3453 error_log("Looking at a restore_activity_task task");
3454 if ($task->get_old_contextid() == $cmcontext->id) {
3455 error_log("Contexts match");
3456 $newcmid = $task->get_moduleid();
3462 // if we know the cmid of the new course module, let us move it
3463 // right below the original one. otherwise it will stay at the
3464 // end of the section
3466 $info = get_fast_modinfo($course);
3467 $newcm = $info->get_cm($newcmid);
3468 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3469 moveto_module($newcm, $section, $cm);
3470 moveto_module($cm, $section, $newcm);
3472 rebuild_course_cache($cm->course);
3476 if (empty($CFG->keeptempdirectoriesonbackup)) {
3477 fulldelete($backupbasepath);
3480 $resp = new stdClass();
3482 $courserenderer = $PAGE->get_renderer('core', 'course');
3483 $completioninfo = new completion_info($course);
3484 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3485 $newcm, null, array());
3487 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3488 $resp->cmid = $newcm->id;
3490 // Trigger a redirect
3491 $resp->redirect = true;
3497 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3498 * Sorts by descending order of time.
3500 * @param stdClass $a First object
3501 * @param stdClass $b Second object
3502 * @return int 0,1,-1 representing the order
3504 function compare_activities_by_time_desc($a, $b) {
3505 // Make sure the activities actually have a timestamp property.
3506 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3509 // We treat instances without timestamp as if they have a timestamp of 0.
3510 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3513 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3516 if ($a->timestamp == $b->timestamp) {
3519 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3523 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3524 * Sorts by ascending order of time.
3526 * @param stdClass $a First object
3527 * @param stdClass $b Second object
3528 * @return int 0,1,-1 representing the order
3530 function compare_activities_by_time_asc($a, $b) {
3531 // Make sure the activities actually have a timestamp property.
3532 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3535 // We treat instances without timestamp as if they have a timestamp of 0.
3536 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3539 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3542 if ($a->timestamp == $b->timestamp) {
3545 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3549 * Changes the visibility of a course.
3551 * @param int $courseid The course to change.
3552 * @param bool $show True to make it visible, false otherwise.
3555 function course_change_visibility($courseid, $show = true) {
3556 $course = new stdClass;
3557 $course->id = $courseid;
3558 $course->visible = ($show) ? '1' : '0';
3559 $course->visibleold = $course->visible;
3560 update_course($course);
3565 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3567 * @param stdClass|course_in_list $course
3568 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3571 function course_change_sortorder_by_one($course, $up) {
3573 $params = array($course->sortorder, $course->category);
3575 $select = 'sortorder < ? AND category = ?';
3576 $sort = 'sortorder DESC';
3578 $select = 'sortorder > ? AND category = ?';
3579 $sort = 'sortorder ASC';
3581 fix_course_sortorder();
3582 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3584 $swapcourse = reset($swapcourse);
3585 $DB->set_field('course', 'sortorder', $swapco