Merge branch 'MDL-40920_master' of https://github.com/markn86/moodle
[moodle.git] / course / lib.php
blobd4e49b970ff0521b1a7f3ac00398d4ea1fbd4022
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
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.
34 /**
35 * Number of courses to display when summaries are included.
36 * @var int
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('FRONTPAGECATEGORYNAMES', '2');
47 define('FRONTPAGECATEGORYCOMBO', '4');
48 define('FRONTPAGEENROLLEDCOURSELIST', '5');
49 define('FRONTPAGEALLCOURSELIST', '6');
50 define('FRONTPAGECOURSESEARCH', '7');
51 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'calendar':
71 case 'category':
72 case 'mnet course':
73 if (strpos($url, '../') === 0) {
74 $url = ltrim($url, '.');
75 } else {
76 $url = "/course/$url";
78 break;
79 case 'user':
80 case 'blog':
81 $url = "/$module/$url";
82 break;
83 case 'upload':
84 $url = $url;
85 break;
86 case 'coursetags':
87 $url = '/'.$url;
88 break;
89 case 'library':
90 case '':
91 $url = '/';
92 break;
93 case 'message':
94 $url = "/message/$url";
95 break;
96 case 'notes':
97 $url = "/notes/$url";
98 break;
99 case 'tag':
100 $url = "/tag/$url";
101 break;
102 case 'role':
103 $url = '/'.$url;
104 break;
105 case 'grade':
106 $url = "/grade/$url";
107 break;
108 default:
109 $url = "/mod/$module/$url";
110 break;
113 //now let's sanitise urls - there might be some ugly nasties:-(
114 $parts = explode('?', $url);
115 $script = array_shift($parts);
116 if (strpos($script, 'http') === 0) {
117 $script = clean_param($script, PARAM_URL);
118 } else {
119 $script = clean_param($script, PARAM_PATH);
122 $query = '';
123 if ($parts) {
124 $query = implode('', $parts);
125 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
126 $parts = explode('&', $query);
127 $eq = urlencode('=');
128 foreach ($parts as $key=>$part) {
129 $part = urlencode(urldecode($part));
130 $part = str_replace($eq, '=', $part);
131 $parts[$key] = $part;
133 $query = '?'.implode('&amp;', $parts);
136 return $script.$query;
140 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
141 $modname="", $modid=0, $modaction="", $groupid=0) {
142 global $CFG, $DB;
144 // It is assumed that $date is the GMT time of midnight for that day,
145 // and so the next 86400 seconds worth of logs are printed.
147 /// Setup for group handling.
149 // TODO: I don't understand group/context/etc. enough to be able to do
150 // something interesting with it here
151 // What is the context of a remote course?
153 /// If the group mode is separate, and this user does not have editing privileges,
154 /// then only the user's group can be viewed.
155 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
156 // $groupid = get_current_group($course->id);
158 /// If this course doesn't have groups, no groupid can be specified.
159 //else if (!$course->groupmode) {
160 // $groupid = 0;
163 $groupid = 0;
165 $joins = array();
166 $where = '';
168 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
169 FROM {mnet_log} l
170 LEFT JOIN {user} u ON l.userid = u.id
171 WHERE ";
172 $params = array();
174 $where .= "l.hostid = :hostid";
175 $params['hostid'] = $hostid;
177 // TODO: Is 1 really a magic number referring to the sitename?
178 if ($course != SITEID || $modid != 0) {
179 $where .= " AND l.course=:courseid";
180 $params['courseid'] = $course;
183 if ($modname) {
184 $where .= " AND l.module = :modname";
185 $params['modname'] = $modname;
188 if ('site_errors' === $modid) {
189 $where .= " AND ( l.action='error' OR l.action='infected' )";
190 } else if ($modid) {
191 //TODO: This assumes that modids are the same across sites... probably
192 //not true
193 $where .= " AND l.cmid = :modid";
194 $params['modid'] = $modid;
197 if ($modaction) {
198 $firstletter = substr($modaction, 0, 1);
199 if ($firstletter == '-') {
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
201 $params['modaction'] = '%'.substr($modaction, 1).'%';
202 } else {
203 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
204 $params['modaction'] = '%'.$modaction.'%';
208 if ($user) {
209 $where .= " AND l.userid = :user";
210 $params['user'] = $user;
213 if ($date) {
214 $enddate = $date + 86400;
215 $where .= " AND l.time > :date AND l.time < :enddate";
216 $params['date'] = $date;
217 $params['enddate'] = $enddate;
220 $result = array();
221 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
222 if(!empty($result['totalcount'])) {
223 $where .= " ORDER BY $order";
224 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
225 } else {
226 $result['logs'] = array();
228 return $result;
231 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
232 $modname="", $modid=0, $modaction="", $groupid=0) {
233 global $DB, $SESSION, $USER;
234 // It is assumed that $date is the GMT time of midnight for that day,
235 // and so the next 86400 seconds worth of logs are printed.
237 /// Setup for group handling.
239 /// If the group mode is separate, and this user does not have editing privileges,
240 /// then only the user's group can be viewed.
241 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
242 if (isset($SESSION->currentgroup[$course->id])) {
243 $groupid = $SESSION->currentgroup[$course->id];
244 } else {
245 $groupid = groups_get_all_groups($course->id, $USER->id);
246 if (is_array($groupid)) {
247 $groupid = array_shift(array_keys($groupid));
248 $SESSION->currentgroup[$course->id] = $groupid;
249 } else {
250 $groupid = 0;
254 /// If this course doesn't have groups, no groupid can be specified.
255 else if (!$course->groupmode) {
256 $groupid = 0;
259 $joins = array();
260 $params = array();
262 if ($course->id != SITEID || $modid != 0) {
263 $joins[] = "l.course = :courseid";
264 $params['courseid'] = $course->id;
267 if ($modname) {
268 $joins[] = "l.module = :modname";
269 $params['modname'] = $modname;
272 if ('site_errors' === $modid) {
273 $joins[] = "( l.action='error' OR l.action='infected' )";
274 } else if ($modid) {
275 $joins[] = "l.cmid = :modid";
276 $params['modid'] = $modid;
279 if ($modaction) {
280 $firstletter = substr($modaction, 0, 1);
281 if ($firstletter == '-') {
282 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
283 $params['modaction'] = '%'.substr($modaction, 1).'%';
284 } else {
285 $joins[] = $DB->sql_like('l.action', ':modaction', false);
286 $params['modaction'] = '%'.$modaction.'%';
291 /// Getting all members of a group.
292 if ($groupid and !$user) {
293 if ($gusers = groups_get_members($groupid)) {
294 $gusers = array_keys($gusers);
295 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
296 } else {
297 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
300 else if ($user) {
301 $joins[] = "l.userid = :userid";
302 $params['userid'] = $user;
305 if ($date) {
306 $enddate = $date + 86400;
307 $joins[] = "l.time > :date AND l.time < :enddate";
308 $params['date'] = $date;
309 $params['enddate'] = $enddate;
312 $selector = implode(' AND ', $joins);
314 $totalcount = 0; // Initialise
315 $result = array();
316 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
317 $result['totalcount'] = $totalcount;
318 return $result;
322 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
323 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
325 global $CFG, $DB, $OUTPUT;
327 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
328 $modname, $modid, $modaction, $groupid)) {
329 echo $OUTPUT->notification("No logs found!");
330 echo $OUTPUT->footer();
331 exit;
334 $courses = array();
336 if ($course->id == SITEID) {
337 $courses[0] = '';
338 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
339 foreach ($ccc as $cc) {
340 $courses[$cc->id] = $cc->shortname;
343 } else {
344 $courses[$course->id] = $course->shortname;
347 $totalcount = $logs['totalcount'];
348 $count=0;
349 $ldcache = array();
350 $tt = getdate(time());
351 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
353 $strftimedatetime = get_string("strftimedatetime");
355 echo "<div class=\"info\">\n";
356 print_string("displayingrecords", "", $totalcount);
357 echo "</div>\n";
359 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
361 $table = new html_table();
362 $table->classes = array('logtable','generaltable');
363 $table->align = array('right', 'left', 'left');
364 $table->head = array(
365 get_string('time'),
366 get_string('ip_address'),
367 get_string('fullnameuser'),
368 get_string('action'),
369 get_string('info')
371 $table->data = array();
373 if ($course->id == SITEID) {
374 array_unshift($table->align, 'left');
375 array_unshift($table->head, get_string('course'));
378 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
379 if (empty($logs['logs'])) {
380 $logs['logs'] = array();
383 foreach ($logs['logs'] as $log) {
385 if (isset($ldcache[$log->module][$log->action])) {
386 $ld = $ldcache[$log->module][$log->action];
387 } else {
388 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
389 $ldcache[$log->module][$log->action] = $ld;
391 if ($ld && is_numeric($log->info)) {
392 // ugly hack to make sure fullname is shown correctly
393 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
394 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
395 } else {
396 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
400 //Filter log->info
401 $log->info = format_string($log->info);
403 // If $log->url has been trimmed short by the db size restriction
404 // code in add_to_log, keep a note so we don't add a link to a broken url
405 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
407 $row = array();
408 if ($course->id == SITEID) {
409 if (empty($log->course)) {
410 $row[] = get_string('site');
411 } else {
412 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
416 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
418 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
419 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
421 $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))));
423 $displayaction="$log->module $log->action";
424 if ($brokenurl) {
425 $row[] = $displayaction;
426 } else {
427 $link = make_log_url($log->module,$log->url);
428 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
430 $row[] = $log->info;
431 $table->data[] = $row;
434 echo html_writer::table($table);
435 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
439 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
440 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
442 global $CFG, $DB, $OUTPUT;
444 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
445 $modname, $modid, $modaction, $groupid)) {
446 echo $OUTPUT->notification("No logs found!");
447 echo $OUTPUT->footer();
448 exit;
451 if ($course->id == SITEID) {
452 $courses[0] = '';
453 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
454 foreach ($ccc as $cc) {
455 $courses[$cc->id] = $cc->shortname;
460 $totalcount = $logs['totalcount'];
461 $count=0;
462 $ldcache = array();
463 $tt = getdate(time());
464 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
466 $strftimedatetime = get_string("strftimedatetime");
468 echo "<div class=\"info\">\n";
469 print_string("displayingrecords", "", $totalcount);
470 echo "</div>\n";
472 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
474 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
475 echo "<tr>";
476 if ($course->id == SITEID) {
477 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
479 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
480 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
481 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
482 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
483 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
484 echo "</tr>\n";
486 if (empty($logs['logs'])) {
487 echo "</table>\n";
488 return;
491 $row = 1;
492 foreach ($logs['logs'] as $log) {
494 $log->info = $log->coursename;
495 $row = ($row + 1) % 2;
497 if (isset($ldcache[$log->module][$log->action])) {
498 $ld = $ldcache[$log->module][$log->action];
499 } else {
500 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
501 $ldcache[$log->module][$log->action] = $ld;
503 if (0 && $ld && !empty($log->info)) {
504 // ugly hack to make sure fullname is shown correctly
505 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
506 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
507 } else {
508 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
512 //Filter log->info
513 $log->info = format_string($log->info);
515 echo '<tr class="r'.$row.'">';
516 if ($course->id == SITEID) {
517 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
518 echo "<td class=\"r$row c0\" >\n";
519 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
520 echo "</td>\n";
522 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
523 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
524 echo "<td class=\"r$row c2\" >\n";
525 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
526 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
527 echo "</td>\n";
528 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
529 echo "<td class=\"r$row c3\" >\n";
530 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
531 echo "</td>\n";
532 echo "<td class=\"r$row c4\">\n";
533 echo $log->action .': '.$log->module;
534 echo "</td>\n";
535 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
536 echo "</tr>\n";
538 echo "</table>\n";
540 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
544 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
545 $modid, $modaction, $groupid) {
546 global $DB, $CFG;
548 require_once($CFG->libdir . '/csvlib.class.php');
550 $csvexporter = new csv_export_writer('tab');
552 $header = array();
553 $header[] = get_string('course');
554 $header[] = get_string('time');
555 $header[] = get_string('ip_address');
556 $header[] = get_string('fullnameuser');
557 $header[] = get_string('action');
558 $header[] = get_string('info');
560 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
561 $modname, $modid, $modaction, $groupid)) {
562 return false;
565 $courses = array();
567 if ($course->id == SITEID) {
568 $courses[0] = '';
569 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
570 foreach ($ccc as $cc) {
571 $courses[$cc->id] = $cc->shortname;
574 } else {
575 $courses[$course->id] = $course->shortname;
578 $count=0;
579 $ldcache = array();
580 $tt = getdate(time());
581 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
583 $strftimedatetime = get_string("strftimedatetime");
585 $csvexporter->set_filename('logs', '.txt');
586 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
587 $csvexporter->add_data($title);
588 $csvexporter->add_data($header);
590 if (empty($logs['logs'])) {
591 return true;
594 foreach ($logs['logs'] as $log) {
595 if (isset($ldcache[$log->module][$log->action])) {
596 $ld = $ldcache[$log->module][$log->action];
597 } else {
598 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
599 $ldcache[$log->module][$log->action] = $ld;
601 if ($ld && is_numeric($log->info)) {
602 // ugly hack to make sure fullname is shown correctly
603 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
604 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
605 } else {
606 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
610 //Filter log->info
611 $log->info = format_string($log->info);
612 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
614 $coursecontext = context_course::instance($course->id);
615 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
616 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
617 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
618 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
619 $csvexporter->add_data($row);
621 $csvexporter->download_file();
622 return true;
626 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
627 $modid, $modaction, $groupid) {
629 global $CFG, $DB;
631 require_once("$CFG->libdir/excellib.class.php");
633 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
634 $modname, $modid, $modaction, $groupid)) {
635 return false;
638 $courses = array();
640 if ($course->id == SITEID) {
641 $courses[0] = '';
642 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
643 foreach ($ccc as $cc) {
644 $courses[$cc->id] = $cc->shortname;
647 } else {
648 $courses[$course->id] = $course->shortname;
651 $count=0;
652 $ldcache = array();
653 $tt = getdate(time());
654 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
656 $strftimedatetime = get_string("strftimedatetime");
658 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
659 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
660 $filename .= '.xls';
662 $workbook = new MoodleExcelWorkbook('-');
663 $workbook->send($filename);
665 $worksheet = array();
666 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
667 get_string('fullnameuser'), get_string('action'), get_string('info'));
669 // Creating worksheets
670 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
671 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
672 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
673 $worksheet[$wsnumber]->set_column(1, 1, 30);
674 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
675 userdate(time(), $strftimedatetime));
676 $col = 0;
677 foreach ($headers as $item) {
678 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
679 $col++;
683 if (empty($logs['logs'])) {
684 $workbook->close();
685 return true;
688 $formatDate =& $workbook->add_format();
689 $formatDate->set_num_format(get_string('log_excel_date_format'));
691 $row = FIRSTUSEDEXCELROW;
692 $wsnumber = 1;
693 $myxls =& $worksheet[$wsnumber];
694 foreach ($logs['logs'] as $log) {
695 if (isset($ldcache[$log->module][$log->action])) {
696 $ld = $ldcache[$log->module][$log->action];
697 } else {
698 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
699 $ldcache[$log->module][$log->action] = $ld;
701 if ($ld && is_numeric($log->info)) {
702 // ugly hack to make sure fullname is shown correctly
703 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
704 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
705 } else {
706 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
710 // Filter log->info
711 $log->info = format_string($log->info);
712 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
714 if ($nroPages>1) {
715 if ($row > EXCELROWS) {
716 $wsnumber++;
717 $myxls =& $worksheet[$wsnumber];
718 $row = FIRSTUSEDEXCELROW;
722 $coursecontext = context_course::instance($course->id);
724 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
725 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
726 $myxls->write($row, 2, $log->ip, '');
727 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
728 $myxls->write($row, 3, $fullname, '');
729 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
730 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
731 $myxls->write($row, 5, $log->info, '');
733 $row++;
736 $workbook->close();
737 return true;
740 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
741 $modid, $modaction, $groupid) {
743 global $CFG, $DB;
745 require_once("$CFG->libdir/odslib.class.php");
747 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
748 $modname, $modid, $modaction, $groupid)) {
749 return false;
752 $courses = array();
754 if ($course->id == SITEID) {
755 $courses[0] = '';
756 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
757 foreach ($ccc as $cc) {
758 $courses[$cc->id] = $cc->shortname;
761 } else {
762 $courses[$course->id] = $course->shortname;
765 $count=0;
766 $ldcache = array();
767 $tt = getdate(time());
768 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
770 $strftimedatetime = get_string("strftimedatetime");
772 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
773 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
774 $filename .= '.ods';
776 $workbook = new MoodleODSWorkbook('-');
777 $workbook->send($filename);
779 $worksheet = array();
780 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
781 get_string('fullnameuser'), get_string('action'), get_string('info'));
783 // Creating worksheets
784 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
785 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
786 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
787 $worksheet[$wsnumber]->set_column(1, 1, 30);
788 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
789 userdate(time(), $strftimedatetime));
790 $col = 0;
791 foreach ($headers as $item) {
792 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
793 $col++;
797 if (empty($logs['logs'])) {
798 $workbook->close();
799 return true;
802 $formatDate =& $workbook->add_format();
803 $formatDate->set_num_format(get_string('log_excel_date_format'));
805 $row = FIRSTUSEDEXCELROW;
806 $wsnumber = 1;
807 $myxls =& $worksheet[$wsnumber];
808 foreach ($logs['logs'] as $log) {
809 if (isset($ldcache[$log->module][$log->action])) {
810 $ld = $ldcache[$log->module][$log->action];
811 } else {
812 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
813 $ldcache[$log->module][$log->action] = $ld;
815 if ($ld && is_numeric($log->info)) {
816 // ugly hack to make sure fullname is shown correctly
817 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
818 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
819 } else {
820 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
824 // Filter log->info
825 $log->info = format_string($log->info);
826 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
828 if ($nroPages>1) {
829 if ($row > EXCELROWS) {
830 $wsnumber++;
831 $myxls =& $worksheet[$wsnumber];
832 $row = FIRSTUSEDEXCELROW;
836 $coursecontext = context_course::instance($course->id);
838 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
839 $myxls->write_date($row, 1, $log->time);
840 $myxls->write_string($row, 2, $log->ip);
841 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
842 $myxls->write_string($row, 3, $fullname);
843 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
844 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
845 $myxls->write_string($row, 5, $log->info);
847 $row++;
850 $workbook->close();
851 return true;
855 * Checks the integrity of the course data.
857 * In summary - compares course_sections.sequence and course_modules.section.
859 * More detailed, checks that:
860 * - course_sections.sequence contains each module id not more than once in the course
861 * - for each moduleid from course_sections.sequence the field course_modules.section
862 * refers to the same section id (this means course_sections.sequence is more
863 * important if they are different)
864 * - ($fullcheck only) each module in the course is present in one of
865 * course_sections.sequence
866 * - ($fullcheck only) removes non-existing course modules from section sequences
868 * If there are any mismatches, the changes are made and records are updated in DB.
870 * Course cache is NOT rebuilt if there are any errors!
872 * This function is used each time when course cache is being rebuilt with $fullcheck = false
873 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
875 * @param int $courseid id of the course
876 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
877 * the list of enabled course modules in the course. Retrieved from DB if not specified.
878 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
879 * @param array $sections records from course_sections table for this course.
880 * Retrieved from DB if not specified
881 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
882 * course modules from sequences. Only to be used in site maintenance mode when we are
883 * sure that another user is not in the middle of the process of moving/removing a module.
884 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
885 * @return array array of messages with found problems. Empty output means everything is ok
887 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
888 global $DB;
889 $messages = array();
890 if ($sections === null) {
891 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
893 if ($fullcheck) {
894 // Retrieve all records from course_modules regardless of module type visibility.
895 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
897 if ($rawmods === null) {
898 $rawmods = get_course_mods($courseid);
900 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
901 // If either of the arrays is empty, no modules are displayed anyway.
902 return true;
904 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
906 // First make sure that each module id appears in section sequences only once.
907 // If it appears in several section sequences the last section wins.
908 // If it appears twice in one section sequence, the first occurence wins.
909 $modsection = array();
910 foreach ($sections as $sectionid => $section) {
911 $sections[$sectionid]->newsequence = $section->sequence;
912 if (!empty($section->sequence)) {
913 $sequence = explode(",", $section->sequence);
914 $sequenceunique = array_unique($sequence);
915 if (count($sequenceunique) != count($sequence)) {
916 // Some course module id appears in this section sequence more than once.
917 ksort($sequenceunique); // Preserve initial order of modules.
918 $sequence = array_values($sequenceunique);
919 $sections[$sectionid]->newsequence = join(',', $sequence);
920 $messages[] = $debuggingprefix.'Sequence for course section ['.
921 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
923 foreach ($sequence as $cmid) {
924 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
925 // Some course module id appears to be in more than one section's sequences.
926 $wrongsectionid = $modsection[$cmid];
927 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
928 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
929 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
931 $modsection[$cmid] = $sectionid;
936 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
937 if ($fullcheck) {
938 foreach ($rawmods as $cmid => $mod) {
939 if (!isset($modsection[$cmid])) {
940 // This is a module that is not mentioned in course_section.sequence at all.
941 // Add it to the section $mod->section or to the last available section.
942 if ($mod->section && isset($sections[$mod->section])) {
943 $modsection[$cmid] = $mod->section;
944 } else {
945 $firstsection = reset($sections);
946 $modsection[$cmid] = $firstsection->id;
948 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
949 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
950 $modsection[$cmid].']';
953 foreach ($modsection as $cmid => $sectionid) {
954 if (!isset($rawmods[$cmid])) {
955 // Section $sectionid refers to module id that does not exist.
956 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
957 $messages[] = $debuggingprefix.'Course module ['.$cmid.
958 '] does not exist but is present in the sequence of section ['.$sectionid.']';
963 // Update changed sections.
964 if (!$checkonly && !empty($messages)) {
965 foreach ($sections as $sectionid => $section) {
966 if ($section->newsequence !== $section->sequence) {
967 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
972 // Now make sure that all modules point to the correct sections.
973 foreach ($rawmods as $cmid => $mod) {
974 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
975 if (!$checkonly) {
976 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
978 $messages[] = $debuggingprefix.'Course module ['.$cmid.
979 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
983 return $messages;
987 * For a given course, returns an array of course activity objects
988 * Each item in the array contains he following properties:
990 function get_array_of_activities($courseid) {
991 // cm - course module id
992 // mod - name of the module (eg forum)
993 // section - the number of the section (eg week or topic)
994 // name - the name of the instance
995 // visible - is the instance visible or not
996 // groupingid - grouping id
997 // groupmembersonly - is this instance visible to group members only
998 // extra - contains extra string to include in any link
999 global $CFG, $DB;
1000 if(!empty($CFG->enableavailability)) {
1001 require_once($CFG->libdir.'/conditionlib.php');
1004 $course = $DB->get_record('course', array('id'=>$courseid));
1006 if (empty($course)) {
1007 throw new moodle_exception('courseidnotfound');
1010 $mod = array();
1012 $rawmods = get_course_mods($courseid);
1013 if (empty($rawmods)) {
1014 return $mod; // always return array
1017 if ($sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence')) {
1018 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
1019 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
1020 debugging(join('<br>', $errormessages));
1021 $rawmods = get_course_mods($courseid);
1022 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence');
1024 // Build array of activities.
1025 foreach ($sections as $section) {
1026 if (!empty($section->sequence)) {
1027 $sequence = explode(",", $section->sequence);
1028 foreach ($sequence as $seq) {
1029 if (empty($rawmods[$seq])) {
1030 continue;
1032 $mod[$seq] = new stdClass();
1033 $mod[$seq]->id = $rawmods[$seq]->instance;
1034 $mod[$seq]->cm = $rawmods[$seq]->id;
1035 $mod[$seq]->mod = $rawmods[$seq]->modname;
1037 // Oh dear. Inconsistent names left here for backward compatibility.
1038 $mod[$seq]->section = $section->section;
1039 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1041 $mod[$seq]->module = $rawmods[$seq]->module;
1042 $mod[$seq]->added = $rawmods[$seq]->added;
1043 $mod[$seq]->score = $rawmods[$seq]->score;
1044 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1045 $mod[$seq]->visible = $rawmods[$seq]->visible;
1046 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1047 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1048 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1049 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1050 $mod[$seq]->indent = $rawmods[$seq]->indent;
1051 $mod[$seq]->completion = $rawmods[$seq]->completion;
1052 $mod[$seq]->extra = "";
1053 $mod[$seq]->completiongradeitemnumber =
1054 $rawmods[$seq]->completiongradeitemnumber;
1055 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1056 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1057 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1058 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1059 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1060 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1061 if (!empty($CFG->enableavailability)) {
1062 condition_info::fill_availability_conditions($rawmods[$seq]);
1063 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1064 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1065 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1068 $modname = $mod[$seq]->mod;
1069 $functionname = $modname."_get_coursemodule_info";
1071 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1072 continue;
1075 include_once("$CFG->dirroot/mod/$modname/lib.php");
1077 if ($hasfunction = function_exists($functionname)) {
1078 if ($info = $functionname($rawmods[$seq])) {
1079 if (!empty($info->icon)) {
1080 $mod[$seq]->icon = $info->icon;
1082 if (!empty($info->iconcomponent)) {
1083 $mod[$seq]->iconcomponent = $info->iconcomponent;
1085 if (!empty($info->name)) {
1086 $mod[$seq]->name = $info->name;
1088 if ($info instanceof cached_cm_info) {
1089 // When using cached_cm_info you can include three new fields
1090 // that aren't available for legacy code
1091 if (!empty($info->content)) {
1092 $mod[$seq]->content = $info->content;
1094 if (!empty($info->extraclasses)) {
1095 $mod[$seq]->extraclasses = $info->extraclasses;
1097 if (!empty($info->iconurl)) {
1098 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
1099 $url = new moodle_url($info->iconurl);
1100 $mod[$seq]->iconurl = $url->out(false);
1102 if (!empty($info->onclick)) {
1103 $mod[$seq]->onclick = $info->onclick;
1105 if (!empty($info->customdata)) {
1106 $mod[$seq]->customdata = $info->customdata;
1108 } else {
1109 // When using a stdclass, the (horrible) deprecated ->extra field
1110 // is available for BC
1111 if (!empty($info->extra)) {
1112 $mod[$seq]->extra = $info->extra;
1117 // When there is no modname_get_coursemodule_info function,
1118 // but showdescriptions is enabled, then we use the 'intro'
1119 // and 'introformat' fields in the module table
1120 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1121 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1122 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1123 // Set content from intro and introformat. Filters are disabled
1124 // because we filter it with format_text at display time
1125 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1126 $modvalues, $rawmods[$seq]->id, false);
1128 // To save making another query just below, put name in here
1129 $mod[$seq]->name = $modvalues->name;
1132 if (!isset($mod[$seq]->name)) {
1133 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1136 // Minimise the database size by unsetting default options when they are
1137 // 'empty'. This list corresponds to code in the cm_info constructor.
1138 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1139 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1140 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1141 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1142 'completionview', 'completionexpected', 'score', 'showdescription')
1143 as $property) {
1144 if (property_exists($mod[$seq], $property) &&
1145 empty($mod[$seq]->{$property})) {
1146 unset($mod[$seq]->{$property});
1149 // Special case: this value is usually set to null, but may be 0
1150 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1151 is_null($mod[$seq]->completiongradeitemnumber)) {
1152 unset($mod[$seq]->completiongradeitemnumber);
1158 return $mod;
1162 * Returns the localised human-readable names of all used modules
1164 * @param bool $plural if true returns the plural forms of the names
1165 * @return array where key is the module name (component name without 'mod_') and
1166 * the value is the human-readable string. Array sorted alphabetically by value
1168 function get_module_types_names($plural = false) {
1169 static $modnames = null;
1170 global $DB, $CFG;
1171 if ($modnames === null) {
1172 $modnames = array(0 => array(), 1 => array());
1173 if ($allmods = $DB->get_records("modules")) {
1174 foreach ($allmods as $mod) {
1175 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1176 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1177 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1180 core_collator::asort($modnames[0]);
1181 core_collator::asort($modnames[1]);
1184 return $modnames[(int)$plural];
1188 * Set highlighted section. Only one section can be highlighted at the time.
1190 * @param int $courseid course id
1191 * @param int $marker highlight section with this number, 0 means remove higlightin
1192 * @return void
1194 function course_set_marker($courseid, $marker) {
1195 global $DB;
1196 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1197 format_base::reset_course_cache($courseid);
1201 * For a given course section, marks it visible or hidden,
1202 * and does the same for every activity in that section
1204 * @param int $courseid course id
1205 * @param int $sectionnumber The section number to adjust
1206 * @param int $visibility The new visibility
1207 * @return array A list of resources which were hidden in the section
1209 function set_section_visible($courseid, $sectionnumber, $visibility) {
1210 global $DB;
1212 $resourcestotoggle = array();
1213 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1214 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1215 if (!empty($section->sequence)) {
1216 $modules = explode(",", $section->sequence);
1217 foreach ($modules as $moduleid) {
1218 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1219 if ($visibility) {
1220 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1221 set_coursemodule_visible($moduleid, $cm->visibleold);
1222 } else {
1223 // We hide the section, so we hide the module but we store the original state in visibleold.
1224 set_coursemodule_visible($moduleid, 0);
1225 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1230 rebuild_course_cache($courseid, true);
1232 // Determine which modules are visible for AJAX update
1233 if (!empty($modules)) {
1234 list($insql, $params) = $DB->get_in_or_equal($modules);
1235 $select = 'id ' . $insql . ' AND visible = ?';
1236 array_push($params, $visibility);
1237 if (!$visibility) {
1238 $select .= ' AND visibleold = 1';
1240 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1243 return $resourcestotoggle;
1247 * Retrieve all metadata for the requested modules
1249 * @param object $course The Course
1250 * @param array $modnames An array containing the list of modules and their
1251 * names
1252 * @param int $sectionreturn The section to return to
1253 * @return array A list of stdClass objects containing metadata about each
1254 * module
1256 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1257 global $CFG, $OUTPUT;
1259 // get_module_metadata will be called once per section on the page and courses may show
1260 // different modules to one another
1261 static $modlist = array();
1262 if (!isset($modlist[$course->id])) {
1263 $modlist[$course->id] = array();
1266 $return = array();
1267 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1268 if ($sectionreturn !== null) {
1269 $urlbase->param('sr', $sectionreturn);
1271 foreach($modnames as $modname => $modnamestr) {
1272 if (!course_allowed_module($course, $modname)) {
1273 continue;
1275 if (isset($modlist[$course->id][$modname])) {
1276 // This module is already cached
1277 $return[$modname] = $modlist[$course->id][$modname];
1278 continue;
1281 // Include the module lib
1282 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1283 if (!file_exists($libfile)) {
1284 continue;
1286 include_once($libfile);
1288 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1289 $gettypesfunc = $modname.'_get_types';
1290 $types = MOD_SUBTYPE_NO_CHILDREN;
1291 if (function_exists($gettypesfunc)) {
1292 $types = $gettypesfunc();
1294 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
1295 if (is_array($types) && count($types) > 0) {
1296 $group = new stdClass();
1297 $group->name = $modname;
1298 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1299 foreach($types as $type) {
1300 if ($type->typestr === '--') {
1301 continue;
1303 if (strpos($type->typestr, '--') === 0) {
1304 $group->title = str_replace('--', '', $type->typestr);
1305 continue;
1307 // Set the Sub Type metadata
1308 $subtype = new stdClass();
1309 $subtype->title = $type->typestr;
1310 $subtype->type = str_replace('&amp;', '&', $type->type);
1311 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1312 $subtype->archetype = $type->modclass;
1314 // The group archetype should match the subtype archetypes and all subtypes
1315 // should have the same archetype
1316 $group->archetype = $subtype->archetype;
1318 if (!empty($type->help)) {
1319 $subtype->help = $type->help;
1320 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1321 $subtype->help = get_string('help' . $subtype->name, $modname);
1323 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1324 $group->types[] = $subtype;
1326 $modlist[$course->id][$modname] = $group;
1328 } else {
1329 $module = new stdClass();
1330 $module->title = $modnamestr;
1331 $module->name = $modname;
1332 $module->link = new moodle_url($urlbase, array('add' => $modname));
1333 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1334 $sm = get_string_manager();
1335 if ($sm->string_exists('modulename_help', $modname)) {
1336 $module->help = get_string('modulename_help', $modname);
1337 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1338 $link = get_string('modulename_link', $modname);
1339 $linktext = get_string('morehelp');
1340 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1343 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1344 $modlist[$course->id][$modname] = $module;
1346 if (isset($modlist[$course->id][$modname])) {
1347 $return[$modname] = $modlist[$course->id][$modname];
1348 } else {
1349 debugging("Invalid module metadata configuration for {$modname}");
1353 return $return;
1357 * Return the course category context for the category with id $categoryid, except
1358 * that if $categoryid is 0, return the system context.
1360 * @param integer $categoryid a category id or 0.
1361 * @return context the corresponding context
1363 function get_category_or_system_context($categoryid) {
1364 if ($categoryid) {
1365 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1366 } else {
1367 return context_system::instance();
1372 * Returns full course categories trees to be used in html_writer::select()
1374 * Calls {@link coursecat::make_categories_list()} to build the tree and
1375 * adds whitespace to denote nesting
1377 * @return array array mapping coursecat id to the display name
1379 function make_categories_options() {
1380 global $CFG;
1381 require_once($CFG->libdir. '/coursecatlib.php');
1382 $cats = coursecat::make_categories_list('', 0, ' / ');
1383 foreach ($cats as $key => $value) {
1384 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
1385 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
1387 return $cats;
1391 * Print the buttons relating to course requests.
1393 * @param object $context current page context.
1395 function print_course_request_buttons($context) {
1396 global $CFG, $DB, $OUTPUT;
1397 if (empty($CFG->enablecourserequests)) {
1398 return;
1400 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1401 /// Print a button to request a new course
1402 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1404 /// Print a button to manage pending requests
1405 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1406 $disabled = !$DB->record_exists('course_request', array());
1407 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1412 * Does the user have permission to edit things in this category?
1414 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1415 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1417 function can_edit_in_category($categoryid = 0) {
1418 $context = get_category_or_system_context($categoryid);
1419 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1422 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1424 function add_course_module($mod) {
1425 global $DB;
1427 $mod->added = time();
1428 unset($mod->id);
1430 $cmid = $DB->insert_record("course_modules", $mod);
1431 rebuild_course_cache($mod->course, true);
1432 return $cmid;
1436 * Creates missing course section(s) and rebuilds course cache
1438 * @param int|stdClass $courseorid course id or course object
1439 * @param int|array $sections list of relative section numbers to create
1440 * @return bool if there were any sections created
1442 function course_create_sections_if_missing($courseorid, $sections) {
1443 global $DB;
1444 if (!is_array($sections)) {
1445 $sections = array($sections);
1447 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1448 if (is_object($courseorid)) {
1449 $courseorid = $courseorid->id;
1451 $coursechanged = false;
1452 foreach ($sections as $sectionnum) {
1453 if (!in_array($sectionnum, $existing)) {
1454 $cw = new stdClass();
1455 $cw->course = $courseorid;
1456 $cw->section = $sectionnum;
1457 $cw->summary = '';
1458 $cw->summaryformat = FORMAT_HTML;
1459 $cw->sequence = '';
1460 $id = $DB->insert_record("course_sections", $cw);
1461 $coursechanged = true;
1464 if ($coursechanged) {
1465 rebuild_course_cache($courseorid, true);
1467 return $coursechanged;
1471 * Adds an existing module to the section
1473 * Updates both tables {course_sections} and {course_modules}
1475 * Note: This function does not use modinfo PROVIDED that the section you are
1476 * adding the module to already exists. If the section does not exist, it will
1477 * build modinfo if necessary and create the section.
1479 * @param int|stdClass $courseorid course id or course object
1480 * @param int $cmid id of the module already existing in course_modules table
1481 * @param int $sectionnum relative number of the section (field course_sections.section)
1482 * If section does not exist it will be created
1483 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1484 * before which the module needs to be included. Null for inserting in the
1485 * end of the section
1486 * @return int The course_sections ID where the module is inserted
1488 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1489 global $DB, $COURSE;
1490 if (is_object($beforemod)) {
1491 $beforemod = $beforemod->id;
1493 if (is_object($courseorid)) {
1494 $courseid = $courseorid->id;
1495 } else {
1496 $courseid = $courseorid;
1498 // Do not try to use modinfo here, there is no guarantee it is valid!
1499 $section = $DB->get_record('course_sections',
1500 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
1501 if (!$section) {
1502 // This function call requires modinfo.
1503 course_create_sections_if_missing($courseorid, $sectionnum);
1504 $section = $DB->get_record('course_sections',
1505 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
1508 $modarray = explode(",", trim($section->sequence));
1509 if (empty($section->sequence)) {
1510 $newsequence = "$cmid";
1511 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1512 $insertarray = array($cmid, $beforemod);
1513 array_splice($modarray, $key[0], 1, $insertarray);
1514 $newsequence = implode(",", $modarray);
1515 } else {
1516 $newsequence = "$section->sequence,$cmid";
1518 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1519 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1520 if (is_object($courseorid)) {
1521 rebuild_course_cache($courseorid->id, true);
1522 } else {
1523 rebuild_course_cache($courseorid, true);
1525 return $section->id; // Return course_sections ID that was used.
1528 function set_coursemodule_groupmode($id, $groupmode) {
1529 global $DB;
1530 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1531 if ($cm->groupmode != $groupmode) {
1532 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1533 rebuild_course_cache($cm->course, true);
1535 return ($cm->groupmode != $groupmode);
1538 function set_coursemodule_idnumber($id, $idnumber) {
1539 global $DB;
1540 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1541 if ($cm->idnumber != $idnumber) {
1542 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1543 rebuild_course_cache($cm->course, true);
1545 return ($cm->idnumber != $idnumber);
1549 * Set the visibility of a module and inherent properties.
1551 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1552 * has been moved to {@link set_section_visible()} which was the only place from which
1553 * the parameter was used.
1555 * @param int $id of the module
1556 * @param int $visible state of the module
1557 * @return bool false when the module was not found, true otherwise
1559 function set_coursemodule_visible($id, $visible) {
1560 global $DB, $CFG;
1561 require_once($CFG->libdir.'/gradelib.php');
1562 require_once($CFG->dirroot.'/calendar/lib.php');
1564 // Trigger developer's attention when using the previously removed argument.
1565 if (func_num_args() > 2) {
1566 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1567 has been removed.', DEBUG_DEVELOPER);
1570 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1571 return false;
1574 // Create events and propagate visibility to associated grade items if the value has changed.
1575 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1576 if ($cm->visible == $visible) {
1577 return true;
1580 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1581 return false;
1583 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1584 foreach($events as $event) {
1585 if ($visible) {
1586 $event = new calendar_event($event);
1587 $event->toggle_visibility(true);
1588 } else {
1589 $event = new calendar_event($event);
1590 $event->toggle_visibility(false);
1595 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1596 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1597 $cminfo = new stdClass();
1598 $cminfo->id = $id;
1599 $cminfo->visible = $visible;
1600 $cminfo->visibleold = $visible;
1601 $DB->update_record('course_modules', $cminfo);
1603 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1604 // Note that this must be done after updating the row in course_modules, in case
1605 // the modules grade_item_update function needs to access $cm->visible.
1606 if (plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1607 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1608 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1609 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1610 } else {
1611 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1612 if ($grade_items) {
1613 foreach ($grade_items as $grade_item) {
1614 $grade_item->set_hidden(!$visible);
1619 rebuild_course_cache($cm->course, true);
1620 return true;
1624 * This function will handles the whole deletion process of a module. This includes calling
1625 * the modules delete_instance function, deleting files, events, grades, conditional data,
1626 * the data in the course_module and course_sections table and adding a module deletion
1627 * event to the DB.
1629 * @param int $cmid the course module id
1630 * @since 2.5
1632 function course_delete_module($cmid) {
1633 global $CFG, $DB;
1635 require_once($CFG->libdir.'/gradelib.php');
1636 require_once($CFG->dirroot.'/blog/lib.php');
1637 require_once($CFG->dirroot.'/calendar/lib.php');
1639 // Get the course module.
1640 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1641 return true;
1644 // Get the module context.
1645 $modcontext = context_module::instance($cm->id);
1647 // Get the course module name.
1648 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1650 // Get the file location of the delete_instance function for this module.
1651 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1653 // Include the file required to call the delete_instance function for this module.
1654 if (file_exists($modlib)) {
1655 require_once($modlib);
1656 } else {
1657 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1658 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1661 $deleteinstancefunction = $modulename . '_delete_instance';
1663 // Ensure the delete_instance function exists for this module.
1664 if (!function_exists($deleteinstancefunction)) {
1665 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1666 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1669 // Call the delete_instance function, if it returns false throw an exception.
1670 if (!$deleteinstancefunction($cm->instance)) {
1671 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1672 "Cannot delete the module $modulename (instance).");
1675 // Remove all module files in case modules forget to do that.
1676 $fs = get_file_storage();
1677 $fs->delete_area_files($modcontext->id);
1679 // Delete events from calendar.
1680 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1681 foreach($events as $event) {
1682 $calendarevent = calendar_event::load($event->id);
1683 $calendarevent->delete();
1687 // Delete grade items, outcome items and grades attached to modules.
1688 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1689 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1690 foreach ($grade_items as $grade_item) {
1691 $grade_item->delete('moddelete');
1695 // Delete completion and availability data; it is better to do this even if the
1696 // features are not turned on, in case they were turned on previously (these will be
1697 // very quick on an empty table).
1698 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1699 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
1700 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
1701 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1702 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1704 // Delete the context.
1705 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1707 // Delete the module from the course_modules table.
1708 $DB->delete_records('course_modules', array('id' => $cm->id));
1710 // Delete module from that section.
1711 if (!delete_mod_from_section($cm->id, $cm->section)) {
1712 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1713 "Cannot delete the module $modulename (instance) from section.");
1716 // Trigger event for course module delete action.
1717 $event = \core\event\course_module_deleted::create(array(
1718 'courseid' => $cm->course,
1719 'context' => $modcontext,
1720 'objectid' => $cm->id,
1721 'other' => array(
1722 'modulename' => $modulename,
1723 'instanceid' => $cm->instance,
1726 $event->add_record_snapshot('course_modules', $cm);
1727 $event->trigger();
1728 rebuild_course_cache($cm->course, true);
1731 function delete_mod_from_section($modid, $sectionid) {
1732 global $DB;
1734 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1736 $modarray = explode(",", $section->sequence);
1738 if ($key = array_keys ($modarray, $modid)) {
1739 array_splice($modarray, $key[0], 1);
1740 $newsequence = implode(",", $modarray);
1741 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1742 rebuild_course_cache($section->course, true);
1743 return true;
1744 } else {
1745 return false;
1749 return false;
1753 * Moves a section within a course, from a position to another.
1754 * Be very careful: $section and $destination refer to section number,
1755 * not id!.
1757 * @param object $course
1758 * @param int $section Section number (not id!!!)
1759 * @param int $destination
1760 * @return boolean Result
1762 function move_section_to($course, $section, $destination) {
1763 /// Moves a whole course section up and down within the course
1764 global $USER, $DB;
1766 if (!$destination && $destination != 0) {
1767 return true;
1770 // compartibility with course formats using field 'numsections'
1771 $courseformatoptions = course_get_format($course)->get_format_options();
1772 if ((array_key_exists('numsections', $courseformatoptions) &&
1773 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1774 return false;
1777 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1778 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1779 'section ASC, id ASC', 'id, section')) {
1780 return false;
1783 $movedsections = reorder_sections($sections, $section, $destination);
1785 // Update all sections. Do this in 2 steps to avoid breaking database
1786 // uniqueness constraint
1787 $transaction = $DB->start_delegated_transaction();
1788 foreach ($movedsections as $id => $position) {
1789 if ($sections[$id] !== $position) {
1790 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1793 foreach ($movedsections as $id => $position) {
1794 if ($sections[$id] !== $position) {
1795 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1799 // If we move the highlighted section itself, then just highlight the destination.
1800 // Adjust the higlighted section location if we move something over it either direction.
1801 if ($section == $course->marker) {
1802 course_set_marker($course->id, $destination);
1803 } elseif ($section > $course->marker && $course->marker >= $destination) {
1804 course_set_marker($course->id, $course->marker+1);
1805 } elseif ($section < $course->marker && $course->marker <= $destination) {
1806 course_set_marker($course->id, $course->marker-1);
1809 $transaction->allow_commit();
1810 rebuild_course_cache($course->id, true);
1811 return true;
1815 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1816 * an original position number and a target position number, rebuilds the array so that the
1817 * move is made without any duplication of section positions.
1818 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1819 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1821 * @param array $sections
1822 * @param int $origin_position
1823 * @param int $target_position
1824 * @return array
1826 function reorder_sections($sections, $origin_position, $target_position) {
1827 if (!is_array($sections)) {
1828 return false;
1831 // We can't move section position 0
1832 if ($origin_position < 1) {
1833 echo "We can't move section position 0";
1834 return false;
1837 // Locate origin section in sections array
1838 if (!$origin_key = array_search($origin_position, $sections)) {
1839 echo "searched position not in sections array";
1840 return false; // searched position not in sections array
1843 // Extract origin section
1844 $origin_section = $sections[$origin_key];
1845 unset($sections[$origin_key]);
1847 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1848 $found = false;
1849 $append_array = array();
1850 foreach ($sections as $id => $position) {
1851 if ($found) {
1852 $append_array[$id] = $position;
1853 unset($sections[$id]);
1855 if ($position == $target_position) {
1856 if ($target_position < $origin_position) {
1857 $append_array[$id] = $position;
1858 unset($sections[$id]);
1860 $found = true;
1864 // Append moved section
1865 $sections[$origin_key] = $origin_section;
1867 // Append rest of array (if applicable)
1868 if (!empty($append_array)) {
1869 foreach ($append_array as $id => $position) {
1870 $sections[$id] = $position;
1874 // Renumber positions
1875 $position = 0;
1876 foreach ($sections as $id => $p) {
1877 $sections[$id] = $position;
1878 $position++;
1881 return $sections;
1886 * Move the module object $mod to the specified $section
1887 * If $beforemod exists then that is the module
1888 * before which $modid should be inserted
1890 * @param stdClass|cm_info $mod
1891 * @param stdClass|section_info $section
1892 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1893 * before which the module needs to be included. Null for inserting in the
1894 * end of the section
1895 * @return int new value for module visibility (0 or 1)
1897 function moveto_module($mod, $section, $beforemod=NULL) {
1898 global $OUTPUT, $DB;
1900 // Current module visibility state - return value of this function.
1901 $modvisible = $mod->visible;
1903 // Remove original module from original section.
1904 if (! delete_mod_from_section($mod->id, $mod->section)) {
1905 echo $OUTPUT->notification("Could not delete module from existing section");
1908 // If moving to a hidden section then hide module.
1909 if ($mod->section != $section->id) {
1910 if (!$section->visible && $mod->visible) {
1911 // Module was visible but must become hidden after moving to hidden section.
1912 $modvisible = 0;
1913 set_coursemodule_visible($mod->id, 0);
1914 // Set visibleold to 1 so module will be visible when section is made visible.
1915 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1917 if ($section->visible && !$mod->visible) {
1918 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1919 set_coursemodule_visible($mod->id, $mod->visibleold);
1920 $modvisible = $mod->visibleold;
1924 // Add the module into the new section.
1925 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1926 return $modvisible;
1930 * Returns the list of all editing actions that current user can perform on the module
1932 * @param cm_info $mod The module to produce editing buttons for
1933 * @param int $indent The current indenting (default -1 means no move left-right actions)
1934 * @param int $sr The section to link back to (used for creating the links)
1935 * @return array array of action_link or pix_icon objects
1937 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1938 global $COURSE, $SITE;
1940 static $str;
1942 $coursecontext = context_course::instance($mod->course);
1943 $modcontext = context_module::instance($mod->id);
1945 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1946 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1948 // No permission to edit anything.
1949 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1950 return array();
1953 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1955 if (!isset($str)) {
1956 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1957 'editsettings', 'duplicate', 'hide', 'show'), 'moodle');
1958 $str->assign = get_string('assignroles', 'role');
1959 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1960 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1961 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1964 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1966 if ($sr !== null) {
1967 $baseurl->param('sr', $sr);
1969 $actions = array();
1971 // Update.
1972 if ($hasmanageactivities) {
1973 $actions['update'] = new action_menu_link_secondary(
1974 new moodle_url($baseurl, array('update' => $mod->id)),
1975 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1976 $str->editsettings,
1977 array('class' => 'editing_update', 'data-action' => 'update')
1981 // Indent.
1982 if ($hasmanageactivities) {
1983 $indentlimits = new stdClass();
1984 $indentlimits->min = 0;
1985 $indentlimits->max = 16;
1986 if (right_to_left()) { // Exchange arrows on RTL
1987 $rightarrow = 't/left';
1988 $leftarrow = 't/right';
1989 } else {
1990 $rightarrow = 't/right';
1991 $leftarrow = 't/left';
1994 if ($indent >= $indentlimits->max) {
1995 $enabledclass = 'hidden';
1996 } else {
1997 $enabledclass = '';
1999 $actions['moveright'] = new action_menu_link_secondary(
2000 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
2001 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2002 $str->moveright,
2003 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright', 'data-keepopen' => true)
2006 if ($indent <= $indentlimits->min) {
2007 $enabledclass = 'hidden';
2008 } else {
2009 $enabledclass = '';
2011 $actions['moveleft'] = new action_menu_link_secondary(
2012 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
2013 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2014 $str->moveleft,
2015 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft', 'data-keepopen' => true)
2020 // Hide/Show.
2021 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2022 if ($mod->visible) {
2023 $actions['hide'] = new action_menu_link_secondary(
2024 new moodle_url($baseurl, array('hide' => $mod->id)),
2025 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2026 $str->hide,
2027 array('class' => 'editing_hide', 'data-action' => 'hide')
2029 } else {
2030 $actions['show'] = new action_menu_link_secondary(
2031 new moodle_url($baseurl, array('show' => $mod->id)),
2032 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2033 $str->show,
2034 array('class' => 'editing_show', 'data-action' => 'show')
2039 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2040 // Note that restoring on front page is never allowed.
2041 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
2042 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
2043 $actions['duplicate'] = new action_menu_link_secondary(
2044 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2045 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2046 $str->duplicate,
2047 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sr' => $sr)
2051 // Groupmode.
2052 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
2053 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2054 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2055 $nextgroupmode = VISIBLEGROUPS;
2056 $grouptitle = $str->groupsseparate;
2057 $actionname = 'groupsseparate';
2058 $groupimage = 'i/groups';
2059 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2060 $nextgroupmode = NOGROUPS;
2061 $grouptitle = $str->groupsvisible;
2062 $actionname = 'groupsvisible';
2063 $groupimage = 'i/groupv';
2064 } else {
2065 $nextgroupmode = SEPARATEGROUPS;
2066 $grouptitle = $str->groupsnone;
2067 $actionname = 'groupsnone';
2068 $groupimage = 'i/groupn';
2071 $actions[$actionname] = new action_menu_link_primary(
2072 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
2073 new pix_icon($groupimage, null, 'moodle', array('class' => 'iconsmall')),
2074 $grouptitle,
2075 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode, 'aria-live' => 'assertive')
2077 } else {
2078 $actions['nogroupsupport'] = new action_menu_filler();
2082 // Assign.
2083 if (has_capability('moodle/role:assign', $modcontext)){
2084 $actions['assign'] = new action_menu_link_secondary(
2085 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2086 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2087 $str->assign,
2088 array('class' => 'editing_assign', 'data-action' => 'assignroles')
2092 // Delete.
2093 if ($hasmanageactivities) {
2094 $actions['delete'] = new action_menu_link_secondary(
2095 new moodle_url($baseurl, array('delete' => $mod->id)),
2096 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2097 $str->delete,
2098 array('class' => 'editing_delete', 'data-action' => 'delete')
2102 return $actions;
2106 * Returns the rename action.
2108 * @param cm_info $mod The module to produce editing buttons for
2109 * @param int $sr The section to link back to (used for creating the links)
2110 * @return The markup for the rename action, or an empty string if not available.
2112 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
2113 global $COURSE, $OUTPUT;
2115 static $str;
2116 static $baseurl;
2118 $modcontext = context_module::instance($mod->id);
2119 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2121 if (!isset($str)) {
2122 $str = get_strings(array('edittitle'));
2125 if (!isset($baseurl)) {
2126 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2129 if ($sr !== null) {
2130 $baseurl->param('sr', $sr);
2133 // AJAX edit title.
2134 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
2135 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
2136 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2137 return html_writer::span(
2138 html_writer::link(
2139 new moodle_url($baseurl, array('update' => $mod->id)),
2140 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2141 array(
2142 'class' => 'editing_title',
2143 'data-action' => 'edittitle',
2144 'title' => $str->edittitle,
2149 return '';
2153 * Returns the move action.
2155 * @param cm_info $mod The module to produce a move button for
2156 * @param int $sr The section to link back to (used for creating the links)
2157 * @return The markup for the move action, or an empty string if not available.
2159 function course_get_cm_move(cm_info $mod, $sr = null) {
2160 global $OUTPUT;
2162 static $str;
2163 static $baseurl;
2165 $modcontext = context_module::instance($mod->id);
2166 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2168 if (!isset($str)) {
2169 $str = get_strings(array('move'));
2172 if (!isset($baseurl)) {
2173 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2175 if ($sr !== null) {
2176 $baseurl->param('sr', $sr);
2180 if ($hasmanageactivities) {
2181 $pixicon = 'i/dragdrop';
2183 if (!course_ajax_enabled($mod->get_course())) {
2184 // Override for course frontpage until we get drag/drop working there.
2185 $pixicon = 't/move';
2188 return html_writer::link(
2189 new moodle_url($baseurl, array('copy' => $mod->id)),
2190 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2191 array('class' => 'editing_move', 'data-action' => 'move')
2194 return '';
2198 * given a course object with shortname & fullname, this function will
2199 * truncate the the number of chars allowed and add ... if it was too long
2201 function course_format_name ($course,$max=100) {
2203 $context = context_course::instance($course->id);
2204 $shortname = format_string($course->shortname, true, array('context' => $context));
2205 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2206 $str = $shortname.': '. $fullname;
2207 if (core_text::strlen($str) <= $max) {
2208 return $str;
2210 else {
2211 return core_text::substr($str,0,$max-3).'...';
2216 * Is the user allowed to add this type of module to this course?
2217 * @param object $course the course settings. Only $course->id is used.
2218 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2219 * @return bool whether the current user is allowed to add this type of module to this course.
2221 function course_allowed_module($course, $modname) {
2222 if (is_numeric($modname)) {
2223 throw new coding_exception('Function course_allowed_module no longer
2224 supports numeric module ids. Please update your code to pass the module name.');
2227 $capability = 'mod/' . $modname . ':addinstance';
2228 if (!get_capability_info($capability)) {
2229 // Debug warning that the capability does not exist, but no more than once per page.
2230 static $warned = array();
2231 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2232 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2233 debugging('The module ' . $modname . ' does not define the standard capability ' .
2234 $capability , DEBUG_DEVELOPER);
2235 $warned[$modname] = 1;
2238 // If the capability does not exist, the module can always be added.
2239 return true;
2242 $coursecontext = context_course::instance($course->id);
2243 return has_capability($capability, $coursecontext);
2247 * Efficiently moves many courses around while maintaining
2248 * sortorder in order.
2250 * @param array $courseids is an array of course ids
2251 * @param int $categoryid
2252 * @return bool success
2254 function move_courses($courseids, $categoryid) {
2255 global $DB;
2257 if (empty($courseids)) {
2258 // Nothing to do.
2259 return false;
2262 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2263 return false;
2266 $courseids = array_reverse($courseids);
2267 $newparent = context_coursecat::instance($category->id);
2268 $i = 1;
2270 list($where, $params) = $DB->get_in_or_equal($courseids);
2271 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2272 foreach ($dbcourses as $dbcourse) {
2273 $course = new stdClass();
2274 $course->id = $dbcourse->id;
2275 $course->category = $category->id;
2276 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2277 if ($category->visible == 0) {
2278 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2279 // to previous state if somebody unhides the category.
2280 $course->visible = 0;
2283 $DB->update_record('course', $course);
2285 // Update context, so it can be passed to event.
2286 $context = context_course::instance($course->id);
2287 $context->update_moved($newparent);
2289 // Trigger a course updated event.
2290 $event = \core\event\course_updated::create(array(
2291 'objectid' => $course->id,
2292 'context' => context_course::instance($course->id),
2293 'other' => array('shortname' => $dbcourse->shortname,
2294 'fullname' => $dbcourse->fullname)
2296 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2297 $event->trigger();
2299 fix_course_sortorder();
2300 cache_helper::purge_by_event('changesincourse');
2302 return true;
2306 * Returns the display name of the given section that the course prefers
2308 * Implementation of this function is provided by course format
2309 * @see format_base::get_section_name()
2311 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2312 * @param int|stdClass $section Section object from database or just field course_sections.section
2313 * @return string Display name that the course format prefers, e.g. "Week 2"
2315 function get_section_name($courseorid, $section) {
2316 return course_get_format($courseorid)->get_section_name($section);
2320 * Tells if current course format uses sections
2322 * @param string $format Course format ID e.g. 'weeks' $course->format
2323 * @return bool
2325 function course_format_uses_sections($format) {
2326 $course = new stdClass();
2327 $course->format = $format;
2328 return course_get_format($course)->uses_sections();
2332 * Returns the information about the ajax support in the given source format
2334 * The returned object's property (boolean)capable indicates that
2335 * the course format supports Moodle course ajax features.
2336 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2338 * @param string $format
2339 * @return stdClass
2341 function course_format_ajax_support($format) {
2342 $course = new stdClass();
2343 $course->format = $format;
2344 return course_get_format($course)->supports_ajax();
2348 * Can the current user delete this course?
2349 * Course creators have exception,
2350 * 1 day after the creation they can sill delete the course.
2351 * @param int $courseid
2352 * @return boolean
2354 function can_delete_course($courseid) {
2355 global $USER, $DB;
2357 $context = context_course::instance($courseid);
2359 if (has_capability('moodle/course:delete', $context)) {
2360 return true;
2363 // hack: now try to find out if creator created this course recently (1 day)
2364 if (!has_capability('moodle/course:create', $context)) {
2365 return false;
2368 $since = time() - 60*60*24;
2370 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2371 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2373 return $DB->record_exists_select('log', $select, $params);
2377 * Save the Your name for 'Some role' strings.
2379 * @param integer $courseid the id of this course.
2380 * @param array $data the data that came from the course settings form.
2382 function save_local_role_names($courseid, $data) {
2383 global $DB;
2384 $context = context_course::instance($courseid);
2386 foreach ($data as $fieldname => $value) {
2387 if (strpos($fieldname, 'role_') !== 0) {
2388 continue;
2390 list($ignored, $roleid) = explode('_', $fieldname);
2392 // make up our mind whether we want to delete, update or insert
2393 if (!$value) {
2394 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2396 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2397 $rolename->name = $value;
2398 $DB->update_record('role_names', $rolename);
2400 } else {
2401 $rolename = new stdClass;
2402 $rolename->contextid = $context->id;
2403 $rolename->roleid = $roleid;
2404 $rolename->name = $value;
2405 $DB->insert_record('role_names', $rolename);
2411 * Returns options to use in course overviewfiles filemanager
2413 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2414 * may be empty if course does not exist yet (course create form)
2415 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2416 * or null if overviewfiles are disabled
2418 function course_overviewfiles_options($course) {
2419 global $CFG;
2420 if (empty($CFG->courseoverviewfileslimit)) {
2421 return null;
2423 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2424 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2425 $accepted_types = '*';
2426 } else {
2427 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2428 // Make sure extensions are prefixed with dot unless they are valid typegroups
2429 foreach ($accepted_types as $i => $type) {
2430 if (substr($type, 0, 1) !== '.') {
2431 require_once($CFG->libdir. '/filelib.php');
2432 if (!count(file_get_typegroup('extension', $type))) {
2433 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2434 $accepted_types[$i] = '.'. $type;
2435 $corrected = true;
2439 if (!empty($corrected)) {
2440 set_config('courseoverviewfilesext', join(',', $accepted_types));
2443 $options = array(
2444 'maxfiles' => $CFG->courseoverviewfileslimit,
2445 'maxbytes' => $CFG->maxbytes,
2446 'subdirs' => 0,
2447 'accepted_types' => $accepted_types
2449 if (!empty($course->id)) {
2450 $options['context'] = context_course::instance($course->id);
2451 } else if (is_int($course) && $course > 0) {
2452 $options['context'] = context_course::instance($course);
2454 return $options;
2458 * Create a course and either return a $course object
2460 * Please note this functions does not verify any access control,
2461 * the calling code is responsible for all validation (usually it is the form definition).
2463 * @param array $editoroptions course description editor options
2464 * @param object $data - all the data needed for an entry in the 'course' table
2465 * @return object new course instance
2467 function create_course($data, $editoroptions = NULL) {
2468 global $DB;
2470 //check the categoryid - must be given for all new courses
2471 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2473 // Check if the shortname already exists.
2474 if (!empty($data->shortname)) {
2475 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2476 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2480 // Check if the idnumber already exists.
2481 if (!empty($data->idnumber)) {
2482 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2483 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2487 $data->timecreated = time();
2488 $data->timemodified = $data->timecreated;
2490 // place at beginning of any category
2491 $data->sortorder = 0;
2493 if ($editoroptions) {
2494 // summary text is updated later, we need context to store the files first
2495 $data->summary = '';
2496 $data->summary_format = FORMAT_HTML;
2499 if (!isset($data->visible)) {
2500 // data not from form, add missing visibility info
2501 $data->visible = $category->visible;
2503 $data->visibleold = $data->visible;
2505 $newcourseid = $DB->insert_record('course', $data);
2506 $context = context_course::instance($newcourseid, MUST_EXIST);
2508 if ($editoroptions) {
2509 // Save the files used in the summary editor and store
2510 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2511 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2512 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2514 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2515 // Save the course overviewfiles
2516 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2519 // update course format options
2520 course_get_format($newcourseid)->update_course_format_options($data);
2522 $course = course_get_format($newcourseid)->get_course();
2524 // Setup the blocks
2525 blocks_add_default_course_blocks($course);
2527 // Create a default section.
2528 course_create_sections_if_missing($course, 0);
2530 fix_course_sortorder();
2531 // purge appropriate caches in case fix_course_sortorder() did not change anything
2532 cache_helper::purge_by_event('changesincourse');
2534 // new context created - better mark it as dirty
2535 $context->mark_dirty();
2537 // Save any custom role names.
2538 save_local_role_names($course->id, (array)$data);
2540 // set up enrolments
2541 enrol_course_updated(true, $course, $data);
2543 // Trigger a course created event.
2544 $event = \core\event\course_created::create(array(
2545 'objectid' => $course->id,
2546 'context' => context_course::instance($course->id),
2547 'other' => array('shortname' => $course->shortname,
2548 'fullname' => $course->fullname)
2550 $event->trigger();
2552 return $course;
2556 * Update a course.
2558 * Please note this functions does not verify any access control,
2559 * the calling code is responsible for all validation (usually it is the form definition).
2561 * @param object $data - all the data needed for an entry in the 'course' table
2562 * @param array $editoroptions course description editor options
2563 * @return void
2565 function update_course($data, $editoroptions = NULL) {
2566 global $DB;
2568 $data->timemodified = time();
2570 $oldcourse = course_get_format($data->id)->get_course();
2571 $context = context_course::instance($oldcourse->id);
2573 if ($editoroptions) {
2574 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2576 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2577 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2580 // Check we don't have a duplicate shortname.
2581 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2582 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2583 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2587 // Check we don't have a duplicate idnumber.
2588 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2589 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2590 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2594 if (!isset($data->category) or empty($data->category)) {
2595 // prevent nulls and 0 in category field
2596 unset($data->category);
2598 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2600 if (!isset($data->visible)) {
2601 // data not from form, add missing visibility info
2602 $data->visible = $oldcourse->visible;
2605 if ($data->visible != $oldcourse->visible) {
2606 // reset the visibleold flag when manually hiding/unhiding course
2607 $data->visibleold = $data->visible;
2608 $changesincoursecat = true;
2609 } else {
2610 if ($movecat) {
2611 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2612 if (empty($newcategory->visible)) {
2613 // make sure when moving into hidden category the course is hidden automatically
2614 $data->visible = 0;
2619 // Update with the new data
2620 $DB->update_record('course', $data);
2621 // make sure the modinfo cache is reset
2622 rebuild_course_cache($data->id);
2624 // update course format options with full course data
2625 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2627 $course = $DB->get_record('course', array('id'=>$data->id));
2629 if ($movecat) {
2630 $newparent = context_coursecat::instance($course->category);
2631 $context->update_moved($newparent);
2633 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2634 if ($fixcoursesortorder) {
2635 fix_course_sortorder();
2638 // purge appropriate caches in case fix_course_sortorder() did not change anything
2639 cache_helper::purge_by_event('changesincourse');
2640 if ($changesincoursecat) {
2641 cache_helper::purge_by_event('changesincoursecat');
2644 // Test for and remove blocks which aren't appropriate anymore
2645 blocks_remove_inappropriate($course);
2647 // Save any custom role names.
2648 save_local_role_names($course->id, $data);
2650 // update enrol settings
2651 enrol_course_updated(false, $course, $data);
2653 // Trigger a course updated event.
2654 $event = \core\event\course_updated::create(array(
2655 'objectid' => $course->id,
2656 'context' => context_course::instance($course->id),
2657 'other' => array('shortname' => $course->shortname,
2658 'fullname' => $course->fullname)
2661 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2662 $event->trigger();
2664 if ($oldcourse->format !== $course->format) {
2665 // Remove all options stored for the previous format
2666 // We assume that new course format migrated everything it needed watching trigger
2667 // 'course_updated' and in method format_XXX::update_course_format_options()
2668 $DB->delete_records('course_format_options',
2669 array('courseid' => $course->id, 'format' => $oldcourse->format));
2674 * Average number of participants
2675 * @return integer
2677 function average_number_of_participants() {
2678 global $DB, $SITE;
2680 //count total of enrolments for visible course (except front page)
2681 $sql = 'SELECT COUNT(*) FROM (
2682 SELECT DISTINCT ue.userid, e.courseid
2683 FROM {user_enrolments} ue, {enrol} e, {course} c
2684 WHERE ue.enrolid = e.id
2685 AND e.courseid <> :siteid
2686 AND c.id = e.courseid
2687 AND c.visible = 1) total';
2688 $params = array('siteid' => $SITE->id);
2689 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2692 //count total of visible courses (minus front page)
2693 $coursetotal = $DB->count_records('course', array('visible' => 1));
2694 $coursetotal = $coursetotal - 1 ;
2696 //average of enrolment
2697 if (empty($coursetotal)) {
2698 $participantaverage = 0;
2699 } else {
2700 $participantaverage = $enrolmenttotal / $coursetotal;
2703 return $participantaverage;
2707 * Average number of course modules
2708 * @return integer
2710 function average_number_of_courses_modules() {
2711 global $DB, $SITE;
2713 //count total of visible course module (except front page)
2714 $sql = 'SELECT COUNT(*) FROM (
2715 SELECT cm.course, cm.module
2716 FROM {course} c, {course_modules} cm
2717 WHERE c.id = cm.course
2718 AND c.id <> :siteid
2719 AND cm.visible = 1
2720 AND c.visible = 1) total';
2721 $params = array('siteid' => $SITE->id);
2722 $moduletotal = $DB->count_records_sql($sql, $params);
2725 //count total of visible courses (minus front page)
2726 $coursetotal = $DB->count_records('course', array('visible' => 1));
2727 $coursetotal = $coursetotal - 1 ;
2729 //average of course module
2730 if (empty($coursetotal)) {
2731 $coursemoduleaverage = 0;
2732 } else {
2733 $coursemoduleaverage = $moduletotal / $coursetotal;
2736 return $coursemoduleaverage;
2740 * This class pertains to course requests and contains methods associated with
2741 * create, approving, and removing course requests.
2743 * Please note we do not allow embedded images here because there is no context
2744 * to store them with proper access control.
2746 * @copyright 2009 Sam Hemelryk
2747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2748 * @since Moodle 2.0
2750 * @property-read int $id
2751 * @property-read string $fullname
2752 * @property-read string $shortname
2753 * @property-read string $summary
2754 * @property-read int $summaryformat
2755 * @property-read int $summarytrust
2756 * @property-read string $reason
2757 * @property-read int $requester
2759 class course_request {
2762 * This is the stdClass that stores the properties for the course request
2763 * and is externally accessed through the __get magic method
2764 * @var stdClass
2766 protected $properties;
2769 * An array of options for the summary editor used by course request forms.
2770 * This is initially set by {@link summary_editor_options()}
2771 * @var array
2772 * @static
2774 protected static $summaryeditoroptions;
2777 * Static function to prepare the summary editor for working with a course
2778 * request.
2780 * @static
2781 * @param null|stdClass $data Optional, an object containing the default values
2782 * for the form, these may be modified when preparing the
2783 * editor so this should be called before creating the form
2784 * @return stdClass An object that can be used to set the default values for
2785 * an mforms form
2787 public static function prepare($data=null) {
2788 if ($data === null) {
2789 $data = new stdClass;
2791 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2792 return $data;
2796 * Static function to create a new course request when passed an array of properties
2797 * for it.
2799 * This function also handles saving any files that may have been used in the editor
2801 * @static
2802 * @param stdClass $data
2803 * @return course_request The newly created course request
2805 public static function create($data) {
2806 global $USER, $DB, $CFG;
2807 $data->requester = $USER->id;
2809 // Setting the default category if none set.
2810 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2811 $data->category = $CFG->defaultrequestcategory;
2814 // Summary is a required field so copy the text over
2815 $data->summary = $data->summary_editor['text'];
2816 $data->summaryformat = $data->summary_editor['format'];
2818 $data->id = $DB->insert_record('course_request', $data);
2820 // Create a new course_request object and return it
2821 $request = new course_request($data);
2823 // Notify the admin if required.
2824 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2826 $a = new stdClass;
2827 $a->link = "$CFG->wwwroot/course/pending.php";
2828 $a->user = fullname($USER);
2829 $subject = get_string('courserequest');
2830 $message = get_string('courserequestnotifyemail', 'admin', $a);
2831 foreach ($users as $user) {
2832 $request->notify($user, $USER, 'courserequested', $subject, $message);
2836 return $request;
2840 * Returns an array of options to use with a summary editor
2842 * @uses course_request::$summaryeditoroptions
2843 * @return array An array of options to use with the editor
2845 public static function summary_editor_options() {
2846 global $CFG;
2847 if (self::$summaryeditoroptions === null) {
2848 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2850 return self::$summaryeditoroptions;
2854 * Loads the properties for this course request object. Id is required and if
2855 * only id is provided then we load the rest of the properties from the database
2857 * @param stdClass|int $properties Either an object containing properties
2858 * or the course_request id to load
2860 public function __construct($properties) {
2861 global $DB;
2862 if (empty($properties->id)) {
2863 if (empty($properties)) {
2864 throw new coding_exception('You must provide a course request id when creating a course_request object');
2866 $id = $properties;
2867 $properties = new stdClass;
2868 $properties->id = (int)$id;
2869 unset($id);
2871 if (empty($properties->requester)) {
2872 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2873 print_error('unknowncourserequest');
2875 } else {
2876 $this->properties = $properties;
2878 $this->properties->collision = null;
2882 * Returns the requested property
2884 * @param string $key
2885 * @return mixed
2887 public function __get($key) {
2888 return $this->properties->$key;
2892 * Override this to ensure empty($request->blah) calls return a reliable answer...
2894 * This is required because we define the __get method
2896 * @param mixed $key
2897 * @return bool True is it not empty, false otherwise
2899 public function __isset($key) {
2900 return (!empty($this->properties->$key));
2904 * Returns the user who requested this course
2906 * Uses a static var to cache the results and cut down the number of db queries
2908 * @staticvar array $requesters An array of cached users
2909 * @return stdClass The user who requested the course
2911 public function get_requester() {
2912 global $DB;
2913 static $requesters= array();
2914 if (!array_key_exists($this->properties->requester, $requesters)) {
2915 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2917 return $requesters[$this->properties->requester];
2921 * Checks that the shortname used by the course does not conflict with any other
2922 * courses that exist
2924 * @param string|null $shortnamemark The string to append to the requests shortname
2925 * should a conflict be found
2926 * @return bool true is there is a conflict, false otherwise
2928 public function check_shortname_collision($shortnamemark = '[*]') {
2929 global $DB;
2931 if ($this->properties->collision !== null) {
2932 return $this->properties->collision;
2935 if (empty($this->properties->shortname)) {
2936 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2937 $this->properties->collision = false;
2938 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2939 if (!empty($shortnamemark)) {
2940 $this->properties->shortname .= ' '.$shortnamemark;
2942 $this->properties->collision = true;
2943 } else {
2944 $this->properties->collision = false;
2946 return $this->properties->collision;
2950 * Returns the category where this course request should be created
2952 * Note that we don't check here that user has a capability to view
2953 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2954 * 'moodle/course:changecategory'
2956 * @return coursecat
2958 public function get_category() {
2959 global $CFG;
2960 require_once($CFG->libdir.'/coursecatlib.php');
2961 // If the category is not set, if the current user does not have the rights to change the category, or if the
2962 // category does not exist, we set the default category to the course to be approved.
2963 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2964 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2965 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2966 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2968 if (!$category) {
2969 $category = coursecat::get_default();
2971 return $category;
2975 * This function approves the request turning it into a course
2977 * This function converts the course request into a course, at the same time
2978 * transferring any files used in the summary to the new course and then removing
2979 * the course request and the files associated with it.
2981 * @return int The id of the course that was created from this request
2983 public function approve() {
2984 global $CFG, $DB, $USER;
2986 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2988 $courseconfig = get_config('moodlecourse');
2990 // Transfer appropriate settings
2991 $data = clone($this->properties);
2992 unset($data->id);
2993 unset($data->reason);
2994 unset($data->requester);
2996 // Set category
2997 $category = $this->get_category();
2998 $data->category = $category->id;
2999 // Set misc settings
3000 $data->requested = 1;
3002 // Apply course default settings
3003 $data->format = $courseconfig->format;
3004 $data->newsitems = $courseconfig->newsitems;
3005 $data->showgrades = $courseconfig->showgrades;
3006 $data->showreports = $courseconfig->showreports;
3007 $data->maxbytes = $courseconfig->maxbytes;
3008 $data->groupmode = $courseconfig->groupmode;
3009 $data->groupmodeforce = $courseconfig->groupmodeforce;
3010 $data->visible = $courseconfig->visible;
3011 $data->visibleold = $data->visible;
3012 $data->lang = $courseconfig->lang;
3014 $course = create_course($data);
3015 $context = context_course::instance($course->id, MUST_EXIST);
3017 // add enrol instances
3018 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3019 if ($manual = enrol_get_plugin('manual')) {
3020 $manual->add_default_instance($course);
3024 // enrol the requester as teacher if necessary
3025 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3026 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3029 $this->delete();
3031 $a = new stdClass();
3032 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3033 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3034 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3036 return $course->id;
3040 * Reject a course request
3042 * This function rejects a course request, emailing the requesting user the
3043 * provided notice and then removing the request from the database
3045 * @param string $notice The message to display to the user
3047 public function reject($notice) {
3048 global $USER, $DB;
3049 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3050 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3051 $this->delete();
3055 * Deletes the course request and any associated files
3057 public function delete() {
3058 global $DB;
3059 $DB->delete_records('course_request', array('id' => $this->properties->id));
3063 * Send a message from one user to another using events_trigger
3065 * @param object $touser
3066 * @param object $fromuser
3067 * @param string $name
3068 * @param string $subject
3069 * @param string $message
3071 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3072 $eventdata = new stdClass();
3073 $eventdata->component = 'moodle';
3074 $eventdata->name = $name;
3075 $eventdata->userfrom = $fromuser;
3076 $eventdata->userto = $touser;
3077 $eventdata->subject = $subject;
3078 $eventdata->fullmessage = $message;
3079 $eventdata->fullmessageformat = FORMAT_PLAIN;
3080 $eventdata->fullmessagehtml = '';
3081 $eventdata->smallmessage = '';
3082 $eventdata->notification = 1;
3083 message_send($eventdata);
3088 * Return a list of page types
3089 * @param string $pagetype current page type
3090 * @param context $parentcontext Block's parent context
3091 * @param context $currentcontext Current context of block
3092 * @return array array of page types
3094 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3095 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3096 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3097 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3098 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3100 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3101 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3102 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3103 } else {
3104 // Otherwise consider it a page inside a course even if $currentcontext is null
3105 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3106 'course-*' => get_string('page-course-x', 'pagetype'),
3107 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3110 return $pagetypes;
3114 * Determine whether course ajax should be enabled for the specified course
3116 * @param stdClass $course The course to test against
3117 * @return boolean Whether course ajax is enabled or note
3119 function course_ajax_enabled($course) {
3120 global $CFG, $PAGE, $SITE;
3122 // Ajax must be enabled globally
3123 if (!$CFG->enableajax) {
3124 return false;
3127 // The user must be editing for AJAX to be included
3128 if (!$PAGE->user_is_editing()) {
3129 return false;
3132 // Check that the theme suports
3133 if (!$PAGE->theme->enablecourseajax) {
3134 return false;
3137 // Check that the course format supports ajax functionality
3138 // The site 'format' doesn't have information on course format support
3139 if ($SITE->id !== $course->id) {
3140 $courseformatajaxsupport = course_format_ajax_support($course->format);
3141 if (!$courseformatajaxsupport->capable) {
3142 return false;
3146 // All conditions have been met so course ajax should be enabled
3147 return true;
3151 * Include the relevant javascript and language strings for the resource
3152 * toolbox YUI module
3154 * @param integer $id The ID of the course being applied to
3155 * @param array $usedmodules An array containing the names of the modules in use on the page
3156 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3157 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3158 * * resourceurl The URL to post changes to for resource changes
3159 * * sectionurl The URL to post changes to for section changes
3160 * * pageparams Additional parameters to pass through in the post
3161 * @return bool
3163 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3164 global $CFG, $PAGE, $SITE;
3166 // Ensure that ajax should be included
3167 if (!course_ajax_enabled($course)) {
3168 return false;
3171 if (!$config) {
3172 $config = new stdClass();
3175 // The URL to use for resource changes
3176 if (!isset($config->resourceurl)) {
3177 $config->resourceurl = '/course/rest.php';
3180 // The URL to use for section changes
3181 if (!isset($config->sectionurl)) {
3182 $config->sectionurl = '/course/rest.php';
3185 // Any additional parameters which need to be included on page submission
3186 if (!isset($config->pageparams)) {
3187 $config->pageparams = array();
3190 // Include toolboxes
3191 $PAGE->requires->yui_module('moodle-course-toolboxes',
3192 'M.course.init_resource_toolbox',
3193 array(array(
3194 'courseid' => $course->id,
3195 'ajaxurl' => $config->resourceurl,
3196 'config' => $config,
3199 $PAGE->requires->yui_module('moodle-course-toolboxes',
3200 'M.course.init_section_toolbox',
3201 array(array(
3202 'courseid' => $course->id,
3203 'format' => $course->format,
3204 'ajaxurl' => $config->sectionurl,
3205 'config' => $config,
3209 // Include course dragdrop
3210 if ($course->id != $SITE->id) {
3211 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3212 array(array(
3213 'courseid' => $course->id,
3214 'ajaxurl' => $config->sectionurl,
3215 'config' => $config,
3216 )), null, true);
3218 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3219 array(array(
3220 'courseid' => $course->id,
3221 'ajaxurl' => $config->resourceurl,
3222 'config' => $config,
3223 )), null, true);
3226 // Require various strings for the command toolbox
3227 $PAGE->requires->strings_for_js(array(
3228 'moveleft',
3229 'deletechecktype',
3230 'deletechecktypename',
3231 'edittitle',
3232 'edittitleinstructions',
3233 'show',
3234 'hide',
3235 'groupsnone',
3236 'groupsvisible',
3237 'groupsseparate',
3238 'clicktochangeinbrackets',
3239 'markthistopic',
3240 'markedthistopic',
3241 'move',
3242 'movesection',
3243 'movecontent',
3244 'tocontent',
3245 'emptydragdropregion'
3246 ), 'moodle');
3248 // Include format-specific strings
3249 if ($course->id != $SITE->id) {
3250 $PAGE->requires->strings_for_js(array(
3251 'showfromothers',
3252 'hidefromothers',
3253 ), 'format_' . $course->format);
3256 // For confirming resource deletion we need the name of the module in question
3257 foreach ($usedmodules as $module => $modname) {
3258 $PAGE->requires->string_for_js('pluginname', $module);
3261 // Load drag and drop upload AJAX.
3262 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3263 dndupload_add_to_course($course, $enabledmodules);
3265 return true;
3269 * Returns the sorted list of available course formats, filtered by enabled if necessary
3271 * @param bool $enabledonly return only formats that are enabled
3272 * @return array array of sorted format names
3274 function get_sorted_course_formats($enabledonly = false) {
3275 global $CFG;
3276 $formats = core_component::get_plugin_list('format');
3278 if (!empty($CFG->format_plugins_sortorder)) {
3279 $order = explode(',', $CFG->format_plugins_sortorder);
3280 $order = array_merge(array_intersect($order, array_keys($formats)),
3281 array_diff(array_keys($formats), $order));
3282 } else {
3283 $order = array_keys($formats);
3285 if (!$enabledonly) {
3286 return $order;
3288 $sortedformats = array();
3289 foreach ($order as $formatname) {
3290 if (!get_config('format_'.$formatname, 'disabled')) {
3291 $sortedformats[] = $formatname;
3294 return $sortedformats;
3298 * The URL to use for the specified course (with section)
3300 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3301 * @param int|stdClass $section Section object from database or just field course_sections.section
3302 * if omitted the course view page is returned
3303 * @param array $options options for view URL. At the moment core uses:
3304 * 'navigation' (bool) if true and section has no separate page, the function returns null
3305 * 'sr' (int) used by multipage formats to specify to which section to return
3306 * @return moodle_url The url of course
3308 function course_get_url($courseorid, $section = null, $options = array()) {
3309 return course_get_format($courseorid)->get_view_url($section, $options);
3313 * Create a module.
3315 * It includes:
3316 * - capability checks and other checks
3317 * - create the module from the module info
3319 * @param object $module
3320 * @return object the created module info
3321 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3323 function create_module($moduleinfo) {
3324 global $DB, $CFG;
3326 require_once($CFG->dirroot . '/course/modlib.php');
3328 // Check manadatory attributs.
3329 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3330 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3331 $mandatoryfields[] = 'introeditor';
3333 foreach($mandatoryfields as $mandatoryfield) {
3334 if (!isset($moduleinfo->{$mandatoryfield})) {
3335 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3339 // Some additional checks (capability / existing instances).
3340 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3341 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3343 // Add the module.
3344 $moduleinfo->module = $module->id;
3345 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3347 return $moduleinfo;
3351 * Update a module.
3353 * It includes:
3354 * - capability and other checks
3355 * - update the module
3357 * @param object $module
3358 * @return object the updated module info
3359 * @throws moodle_exception if current user is not allowed to update the module
3361 function update_module($moduleinfo) {
3362 global $DB, $CFG;
3364 require_once($CFG->dirroot . '/course/modlib.php');
3366 // Check the course module exists.
3367 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3369 // Check the course exists.
3370 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3372 // Some checks (capaibility / existing instances).
3373 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3375 // Retrieve few information needed by update_moduleinfo.
3376 $moduleinfo->modulename = $cm->modname;
3377 if (!isset($moduleinfo->scale)) {
3378 $moduleinfo->scale = 0;
3380 $moduleinfo->type = 'mod';
3382 // Update the module.
3383 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3385 return $moduleinfo;
3389 * Duplicate a module on the course.
3391 * @param object $course The course
3392 * @param object $cm The course module to duplicate
3393 * @throws moodle_exception if the plugin doesn't support duplication
3394 * @return Object containing:
3395 * - fullcontent: The HTML markup for the created CM
3396 * - cmid: The CMID of the newly created CM
3397 * - redirect: Whether to trigger a redirect following this change
3399 function mod_duplicate_activity($course, $cm, $sr = null) {
3400 global $CFG, $USER, $PAGE, $DB;
3402 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3403 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3404 require_once($CFG->libdir . '/filelib.php');
3406 $a = new stdClass();
3407 $a->modtype = get_string('modulename', $cm->modname);
3408 $a->modname = format_string($cm->name);
3410 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3411 throw new moodle_exception('duplicatenosupport', 'error');
3414 // backup the activity
3416 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3417 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3419 $backupid = $bc->get_backupid();
3420 $backupbasepath = $bc->get_plan()->get_basepath();
3422 $bc->execute_plan();
3424 $bc->destroy();
3426 // restore the backup immediately
3428 $rc = new restore_controller($backupid, $course->id,
3429 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3431 $cmcontext = context_module::instance($cm->id);
3432 if (!$rc->execute_precheck()) {
3433 $precheckresults = $rc->get_precheck_results();
3434 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3435 if (empty($CFG->keeptempdirectoriesonbackup)) {
3436 fulldelete($backupbasepath);
3441 $rc->execute_plan();
3443 // now a bit hacky part follows - we try to get the cmid of the newly
3444 // restored copy of the module
3445 $newcmid = null;
3446 $tasks = $rc->get_plan()->get_tasks();
3447 foreach ($tasks as $task) {
3448 error_log("Looking at a task");
3449 if (is_subclass_of($task, 'restore_activity_task')) {
3450 error_log("Looking at a restore_activity_task task");
3451 if ($task->get_old_contextid() == $cmcontext->id) {
3452 error_log("Contexts match");
3453 $newcmid = $task->get_moduleid();
3454 break;
3459 // if we know the cmid of the new course module, let us move it
3460 // right below the original one. otherwise it will stay at the
3461 // end of the section
3462 if ($newcmid) {
3463 $info = get_fast_modinfo($course);
3464 $newcm = $info->get_cm($newcmid);
3465 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3466 moveto_module($newcm, $section, $cm);
3467 moveto_module($cm, $section, $newcm);
3469 rebuild_course_cache($cm->course);
3471 $rc->destroy();
3473 if (empty($CFG->keeptempdirectoriesonbackup)) {
3474 fulldelete($backupbasepath);
3477 $resp = new stdClass();
3478 if ($newcm) {
3479 $courserenderer = $PAGE->get_renderer('core', 'course');
3480 $completioninfo = new completion_info($course);
3481 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3482 $newcm, null, array());
3484 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3485 $resp->cmid = $newcm->id;
3486 } else {
3487 // Trigger a redirect
3488 $resp->redirect = true;
3490 return $resp;
3494 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3495 * Sorts by descending order of time.
3497 * @param stdClass $a First object
3498 * @param stdClass $b Second object
3499 * @return int 0,1,-1 representing the order
3501 function compare_activities_by_time_desc($a, $b) {
3502 // Make sure the activities actually have a timestamp property.
3503 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3504 return 0;
3506 // We treat instances without timestamp as if they have a timestamp of 0.
3507 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3508 return 1;
3510 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3511 return -1;
3513 if ($a->timestamp == $b->timestamp) {
3514 return 0;
3516 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3520 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3521 * Sorts by ascending order of time.
3523 * @param stdClass $a First object
3524 * @param stdClass $b Second object
3525 * @return int 0,1,-1 representing the order
3527 function compare_activities_by_time_asc($a, $b) {
3528 // Make sure the activities actually have a timestamp property.
3529 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3530 return 0;
3532 // We treat instances without timestamp as if they have a timestamp of 0.
3533 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3534 return -1;
3536 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3537 return 1;
3539 if ($a->timestamp == $b->timestamp) {
3540 return 0;
3542 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3546 * Changes the visibility of a course.
3548 * @param int $courseid The course to change.
3549 * @param bool $show True to make it visible, false otherwise.
3550 * @return bool
3552 function course_change_visibility($courseid, $show = true) {
3553 $course = new stdClass;
3554 $course->id = $courseid;
3555 $course->visible = ($show) ? '1' : '0';
3556 $course->visibleold = $course->visible;
3557 update_course($course);
3558 return true;
3562 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3564 * @param stdClass|course_in_list $course
3565 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3566 * @return bool
3568 function course_change_sortorder_by_one($course, $up) {
3569 global $DB;
3570 $params = array($course->sortorder, $course->category);
3571 if ($up) {
3572 $select = 'sortorder < ? AND category = ?';
3573 $sort = 'sortorder DESC';
3574 } else {
3575 $select = 'sortorder > ? AND category = ?';
3576 $sort = 'sortorder ASC';
3578 fix_course_sortorder();
3579 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3580 if ($swapcourse) {
3581 $swapcourse = reset($swapcourse);
3582 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3583 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3584 // Finally reorder courses.
3585 fix_course_sortorder();
3586 cache_helper::purge_by_event('changesincourse');
3587 return true;
3589 return false;
3593 * Changes the sort order of courses in a category so that the first course appears after the second.
3595 * @param int|stdClass $courseorid The course to focus on.
3596 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3597 * @return bool
3599 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3600 global $DB;
3602 if (!is_object($courseorid)) {
3603 $course = get_course($courseorid);
3604 } else {
3605 $course = $courseorid;
3608 if ((int)$moveaftercourseid === 0) {
3609 // We've moving the course to the start of the queue.
3610 $sql = 'SELECT sortorder
3611 FROM {course}
3612 WHERE category = :categoryid
3613 ORDER BY sortorder';
3614 $params = array(
3615 'categoryid' => $course->category
3617 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3619 $sql = 'UPDATE {course}
3620 SET sortorder = sortorder + 1
3621 WHERE category = :categoryid
3622 AND id <> :id';
3623 $params = array(
3624 'categoryid' => $course->category,
3625 'id' => $course->id,
3627 $DB->execute($sql, $params);
3628 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3629 } else if ($course->id === $moveaftercourseid) {
3630 // They're the same - moronic.
3631 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3632 return false;
3633 } else {
3634 // Moving this course after the given course. It could be before it could be after.
3635 $moveaftercourse = get_course($moveaftercourseid);
3636 if ($course->category !== $moveaftercourse->category) {
3637 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3638 return false;
3640 // Increment all courses in the same category that are ordered after the moveafter course.
3641 // This makes a space for the course we're moving.
3642 $sql = 'UPDATE {course}
3643 SET sortorder = sortorder + 1
3644 WHERE category = :categoryid
3645 AND sortorder > :sortorder';
3646 $params = array(
3647 'categoryid' => $moveaftercourse->category,
3648 'sortorder' => $moveaftercourse->sortorder
3650 $DB->execute($sql, $params);
3651 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3653 fix_course_sortorder();
3654 cache_helper::purge_by_event('changesincourse');
3655 return true;