3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
38 * Number of courses to display when summaries are included.
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1'); // Not used. TODO MDL-38832 remove
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3'); // Not used. TODO MDL-38832 remove
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGEENROLLEDCOURSELIST', '5');
52 define('FRONTPAGEALLCOURSELIST', '6');
53 define('FRONTPAGECOURSESEARCH', '7');
54 define('FRONTPAGECOURSELIMIT', 200); // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage. TODO MDL-38832 remove
55 define('EXCELROWS', 65535);
56 define('FIRSTUSEDEXCELROW', 3);
58 define('MOD_CLASS_ACTIVITY', 0);
59 define('MOD_CLASS_RESOURCE', 1);
61 function make_log_url($module, $url) {
64 if (strpos($url, 'report/') === 0) {
65 // there is only one report type, course reports are deprecated
76 if (strpos($url, '../') === 0) {
77 $url = ltrim($url, '.');
79 $url = "/course/$url";
84 $url = "/$module/$url";
97 $url = "/message/$url";
100 $url = "/notes/$url";
109 $url = "/grade/$url";
112 $url = "/mod/$module/$url";
116 //now let's sanitise urls - there might be some ugly nasties:-(
117 $parts = explode('?', $url);
118 $script = array_shift($parts);
119 if (strpos($script, 'http') === 0) {
120 $script = clean_param($script, PARAM_URL);
122 $script = clean_param($script, PARAM_PATH);
127 $query = implode('', $parts);
128 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
129 $parts = explode('&', $query);
130 $eq = urlencode('=');
131 foreach ($parts as $key=>$part) {
132 $part = urlencode(urldecode($part));
133 $part = str_replace($eq, '=', $part);
134 $parts[$key] = $part;
136 $query = '?'.implode('&', $parts);
139 return $script.$query;
143 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
144 $modname="", $modid=0, $modaction="", $groupid=0) {
147 // It is assumed that $date is the GMT time of midnight for that day,
148 // and so the next 86400 seconds worth of logs are printed.
150 /// Setup for group handling.
152 // TODO: I don't understand group/context/etc. enough to be able to do
153 // something interesting with it here
154 // What is the context of a remote course?
156 /// If the group mode is separate, and this user does not have editing privileges,
157 /// then only the user's group can be viewed.
158 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
159 // $groupid = get_current_group($course->id);
161 /// If this course doesn't have groups, no groupid can be specified.
162 //else if (!$course->groupmode) {
171 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
173 LEFT JOIN {user} u ON l.userid = u.id
177 $where .= "l.hostid = :hostid";
178 $params['hostid'] = $hostid;
180 // TODO: Is 1 really a magic number referring to the sitename?
181 if ($course != SITEID || $modid != 0) {
182 $where .= " AND l.course=:courseid";
183 $params['courseid'] = $course;
187 $where .= " AND l.module = :modname";
188 $params['modname'] = $modname;
191 if ('site_errors' === $modid) {
192 $where .= " AND ( l.action='error' OR l.action='infected' )";
194 //TODO: This assumes that modids are the same across sites... probably
196 $where .= " AND l.cmid = :modid";
197 $params['modid'] = $modid;
201 $firstletter = substr($modaction, 0, 1);
202 if ($firstletter == '-') {
203 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
204 $params['modaction'] = '%'.substr($modaction, 1).'%';
206 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
207 $params['modaction'] = '%'.$modaction.'%';
212 $where .= " AND l.userid = :user";
213 $params['user'] = $user;
217 $enddate = $date + 86400;
218 $where .= " AND l.time > :date AND l.time < :enddate";
219 $params['date'] = $date;
220 $params['enddate'] = $enddate;
224 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
225 if(!empty($result['totalcount'])) {
226 $where .= " ORDER BY $order";
227 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
229 $result['logs'] = array();
234 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
235 $modname="", $modid=0, $modaction="", $groupid=0) {
236 global $DB, $SESSION, $USER;
237 // It is assumed that $date is the GMT time of midnight for that day,
238 // and so the next 86400 seconds worth of logs are printed.
240 /// Setup for group handling.
242 /// If the group mode is separate, and this user does not have editing privileges,
243 /// then only the user's group can be viewed.
244 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
245 if (isset($SESSION->currentgroup[$course->id])) {
246 $groupid = $SESSION->currentgroup[$course->id];
248 $groupid = groups_get_all_groups($course->id, $USER->id);
249 if (is_array($groupid)) {
250 $groupid = array_shift(array_keys($groupid));
251 $SESSION->currentgroup[$course->id] = $groupid;
257 /// If this course doesn't have groups, no groupid can be specified.
258 else if (!$course->groupmode) {
265 if ($course->id != SITEID || $modid != 0) {
266 $joins[] = "l.course = :courseid";
267 $params['courseid'] = $course->id;
271 $joins[] = "l.module = :modname";
272 $params['modname'] = $modname;
275 if ('site_errors' === $modid) {
276 $joins[] = "( l.action='error' OR l.action='infected' )";
278 $joins[] = "l.cmid = :modid";
279 $params['modid'] = $modid;
283 $firstletter = substr($modaction, 0, 1);
284 if ($firstletter == '-') {
285 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
286 $params['modaction'] = '%'.substr($modaction, 1).'%';
288 $joins[] = $DB->sql_like('l.action', ':modaction', false);
289 $params['modaction'] = '%'.$modaction.'%';
294 /// Getting all members of a group.
295 if ($groupid and !$user) {
296 if ($gusers = groups_get_members($groupid)) {
297 $gusers = array_keys($gusers);
298 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
300 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
304 $joins[] = "l.userid = :userid";
305 $params['userid'] = $user;
309 $enddate = $date + 86400;
310 $joins[] = "l.time > :date AND l.time < :enddate";
311 $params['date'] = $date;
312 $params['enddate'] = $enddate;
315 $selector = implode(' AND ', $joins);
317 $totalcount = 0; // Initialise
319 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
320 $result['totalcount'] = $totalcount;
325 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
326 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
328 global $CFG, $DB, $OUTPUT;
330 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
331 $modname, $modid, $modaction, $groupid)) {
332 echo $OUTPUT->notification("No logs found!");
333 echo $OUTPUT->footer();
339 if ($course->id == SITEID) {
341 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
342 foreach ($ccc as $cc) {
343 $courses[$cc->id] = $cc->shortname;
347 $courses[$course->id] = $course->shortname;
350 $totalcount = $logs['totalcount'];
353 $tt = getdate(time());
354 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
356 $strftimedatetime = get_string("strftimedatetime");
358 echo "<div class=\"info\">\n";
359 print_string("displayingrecords", "", $totalcount);
362 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
364 $table = new html_table();
365 $table->classes = array('logtable','generaltable');
366 $table->align = array('right', 'left', 'left');
367 $table->head = array(
369 get_string('ip_address'),
370 get_string('fullnameuser'),
371 get_string('action'),
374 $table->data = array();
376 if ($course->id == SITEID) {
377 array_unshift($table->align, 'left');
378 array_unshift($table->head, get_string('course'));
381 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
382 if (empty($logs['logs'])) {
383 $logs['logs'] = array();
386 foreach ($logs['logs'] as $log) {
388 if (isset($ldcache[$log->module][$log->action])) {
389 $ld = $ldcache[$log->module][$log->action];
391 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
392 $ldcache[$log->module][$log->action] = $ld;
394 if ($ld && is_numeric($log->info)) {
395 // ugly hack to make sure fullname is shown correctly
396 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
397 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
399 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
404 $log->info = format_string($log->info);
406 // If $log->url has been trimmed short by the db size restriction
407 // code in add_to_log, keep a note so we don't add a link to a broken url
408 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
411 if ($course->id == SITEID) {
412 if (empty($log->course)) {
413 $row[] = get_string('site');
415 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
419 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
421 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
422 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
424 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
426 $displayaction="$log->module $log->action";
428 $row[] = $displayaction;
430 $link = make_log_url($log->module,$log->url);
431 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
434 $table->data[] = $row;
437 echo html_writer::table($table);
438 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
442 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
443 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
445 global $CFG, $DB, $OUTPUT;
447 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
448 $modname, $modid, $modaction, $groupid)) {
449 echo $OUTPUT->notification("No logs found!");
450 echo $OUTPUT->footer();
454 if ($course->id == SITEID) {
456 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
457 foreach ($ccc as $cc) {
458 $courses[$cc->id] = $cc->shortname;
463 $totalcount = $logs['totalcount'];
466 $tt = getdate(time());
467 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
469 $strftimedatetime = get_string("strftimedatetime");
471 echo "<div class=\"info\">\n";
472 print_string("displayingrecords", "", $totalcount);
475 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
477 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
479 if ($course->id == SITEID) {
480 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
482 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
483 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
484 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
485 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
486 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
489 if (empty($logs['logs'])) {
495 foreach ($logs['logs'] as $log) {
497 $log->info = $log->coursename;
498 $row = ($row + 1) % 2;
500 if (isset($ldcache[$log->module][$log->action])) {
501 $ld = $ldcache[$log->module][$log->action];
503 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
504 $ldcache[$log->module][$log->action] = $ld;
506 if (0 && $ld && !empty($log->info)) {
507 // ugly hack to make sure fullname is shown correctly
508 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
509 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
511 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
516 $log->info = format_string($log->info);
518 echo '<tr class="r'.$row.'">';
519 if ($course->id == SITEID) {
520 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
521 echo "<td class=\"r$row c0\" >\n";
522 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
525 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
526 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
527 echo "<td class=\"r$row c2\" >\n";
528 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
529 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
531 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
532 echo "<td class=\"r$row c3\" >\n";
533 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
535 echo "<td class=\"r$row c4\">\n";
536 echo $log->action .': '.$log->module;
538 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
543 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
547 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
548 $modid, $modaction, $groupid) {
551 require_once($CFG->libdir . '/csvlib.class.php');
553 $csvexporter = new csv_export_writer('tab');
556 $header[] = get_string('course');
557 $header[] = get_string('time');
558 $header[] = get_string('ip_address');
559 $header[] = get_string('fullnameuser');
560 $header[] = get_string('action');
561 $header[] = get_string('info');
563 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
564 $modname, $modid, $modaction, $groupid)) {
570 if ($course->id == SITEID) {
572 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
573 foreach ($ccc as $cc) {
574 $courses[$cc->id] = $cc->shortname;
578 $courses[$course->id] = $course->shortname;
583 $tt = getdate(time());
584 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
586 $strftimedatetime = get_string("strftimedatetime");
588 $csvexporter->set_filename('logs', '.txt');
589 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
590 $csvexporter->add_data($title);
591 $csvexporter->add_data($header);
593 if (empty($logs['logs'])) {
597 foreach ($logs['logs'] as $log) {
598 if (isset($ldcache[$log->module][$log->action])) {
599 $ld = $ldcache[$log->module][$log->action];
601 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
602 $ldcache[$log->module][$log->action] = $ld;
604 if ($ld && is_numeric($log->info)) {
605 // ugly hack to make sure fullname is shown correctly
606 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
607 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
609 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
614 $log->info = format_string($log->info);
615 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
617 $coursecontext = context_course::instance($course->id);
618 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
619 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
620 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
621 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
622 $csvexporter->add_data($row);
624 $csvexporter->download_file();
629 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
630 $modid, $modaction, $groupid) {
634 require_once("$CFG->libdir/excellib.class.php");
636 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
637 $modname, $modid, $modaction, $groupid)) {
643 if ($course->id == SITEID) {
645 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
646 foreach ($ccc as $cc) {
647 $courses[$cc->id] = $cc->shortname;
651 $courses[$course->id] = $course->shortname;
656 $tt = getdate(time());
657 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
659 $strftimedatetime = get_string("strftimedatetime");
661 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
662 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
665 $workbook = new MoodleExcelWorkbook('-');
666 $workbook->send($filename);
668 $worksheet = array();
669 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
670 get_string('fullnameuser'), get_string('action'), get_string('info'));
672 // Creating worksheets
673 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
674 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
675 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
676 $worksheet[$wsnumber]->set_column(1, 1, 30);
677 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
678 userdate(time(), $strftimedatetime));
680 foreach ($headers as $item) {
681 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
686 if (empty($logs['logs'])) {
691 $formatDate =& $workbook->add_format();
692 $formatDate->set_num_format(get_string('log_excel_date_format'));
694 $row = FIRSTUSEDEXCELROW;
696 $myxls =& $worksheet[$wsnumber];
697 foreach ($logs['logs'] as $log) {
698 if (isset($ldcache[$log->module][$log->action])) {
699 $ld = $ldcache[$log->module][$log->action];
701 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
702 $ldcache[$log->module][$log->action] = $ld;
704 if ($ld && is_numeric($log->info)) {
705 // ugly hack to make sure fullname is shown correctly
706 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
707 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
709 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
714 $log->info = format_string($log->info);
715 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
718 if ($row > EXCELROWS) {
720 $myxls =& $worksheet[$wsnumber];
721 $row = FIRSTUSEDEXCELROW;
725 $coursecontext = context_course::instance($course->id);
727 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
728 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
729 $myxls->write($row, 2, $log->ip, '');
730 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
731 $myxls->write($row, 3, $fullname, '');
732 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
733 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
734 $myxls->write($row, 5, $log->info, '');
743 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
744 $modid, $modaction, $groupid) {
748 require_once("$CFG->libdir/odslib.class.php");
750 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
751 $modname, $modid, $modaction, $groupid)) {
757 if ($course->id == SITEID) {
759 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
760 foreach ($ccc as $cc) {
761 $courses[$cc->id] = $cc->shortname;
765 $courses[$course->id] = $course->shortname;
770 $tt = getdate(time());
771 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
773 $strftimedatetime = get_string("strftimedatetime");
775 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
776 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
779 $workbook = new MoodleODSWorkbook('-');
780 $workbook->send($filename);
782 $worksheet = array();
783 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
784 get_string('fullnameuser'), get_string('action'), get_string('info'));
786 // Creating worksheets
787 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
788 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
789 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
790 $worksheet[$wsnumber]->set_column(1, 1, 30);
791 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
792 userdate(time(), $strftimedatetime));
794 foreach ($headers as $item) {
795 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
800 if (empty($logs['logs'])) {
805 $formatDate =& $workbook->add_format();
806 $formatDate->set_num_format(get_string('log_excel_date_format'));
808 $row = FIRSTUSEDEXCELROW;
810 $myxls =& $worksheet[$wsnumber];
811 foreach ($logs['logs'] as $log) {
812 if (isset($ldcache[$log->module][$log->action])) {
813 $ld = $ldcache[$log->module][$log->action];
815 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
816 $ldcache[$log->module][$log->action] = $ld;
818 if ($ld && is_numeric($log->info)) {
819 // ugly hack to make sure fullname is shown correctly
820 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
821 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
823 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
828 $log->info = format_string($log->info);
829 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
832 if ($row > EXCELROWS) {
834 $myxls =& $worksheet[$wsnumber];
835 $row = FIRSTUSEDEXCELROW;
839 $coursecontext = context_course::instance($course->id);
841 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
842 $myxls->write_date($row, 1, $log->time);
843 $myxls->write_string($row, 2, $log->ip);
844 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
845 $myxls->write_string($row, 3, $fullname);
846 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
847 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
848 $myxls->write_string($row, 5, $log->info);
858 * For a given course, returns an array of course activity objects
859 * Each item in the array contains he following properties:
861 function get_array_of_activities($courseid) {
862 // cm - course module id
863 // mod - name of the module (eg forum)
864 // section - the number of the section (eg week or topic)
865 // name - the name of the instance
866 // visible - is the instance visible or not
867 // groupingid - grouping id
868 // groupmembersonly - is this instance visible to group members only
869 // extra - contains extra string to include in any link
871 if(!empty($CFG->enableavailability)) {
872 require_once($CFG->libdir.'/conditionlib.php');
875 $course = $DB->get_record('course', array('id'=>$courseid));
877 if (empty($course)) {
878 throw new moodle_exception('courseidnotfound');
883 $rawmods = get_course_mods($courseid);
884 if (empty($rawmods)) {
885 return $mod; // always return array
888 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
889 foreach ($sections as $section) {
890 if (!empty($section->sequence)) {
891 $sequence = explode(",", $section->sequence);
892 foreach ($sequence as $seq) {
893 if (empty($rawmods[$seq])) {
896 $mod[$seq] = new stdClass();
897 $mod[$seq]->id = $rawmods[$seq]->instance;
898 $mod[$seq]->cm = $rawmods[$seq]->id;
899 $mod[$seq]->mod = $rawmods[$seq]->modname;
901 // Oh dear. Inconsistent names left here for backward compatibility.
902 $mod[$seq]->section = $section->section;
903 $mod[$seq]->sectionid = $rawmods[$seq]->section;
905 $mod[$seq]->module = $rawmods[$seq]->module;
906 $mod[$seq]->added = $rawmods[$seq]->added;
907 $mod[$seq]->score = $rawmods[$seq]->score;
908 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
909 $mod[$seq]->visible = $rawmods[$seq]->visible;
910 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
911 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
912 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
913 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
914 $mod[$seq]->indent = $rawmods[$seq]->indent;
915 $mod[$seq]->completion = $rawmods[$seq]->completion;
916 $mod[$seq]->extra = "";
917 $mod[$seq]->completiongradeitemnumber =
918 $rawmods[$seq]->completiongradeitemnumber;
919 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
920 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
921 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
922 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
923 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
924 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
925 if (!empty($CFG->enableavailability)) {
926 condition_info::fill_availability_conditions($rawmods[$seq]);
927 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
928 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
929 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
932 $modname = $mod[$seq]->mod;
933 $functionname = $modname."_get_coursemodule_info";
935 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
939 include_once("$CFG->dirroot/mod/$modname/lib.php");
941 if ($hasfunction = function_exists($functionname)) {
942 if ($info = $functionname($rawmods[$seq])) {
943 if (!empty($info->icon)) {
944 $mod[$seq]->icon = $info->icon;
946 if (!empty($info->iconcomponent)) {
947 $mod[$seq]->iconcomponent = $info->iconcomponent;
949 if (!empty($info->name)) {
950 $mod[$seq]->name = $info->name;
952 if ($info instanceof cached_cm_info) {
953 // When using cached_cm_info you can include three new fields
954 // that aren't available for legacy code
955 if (!empty($info->content)) {
956 $mod[$seq]->content = $info->content;
958 if (!empty($info->extraclasses)) {
959 $mod[$seq]->extraclasses = $info->extraclasses;
961 if (!empty($info->iconurl)) {
962 $mod[$seq]->iconurl = $info->iconurl;
964 if (!empty($info->onclick)) {
965 $mod[$seq]->onclick = $info->onclick;
967 if (!empty($info->customdata)) {
968 $mod[$seq]->customdata = $info->customdata;
971 // When using a stdclass, the (horrible) deprecated ->extra field
972 // is available for BC
973 if (!empty($info->extra)) {
974 $mod[$seq]->extra = $info->extra;
979 // When there is no modname_get_coursemodule_info function,
980 // but showdescriptions is enabled, then we use the 'intro'
981 // and 'introformat' fields in the module table
982 if (!$hasfunction && $rawmods[$seq]->showdescription) {
983 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
984 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
985 // Set content from intro and introformat. Filters are disabled
986 // because we filter it with format_text at display time
987 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
988 $modvalues, $rawmods[$seq]->id, false);
990 // To save making another query just below, put name in here
991 $mod[$seq]->name = $modvalues->name;
994 if (!isset($mod[$seq]->name)) {
995 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
998 // Minimise the database size by unsetting default options when they are
999 // 'empty'. This list corresponds to code in the cm_info constructor.
1000 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1001 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1002 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1003 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1004 'completionview', 'completionexpected', 'score', 'showdescription')
1006 if (property_exists($mod[$seq], $property) &&
1007 empty($mod[$seq]->{$property})) {
1008 unset($mod[$seq]->{$property});
1011 // Special case: this value is usually set to null, but may be 0
1012 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1013 is_null($mod[$seq]->completiongradeitemnumber)) {
1014 unset($mod[$seq]->completiongradeitemnumber);
1024 * Returns the localised human-readable names of all used modules
1026 * @param bool $plural if true returns the plural forms of the names
1027 * @return array where key is the module name (component name without 'mod_') and
1028 * the value is the human-readable string. Array sorted alphabetically by value
1030 function get_module_types_names($plural = false) {
1031 static $modnames = null;
1033 if ($modnames === null) {
1034 $modnames = array(0 => array(), 1 => array());
1035 if ($allmods = $DB->get_records("modules")) {
1036 foreach ($allmods as $mod) {
1037 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1038 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1039 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1042 core_collator::asort($modnames[0]);
1043 core_collator::asort($modnames[1]);
1046 return $modnames[(int)$plural];
1050 * Set highlighted section. Only one section can be highlighted at the time.
1052 * @param int $courseid course id
1053 * @param int $marker highlight section with this number, 0 means remove higlightin
1056 function course_set_marker($courseid, $marker) {
1058 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1059 format_base::reset_course_cache($courseid);
1063 * For a given course section, marks it visible or hidden,
1064 * and does the same for every activity in that section
1066 * @param int $courseid course id
1067 * @param int $sectionnumber The section number to adjust
1068 * @param int $visibility The new visibility
1069 * @return array A list of resources which were hidden in the section
1071 function set_section_visible($courseid, $sectionnumber, $visibility) {
1074 $resourcestotoggle = array();
1075 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1076 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1077 if (!empty($section->sequence)) {
1078 $modules = explode(",", $section->sequence);
1079 foreach ($modules as $moduleid) {
1080 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1082 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1083 set_coursemodule_visible($moduleid, $cm->visibleold);
1085 // We hide the section, so we hide the module but we store the original state in visibleold.
1086 set_coursemodule_visible($moduleid, 0);
1087 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1092 rebuild_course_cache($courseid, true);
1094 // Determine which modules are visible for AJAX update
1095 if (!empty($modules)) {
1096 list($insql, $params) = $DB->get_in_or_equal($modules);
1097 $select = 'id ' . $insql . ' AND visible = ?';
1098 array_push($params, $visibility);
1100 $select .= ' AND visibleold = 1';
1102 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1105 return $resourcestotoggle;
1109 * Retrieve all metadata for the requested modules
1111 * @param object $course The Course
1112 * @param array $modnames An array containing the list of modules and their
1114 * @param int $sectionreturn The section to return to
1115 * @return array A list of stdClass objects containing metadata about each
1118 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1119 global $CFG, $OUTPUT;
1121 // get_module_metadata will be called once per section on the page and courses may show
1122 // different modules to one another
1123 static $modlist = array();
1124 if (!isset($modlist[$course->id])) {
1125 $modlist[$course->id] = array();
1129 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1130 if ($sectionreturn !== null) {
1131 $urlbase->param('sr', $sectionreturn);
1133 foreach($modnames as $modname => $modnamestr) {
1134 if (!course_allowed_module($course, $modname)) {
1137 if (isset($modlist[$course->id][$modname])) {
1138 // This module is already cached
1139 $return[$modname] = $modlist[$course->id][$modname];
1143 // Include the module lib
1144 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1145 if (!file_exists($libfile)) {
1148 include_once($libfile);
1150 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1151 $gettypesfunc = $modname.'_get_types';
1152 if (function_exists($gettypesfunc)) {
1153 $types = $gettypesfunc();
1154 if (is_array($types) && count($types) > 0) {
1155 $group = new stdClass();
1156 $group->name = $modname;
1157 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1158 foreach($types as $type) {
1159 if ($type->typestr === '--') {
1162 if (strpos($type->typestr, '--') === 0) {
1163 $group->title = str_replace('--', '', $type->typestr);
1166 // Set the Sub Type metadata
1167 $subtype = new stdClass();
1168 $subtype->title = $type->typestr;
1169 $subtype->type = str_replace('&', '&', $type->type);
1170 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1171 $subtype->archetype = $type->modclass;
1173 // The group archetype should match the subtype archetypes and all subtypes
1174 // should have the same archetype
1175 $group->archetype = $subtype->archetype;
1177 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1178 $subtype->help = get_string('help' . $subtype->name, $modname);
1180 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1181 $group->types[] = $subtype;
1183 $modlist[$course->id][$modname] = $group;
1186 $module = new stdClass();
1187 $module->title = $modnamestr;
1188 $module->name = $modname;
1189 $module->link = new moodle_url($urlbase, array('add' => $modname));
1190 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1191 $sm = get_string_manager();
1192 if ($sm->string_exists('modulename_help', $modname)) {
1193 $module->help = get_string('modulename_help', $modname);
1194 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1195 $link = get_string('modulename_link', $modname);
1196 $linktext = get_string('morehelp');
1197 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1200 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1201 $modlist[$course->id][$modname] = $module;
1203 if (isset($modlist[$course->id][$modname])) {
1204 $return[$modname] = $modlist[$course->id][$modname];
1206 debugging("Invalid module metadata configuration for {$modname}");
1214 * Return the course category context for the category with id $categoryid, except
1215 * that if $categoryid is 0, return the system context.
1217 * @param integer $categoryid a category id or 0.
1218 * @return object the corresponding context
1220 function get_category_or_system_context($categoryid) {
1222 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1224 return context_system::instance();
1229 * Returns full course categories trees to be used in html_writer::select()
1231 * Calls {@link coursecat::make_categories_list()} to build the tree and
1232 * adds whitespace to denote nesting
1234 * @return array array mapping coursecat id to the display name
1236 function make_categories_options() {
1238 require_once($CFG->libdir. '/coursecatlib.php');
1239 $cats = coursecat::make_categories_list('', 0, ' / ');
1240 foreach ($cats as $key => $value) {
1241 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
1242 $cats[$key] = str_repeat(' ', substr_count($value, ' / ')). $value;
1248 * Print the buttons relating to course requests.
1250 * @param object $context current page context.
1252 function print_course_request_buttons($context) {
1253 global $CFG, $DB, $OUTPUT;
1254 if (empty($CFG->enablecourserequests)) {
1257 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1258 /// Print a button to request a new course
1259 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1261 /// Print a button to manage pending requests
1262 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1263 $disabled = !$DB->record_exists('course_request', array());
1264 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1269 * Does the user have permission to edit things in this category?
1271 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1272 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1274 function can_edit_in_category($categoryid = 0) {
1275 $context = get_category_or_system_context($categoryid);
1276 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1279 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1281 function add_course_module($mod) {
1284 $mod->added = time();
1287 $cmid = $DB->insert_record("course_modules", $mod);
1288 rebuild_course_cache($mod->course, true);
1293 * Creates missing course section(s) and rebuilds course cache
1295 * @param int|stdClass $courseorid course id or course object
1296 * @param int|array $sections list of relative section numbers to create
1297 * @return bool if there were any sections created
1299 function course_create_sections_if_missing($courseorid, $sections) {
1301 if (!is_array($sections)) {
1302 $sections = array($sections);
1304 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1305 if (is_object($courseorid)) {
1306 $courseorid = $courseorid->id;
1308 $coursechanged = false;
1309 foreach ($sections as $sectionnum) {
1310 if (!in_array($sectionnum, $existing)) {
1311 $cw = new stdClass();
1312 $cw->course = $courseorid;
1313 $cw->section = $sectionnum;
1315 $cw->summaryformat = FORMAT_HTML;
1317 $id = $DB->insert_record("course_sections", $cw);
1318 $coursechanged = true;
1321 if ($coursechanged) {
1322 rebuild_course_cache($courseorid, true);
1324 return $coursechanged;
1328 * Adds an existing module to the section
1330 * Updates both tables {course_sections} and {course_modules}
1332 * Note: This function does not use modinfo PROVIDED that the section you are
1333 * adding the module to already exists. If the section does not exist, it will
1334 * build modinfo if necessary and create the section.
1336 * @param int|stdClass $courseorid course id or course object
1337 * @param int $cmid id of the module already existing in course_modules table
1338 * @param int $sectionnum relative number of the section (field course_sections.section)
1339 * If section does not exist it will be created
1340 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1341 * before which the module needs to be included. Null for inserting in the
1342 * end of the section
1343 * @return int The course_sections ID where the module is inserted
1345 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1346 global $DB, $COURSE;
1347 if (is_object($beforemod)) {
1348 $beforemod = $beforemod->id;
1350 if (is_object($courseorid)) {
1351 $courseid = $courseorid->id;
1353 $courseid = $courseorid;
1355 // Do not try to use modinfo here, there is no guarantee it is valid!
1356 $section = $DB->get_record('course_sections',
1357 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
1359 // This function call requires modinfo.
1360 course_create_sections_if_missing($courseorid, $sectionnum);
1361 $section = $DB->get_record('course_sections',
1362 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
1365 $modarray = explode(",", trim($section->sequence));
1366 if (empty($section->sequence)) {
1367 $newsequence = "$cmid";
1368 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1369 $insertarray = array($cmid, $beforemod);
1370 array_splice($modarray, $key[0], 1, $insertarray);
1371 $newsequence = implode(",", $modarray);
1373 $newsequence = "$section->sequence,$cmid";
1375 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1376 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1377 if (is_object($courseorid)) {
1378 rebuild_course_cache($courseorid->id, true);
1380 rebuild_course_cache($courseorid, true);
1382 return $section->id; // Return course_sections ID that was used.
1385 function set_coursemodule_groupmode($id, $groupmode) {
1387 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1388 if ($cm->groupmode != $groupmode) {
1389 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1390 rebuild_course_cache($cm->course, true);
1392 return ($cm->groupmode != $groupmode);
1395 function set_coursemodule_idnumber($id, $idnumber) {
1397 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1398 if ($cm->idnumber != $idnumber) {
1399 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1400 rebuild_course_cache($cm->course, true);
1402 return ($cm->idnumber != $idnumber);
1406 * Set the visibility of a module and inherent properties.
1408 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1409 * has been moved to {@link set_section_visible()} which was the only place from which
1410 * the parameter was used.
1412 * @param int $id of the module
1413 * @param int $visible state of the module
1414 * @return bool false when the module was not found, true otherwise
1416 function set_coursemodule_visible($id, $visible) {
1418 require_once($CFG->libdir.'/gradelib.php');
1419 require_once($CFG->dirroot.'/calendar/lib.php');
1421 // Trigger developer's attention when using the previously removed argument.
1422 if (func_num_args() > 2) {
1423 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1424 has been removed.', DEBUG_DEVELOPER);
1427 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1431 // Create events and propagate visibility to associated grade items if the value has changed.
1432 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1433 if ($cm->visible == $visible) {
1437 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1440 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1441 foreach($events as $event) {
1443 $event = new calendar_event($event);
1444 $event->toggle_visibility(true);
1446 $event = new calendar_event($event);
1447 $event->toggle_visibility(false);
1452 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1453 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1455 foreach ($grade_items as $grade_item) {
1456 $grade_item->set_hidden(!$visible);
1460 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1461 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1462 $cminfo = new stdClass();
1464 $cminfo->visible = $visible;
1465 $cminfo->visibleold = $visible;
1466 $DB->update_record('course_modules', $cminfo);
1468 rebuild_course_cache($cm->course, true);
1473 * This function will handles the whole deletion process of a module. This includes calling
1474 * the modules delete_instance function, deleting files, events, grades, conditional data,
1475 * the data in the course_module and course_sections table and adding a module deletion
1478 * @param int $cmid the course module id
1481 function course_delete_module($cmid) {
1482 global $CFG, $DB, $USER;
1484 require_once($CFG->libdir.'/gradelib.php');
1485 require_once($CFG->dirroot.'/blog/lib.php');
1486 require_once($CFG->dirroot.'/calendar/lib.php');
1488 // Get the course module.
1489 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1493 // Get the module context.
1494 $modcontext = context_module::instance($cm->id);
1496 // Get the course module name.
1497 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1499 // Get the file location of the delete_instance function for this module.
1500 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1502 // Include the file required to call the delete_instance function for this module.
1503 if (file_exists($modlib)) {
1504 require_once($modlib);
1506 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1507 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1510 $deleteinstancefunction = $modulename . '_delete_instance';
1512 // Ensure the delete_instance function exists for this module.
1513 if (!function_exists($deleteinstancefunction)) {
1514 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1515 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1518 // Call the delete_instance function, if it returns false throw an exception.
1519 if (!$deleteinstancefunction($cm->instance)) {
1520 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1521 "Cannot delete the module $modulename (instance).");
1524 // Remove all module files in case modules forget to do that.
1525 $fs = get_file_storage();
1526 $fs->delete_area_files($modcontext->id);
1528 // Delete events from calendar.
1529 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1530 foreach($events as $event) {
1531 $calendarevent = calendar_event::load($event->id);
1532 $calendarevent->delete();
1536 // Delete grade items, outcome items and grades attached to modules.
1537 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1538 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1539 foreach ($grade_items as $grade_item) {
1540 $grade_item->delete('moddelete');
1544 // Delete completion and availability data; it is better to do this even if the
1545 // features are not turned on, in case they were turned on previously (these will be
1546 // very quick on an empty table).
1547 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1548 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
1549 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
1550 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1551 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1553 // Delete the context.
1554 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1556 // Delete the module from the course_modules table.
1557 $DB->delete_records('course_modules', array('id' => $cm->id));
1559 // Delete module from that section.
1560 if (!delete_mod_from_section($cm->id, $cm->section)) {
1561 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1562 "Cannot delete the module $modulename (instance) from section.");
1565 // Trigger a mod_deleted event with information about this module.
1566 $eventdata = new stdClass();
1567 $eventdata->modulename = $modulename;
1568 $eventdata->cmid = $cm->id;
1569 $eventdata->courseid = $cm->course;
1570 $eventdata->userid = $USER->id;
1571 events_trigger('mod_deleted', $eventdata);
1573 add_to_log($cm->course, 'course', "delete mod",
1574 "view.php?id=$cm->course",
1575 "$modulename $cm->instance", $cm->id);
1577 rebuild_course_cache($cm->course, true);
1580 function delete_mod_from_section($modid, $sectionid) {
1583 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1585 $modarray = explode(",", $section->sequence);
1587 if ($key = array_keys ($modarray, $modid)) {
1588 array_splice($modarray, $key[0], 1);
1589 $newsequence = implode(",", $modarray);
1590 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1591 rebuild_course_cache($section->course, true);
1602 * Moves a section within a course, from a position to another.
1603 * Be very careful: $section and $destination refer to section number,
1606 * @param object $course
1607 * @param int $section Section number (not id!!!)
1608 * @param int $destination
1609 * @return boolean Result
1611 function move_section_to($course, $section, $destination) {
1612 /// Moves a whole course section up and down within the course
1615 if (!$destination && $destination != 0) {
1619 // compartibility with course formats using field 'numsections'
1620 $courseformatoptions = course_get_format($course)->get_format_options();
1621 if ((array_key_exists('numsections', $courseformatoptions) &&
1622 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1626 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1627 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1628 'section ASC, id ASC', 'id, section')) {
1632 $movedsections = reorder_sections($sections, $section, $destination);
1634 // Update all sections. Do this in 2 steps to avoid breaking database
1635 // uniqueness constraint
1636 $transaction = $DB->start_delegated_transaction();
1637 foreach ($movedsections as $id => $position) {
1638 if ($sections[$id] !== $position) {
1639 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1642 foreach ($movedsections as $id => $position) {
1643 if ($sections[$id] !== $position) {
1644 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1648 // If we move the highlighted section itself, then just highlight the destination.
1649 // Adjust the higlighted section location if we move something over it either direction.
1650 if ($section == $course->marker) {
1651 course_set_marker($course->id, $destination);
1652 } elseif ($section > $course->marker && $course->marker >= $destination) {
1653 course_set_marker($course->id, $course->marker+1);
1654 } elseif ($section < $course->marker && $course->marker <= $destination) {
1655 course_set_marker($course->id, $course->marker-1);
1658 $transaction->allow_commit();
1659 rebuild_course_cache($course->id, true);
1664 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1665 * an original position number and a target position number, rebuilds the array so that the
1666 * move is made without any duplication of section positions.
1667 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1668 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1670 * @param array $sections
1671 * @param int $origin_position
1672 * @param int $target_position
1675 function reorder_sections($sections, $origin_position, $target_position) {
1676 if (!is_array($sections)) {
1680 // We can't move section position 0
1681 if ($origin_position < 1) {
1682 echo "We can't move section position 0";
1686 // Locate origin section in sections array
1687 if (!$origin_key = array_search($origin_position, $sections)) {
1688 echo "searched position not in sections array";
1689 return false; // searched position not in sections array
1692 // Extract origin section
1693 $origin_section = $sections[$origin_key];
1694 unset($sections[$origin_key]);
1696 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1698 $append_array = array();
1699 foreach ($sections as $id => $position) {
1701 $append_array[$id] = $position;
1702 unset($sections[$id]);
1704 if ($position == $target_position) {
1705 if ($target_position < $origin_position) {
1706 $append_array[$id] = $position;
1707 unset($sections[$id]);
1713 // Append moved section
1714 $sections[$origin_key] = $origin_section;
1716 // Append rest of array (if applicable)
1717 if (!empty($append_array)) {
1718 foreach ($append_array as $id => $position) {
1719 $sections[$id] = $position;
1723 // Renumber positions
1725 foreach ($sections as $id => $p) {
1726 $sections[$id] = $position;
1735 * Move the module object $mod to the specified $section
1736 * If $beforemod exists then that is the module
1737 * before which $modid should be inserted
1738 * All parameters are objects
1740 function moveto_module($mod, $section, $beforemod=NULL) {
1741 global $OUTPUT, $DB;
1743 /// Remove original module from original section
1744 if (! delete_mod_from_section($mod->id, $mod->section)) {
1745 echo $OUTPUT->notification("Could not delete module from existing section");
1748 // if moving to a hidden section then hide module
1749 if ($mod->section != $section->id) {
1750 if (!$section->visible && $mod->visible) {
1751 // Set this in the object because it is sent as a response to ajax calls.
1753 set_coursemodule_visible($mod->id, 0);
1754 // Set visibleold to 1 so module will be visible when section is made visible.
1755 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1757 if ($section->visible && !$mod->visible) {
1758 set_coursemodule_visible($mod->id, $mod->visibleold);
1759 // Set this in the object because it is sent as a response to ajax calls.
1760 $mod->visible = $mod->visibleold;
1764 /// Add the module into the new section
1765 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1770 * Returns the list of all editing actions that current user can perform on the module
1772 * @param cm_info $mod The module to produce editing buttons for
1773 * @param int $indent The current indenting (default -1 means no move left-right actions)
1774 * @param int $sr The section to link back to (used for creating the links)
1775 * @return array array of action_link or pix_icon objects
1777 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1778 global $COURSE, $SITE;
1782 $coursecontext = context_course::instance($mod->course);
1783 $modcontext = context_module::instance($mod->id);
1785 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1786 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1788 // No permission to edit anything.
1789 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1793 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1796 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1797 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
1798 $str->assign = get_string('assignroles', 'role');
1799 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1800 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1801 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1802 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
1803 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
1804 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1807 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1810 $baseurl->param('sr', $sr);
1815 if ($mod->has_view() && $hasmanageactivities &&
1816 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
1817 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
1818 // we will not display link if we are on some other-course page (where we should not see this module anyway)
1819 $actions['title'] = new action_menu_link_secondary(
1820 new moodle_url($baseurl, array('update' => $mod->id)),
1821 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
1823 array('class' => 'editing_title', 'data-action' => 'edittitle')
1828 if ($hasmanageactivities) {
1829 if (right_to_left()) { // Exchange arrows on RTL
1830 $rightarrow = 't/left';
1831 $leftarrow = 't/right';
1833 $rightarrow = 't/right';
1834 $leftarrow = 't/left';
1837 $hiddenclass = 'hidden';
1841 $actions['moveleft'] = new action_menu_link_secondary(
1842 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1843 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1845 array('class' => 'editing_moveleft ' . $hiddenclass, 'data-action' => 'moveleft')
1847 $hiddenclass = 'hidden';
1851 $actions['moveright'] = new action_menu_link_secondary(
1852 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1853 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1855 array('class' => 'editing_moveright ' . $hiddenclass, 'data-action' => 'moveright')
1860 if ($hasmanageactivities) {
1861 $actions['move'] = new action_menu_link_primary(
1862 new moodle_url($baseurl, array('copy' => $mod->id)),
1863 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1865 array('class' => 'editing_move status', 'data-action' => 'move')
1870 if ($hasmanageactivities) {
1871 $actions['update'] = new action_menu_link_secondary(
1872 new moodle_url($baseurl, array('update' => $mod->id)),
1873 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1875 array('class' => 'editing_update', 'data-action' => 'update')
1879 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1880 // Note that restoring on front page is never allowed.
1881 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
1882 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
1883 $actions['duplicate'] = new action_menu_link_secondary(
1884 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1885 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1887 array('class' => 'editing_duplicate', 'data-action' => 'duplicate')
1892 if ($hasmanageactivities) {
1893 $actions['delete'] = new action_menu_link_secondary(
1894 new moodle_url($baseurl, array('delete' => $mod->id)),
1895 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1897 array('class' => 'editing_delete', 'data-action' => 'delete')
1902 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1903 if ($mod->visible) {
1904 $actions['hide'] = new action_menu_link_primary(
1905 new moodle_url($baseurl, array('hide' => $mod->id)),
1906 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1908 array('class' => 'editing_hide', 'data-action' => 'hide')
1911 $actions['show'] = new action_menu_link_primary(
1912 new moodle_url($baseurl, array('show' => $mod->id)),
1913 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1915 array('class' => 'editing_show', 'data-action' => 'show')
1921 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1922 if ($mod->coursegroupmodeforce) {
1923 $modgroupmode = $mod->coursegroupmode;
1925 $modgroupmode = $mod->groupmode;
1927 if ($modgroupmode == SEPARATEGROUPS) {
1928 $nextgroupmode = VISIBLEGROUPS;
1929 $grouptitle = $str->groupsseparate;
1930 $forcedgrouptitle = $str->forcedgroupsseparate;
1931 $actionname = 'groupsseparate';
1932 $groupimage = 't/groups';
1933 } else if ($modgroupmode == VISIBLEGROUPS) {
1934 $nextgroupmode = NOGROUPS;
1935 $grouptitle = $str->groupsvisible;
1936 $forcedgrouptitle = $str->forcedgroupsvisible;
1937 $actionname = 'groupsvisible';
1938 $groupimage = 't/groupv';
1940 $nextgroupmode = SEPARATEGROUPS;
1941 $grouptitle = $str->groupsnone;
1942 $forcedgrouptitle = $str->forcedgroupsnone;
1943 $actionname = 'groupsnone';
1944 $groupimage = 't/groupn';
1946 if (!$mod->coursegroupmodeforce) {
1947 $actions[$actionname] = new action_menu_link_primary(
1948 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1949 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1951 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode)
1954 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => '', 'class' => 'iconsmall'));
1959 if (has_capability('moodle/role:assign', $modcontext)){
1960 $actions['assign'] = new action_menu_link_secondary(
1961 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1962 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1964 array('class' => 'editing_assign', 'data-action' => 'assignroles')
1972 * given a course object with shortname & fullname, this function will
1973 * truncate the the number of chars allowed and add ... if it was too long
1975 function course_format_name ($course,$max=100) {
1977 $context = context_course::instance($course->id);
1978 $shortname = format_string($course->shortname, true, array('context' => $context));
1979 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1980 $str = $shortname.': '. $fullname;
1981 if (core_text::strlen($str) <= $max) {
1985 return core_text::substr($str,0,$max-3).'...';
1990 * Is the user allowed to add this type of module to this course?
1991 * @param object $course the course settings. Only $course->id is used.
1992 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
1993 * @return bool whether the current user is allowed to add this type of module to this course.
1995 function course_allowed_module($course, $modname) {
1996 if (is_numeric($modname)) {
1997 throw new coding_exception('Function course_allowed_module no longer
1998 supports numeric module ids. Please update your code to pass the module name.');
2001 $capability = 'mod/' . $modname . ':addinstance';
2002 if (!get_capability_info($capability)) {
2003 // Debug warning that the capability does not exist, but no more than once per page.
2004 static $warned = array();
2005 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2006 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2007 debugging('The module ' . $modname . ' does not define the standard capability ' .
2008 $capability , DEBUG_DEVELOPER);
2009 $warned[$modname] = 1;
2012 // If the capability does not exist, the module can always be added.
2016 $coursecontext = context_course::instance($course->id);
2017 return has_capability($capability, $coursecontext);
2021 * Efficiently moves many courses around while maintaining
2022 * sortorder in order.
2024 * @param array $courseids is an array of course ids
2025 * @param int $categoryid
2026 * @return bool success
2028 function move_courses($courseids, $categoryid) {
2031 if (empty($courseids)) {
2036 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2040 $courseids = array_reverse($courseids);
2041 $newparent = context_coursecat::instance($category->id);
2044 foreach ($courseids as $courseid) {
2045 if ($dbcourse = $DB->get_record('course', array('id' => $courseid))) {
2046 $course = new stdClass();
2047 $course->id = $courseid;
2048 $course->category = $category->id;
2049 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2050 if ($category->visible == 0) {
2051 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2052 // to previous state if somebody unhides the category.
2053 $course->visible = 0;
2056 $DB->update_record('course', $course);
2058 // Store the context.
2059 $context = context_course::instance($course->id);
2061 // Update the course object we are passing to the event.
2062 $dbcourse->category = $course->category;
2063 $dbcourse->sortorder = $course->sortorder;
2065 // Trigger a course updated event.
2066 $event = \core\event\course_updated::create(array(
2067 'objectid' => $course->id,
2068 'context' => $context,
2069 'other' => array('shortname' => $dbcourse->shortname,
2070 'fullname' => $dbcourse->fullname)
2072 $event->add_record_snapshot('course', $dbcourse);
2073 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2076 $context->update_moved($newparent);
2079 fix_course_sortorder();
2080 cache_helper::purge_by_event('changesincourse');
2086 * Returns the display name of the given section that the course prefers
2088 * Implementation of this function is provided by course format
2089 * @see format_base::get_section_name()
2091 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2092 * @param int|stdClass $section Section object from database or just field course_sections.section
2093 * @return string Display name that the course format prefers, e.g. "Week 2"
2095 function get_section_name($courseorid, $section) {
2096 return course_get_format($courseorid)->get_section_name($section);
2100 * Tells if current course format uses sections
2102 * @param string $format Course format ID e.g. 'weeks' $course->format
2105 function course_format_uses_sections($format) {
2106 $course = new stdClass();
2107 $course->format = $format;
2108 return course_get_format($course)->uses_sections();
2112 * Returns the information about the ajax support in the given source format
2114 * The returned object's property (boolean)capable indicates that
2115 * the course format supports Moodle course ajax features.
2116 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2118 * @param string $format
2121 function course_format_ajax_support($format) {
2122 $course = new stdClass();
2123 $course->format = $format;
2124 return course_get_format($course)->supports_ajax();
2128 * Can the current user delete this course?
2129 * Course creators have exception,
2130 * 1 day after the creation they can sill delete the course.
2131 * @param int $courseid
2134 function can_delete_course($courseid) {
2137 $context = context_course::instance($courseid);
2139 if (has_capability('moodle/course:delete', $context)) {
2143 // hack: now try to find out if creator created this course recently (1 day)
2144 if (!has_capability('moodle/course:create', $context)) {
2148 $since = time() - 60*60*24;
2150 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2151 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2153 return $DB->record_exists_select('log', $select, $params);
2157 * Save the Your name for 'Some role' strings.
2159 * @param integer $courseid the id of this course.
2160 * @param array $data the data that came from the course settings form.
2162 function save_local_role_names($courseid, $data) {
2164 $context = context_course::instance($courseid);
2166 foreach ($data as $fieldname => $value) {
2167 if (strpos($fieldname, 'role_') !== 0) {
2170 list($ignored, $roleid) = explode('_', $fieldname);
2172 // make up our mind whether we want to delete, update or insert
2174 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2176 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2177 $rolename->name = $value;
2178 $DB->update_record('role_names', $rolename);
2181 $rolename = new stdClass;
2182 $rolename->contextid = $context->id;
2183 $rolename->roleid = $roleid;
2184 $rolename->name = $value;
2185 $DB->insert_record('role_names', $rolename);
2191 * Returns options to use in course overviewfiles filemanager
2193 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2194 * may be empty if course does not exist yet (course create form)
2195 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2196 * or null if overviewfiles are disabled
2198 function course_overviewfiles_options($course) {
2200 if (empty($CFG->courseoverviewfileslimit)) {
2203 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2204 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2205 $accepted_types = '*';
2207 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2208 // Make sure extensions are prefixed with dot unless they are valid typegroups
2209 foreach ($accepted_types as $i => $type) {
2210 if (substr($type, 0, 1) !== '.') {
2211 require_once($CFG->libdir. '/filelib.php');
2212 if (!count(file_get_typegroup('extension', $type))) {
2213 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2214 $accepted_types[$i] = '.'. $type;
2219 if (!empty($corrected)) {
2220 set_config('courseoverviewfilesext', join(',', $accepted_types));
2224 'maxfiles' => $CFG->courseoverviewfileslimit,
2225 'maxbytes' => $CFG->maxbytes,
2227 'accepted_types' => $accepted_types
2229 if (!empty($course->id)) {
2230 $options['context'] = context_course::instance($course->id);
2231 } else if (is_int($course) && $course > 0) {
2232 $options['context'] = context_course::instance($course);
2238 * Create a course and either return a $course object
2240 * Please note this functions does not verify any access control,
2241 * the calling code is responsible for all validation (usually it is the form definition).
2243 * @param array $editoroptions course description editor options
2244 * @param object $data - all the data needed for an entry in the 'course' table
2245 * @return object new course instance
2247 function create_course($data, $editoroptions = NULL) {
2250 //check the categoryid - must be given for all new courses
2251 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2253 //check if the shortname already exist
2254 if (!empty($data->shortname)) {
2255 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2256 throw new moodle_exception('shortnametaken');
2260 //check if the id number already exist
2261 if (!empty($data->idnumber)) {
2262 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2263 throw new moodle_exception('idnumbertaken');
2267 $data->timecreated = time();
2268 $data->timemodified = $data->timecreated;
2270 // place at beginning of any category
2271 $data->sortorder = 0;
2273 if ($editoroptions) {
2274 // summary text is updated later, we need context to store the files first
2275 $data->summary = '';
2276 $data->summary_format = FORMAT_HTML;
2279 if (!isset($data->visible)) {
2280 // data not from form, add missing visibility info
2281 $data->visible = $category->visible;
2283 $data->visibleold = $data->visible;
2285 $newcourseid = $DB->insert_record('course', $data);
2286 $context = context_course::instance($newcourseid, MUST_EXIST);
2288 if ($editoroptions) {
2289 // Save the files used in the summary editor and store
2290 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2291 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2292 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2294 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2295 // Save the course overviewfiles
2296 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2299 // update course format options
2300 course_get_format($newcourseid)->update_course_format_options($data);
2302 $course = course_get_format($newcourseid)->get_course();
2305 blocks_add_default_course_blocks($course);
2307 // Create a default section.
2308 course_create_sections_if_missing($course, 0);
2310 fix_course_sortorder();
2311 // purge appropriate caches in case fix_course_sortorder() did not change anything
2312 cache_helper::purge_by_event('changesincourse');
2314 // new context created - better mark it as dirty
2315 $context->mark_dirty();
2317 // Save any custom role names.
2318 save_local_role_names($course->id, (array)$data);
2320 // set up enrolments
2321 enrol_course_updated(true, $course, $data);
2323 // Trigger a course created event.
2324 $event = \core\event\course_created::create(array(
2325 'objectid' => $course->id,
2326 'context' => context_course::instance($course->id),
2327 'other' => array('shortname' => $course->shortname,
2328 'fullname' => $course->fullname)
2330 $event->add_record_snapshot('course', $course);
2339 * Please note this functions does not verify any access control,
2340 * the calling code is responsible for all validation (usually it is the form definition).
2342 * @param object $data - all the data needed for an entry in the 'course' table
2343 * @param array $editoroptions course description editor options
2346 function update_course($data, $editoroptions = NULL) {
2349 $data->timemodified = time();
2351 $oldcourse = course_get_format($data->id)->get_course();
2352 $context = context_course::instance($oldcourse->id);
2354 if ($editoroptions) {
2355 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2357 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2358 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2361 if (!isset($data->category) or empty($data->category)) {
2362 // prevent nulls and 0 in category field
2363 unset($data->category);
2365 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2367 if (!isset($data->visible)) {
2368 // data not from form, add missing visibility info
2369 $data->visible = $oldcourse->visible;
2372 if ($data->visible != $oldcourse->visible) {
2373 // reset the visibleold flag when manually hiding/unhiding course
2374 $data->visibleold = $data->visible;
2375 $changesincoursecat = true;
2378 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2379 if (empty($newcategory->visible)) {
2380 // make sure when moving into hidden category the course is hidden automatically
2386 // Update with the new data
2387 $DB->update_record('course', $data);
2388 // make sure the modinfo cache is reset
2389 rebuild_course_cache($data->id);
2391 // update course format options with full course data
2392 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2394 $course = $DB->get_record('course', array('id'=>$data->id));
2397 $newparent = context_coursecat::instance($course->category);
2398 $context->update_moved($newparent);
2401 fix_course_sortorder();
2402 // purge appropriate caches in case fix_course_sortorder() did not change anything
2403 cache_helper::purge_by_event('changesincourse');
2404 if ($changesincoursecat) {
2405 cache_helper::purge_by_event('changesincoursecat');
2408 // Test for and remove blocks which aren't appropriate anymore
2409 blocks_remove_inappropriate($course);
2411 // Save any custom role names.
2412 save_local_role_names($course->id, $data);
2414 // update enrol settings
2415 enrol_course_updated(false, $course, $data);
2417 // Trigger a course updated event.
2418 $event = \core\event\course_updated::create(array(
2419 'objectid' => $course->id,
2420 'context' => $context,
2421 'other' => array('shortname' => $course->shortname,
2422 'fullname' => $course->fullname)
2424 $event->add_record_snapshot('course', $course);
2425 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2428 if ($oldcourse->format !== $course->format) {
2429 // Remove all options stored for the previous format
2430 // We assume that new course format migrated everything it needed watching trigger
2431 // 'course_updated' and in method format_XXX::update_course_format_options()
2432 $DB->delete_records('course_format_options',
2433 array('courseid' => $course->id, 'format' => $oldcourse->format));
2438 * Average number of participants
2441 function average_number_of_participants() {
2444 //count total of enrolments for visible course (except front page)
2445 $sql = 'SELECT COUNT(*) FROM (
2446 SELECT DISTINCT ue.userid, e.courseid
2447 FROM {user_enrolments} ue, {enrol} e, {course} c
2448 WHERE ue.enrolid = e.id
2449 AND e.courseid <> :siteid
2450 AND c.id = e.courseid
2451 AND c.visible = 1) total';
2452 $params = array('siteid' => $SITE->id);
2453 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2456 //count total of visible courses (minus front page)
2457 $coursetotal = $DB->count_records('course', array('visible' => 1));
2458 $coursetotal = $coursetotal - 1 ;
2460 //average of enrolment
2461 if (empty($coursetotal)) {
2462 $participantaverage = 0;
2464 $participantaverage = $enrolmenttotal / $coursetotal;
2467 return $participantaverage;
2471 * Average number of course modules
2474 function average_number_of_courses_modules() {
2477 //count total of visible course module (except front page)
2478 $sql = 'SELECT COUNT(*) FROM (
2479 SELECT cm.course, cm.module
2480 FROM {course} c, {course_modules} cm
2481 WHERE c.id = cm.course
2484 AND c.visible = 1) total';
2485 $params = array('siteid' => $SITE->id);
2486 $moduletotal = $DB->count_records_sql($sql, $params);
2489 //count total of visible courses (minus front page)
2490 $coursetotal = $DB->count_records('course', array('visible' => 1));
2491 $coursetotal = $coursetotal - 1 ;
2493 //average of course module
2494 if (empty($coursetotal)) {
2495 $coursemoduleaverage = 0;
2497 $coursemoduleaverage = $moduletotal / $coursetotal;
2500 return $coursemoduleaverage;
2504 * This class pertains to course requests and contains methods associated with
2505 * create, approving, and removing course requests.
2507 * Please note we do not allow embedded images here because there is no context
2508 * to store them with proper access control.
2510 * @copyright 2009 Sam Hemelryk
2511 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2514 * @property-read int $id
2515 * @property-read string $fullname
2516 * @property-read string $shortname
2517 * @property-read string $summary
2518 * @property-read int $summaryformat
2519 * @property-read int $summarytrust
2520 * @property-read string $reason
2521 * @property-read int $requester
2523 class course_request {
2526 * This is the stdClass that stores the properties for the course request
2527 * and is externally accessed through the __get magic method
2530 protected $properties;
2533 * An array of options for the summary editor used by course request forms.
2534 * This is initially set by {@link summary_editor_options()}
2538 protected static $summaryeditoroptions;
2541 * Static function to prepare the summary editor for working with a course
2545 * @param null|stdClass $data Optional, an object containing the default values
2546 * for the form, these may be modified when preparing the
2547 * editor so this should be called before creating the form
2548 * @return stdClass An object that can be used to set the default values for
2551 public static function prepare($data=null) {
2552 if ($data === null) {
2553 $data = new stdClass;
2555 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2560 * Static function to create a new course request when passed an array of properties
2563 * This function also handles saving any files that may have been used in the editor
2566 * @param stdClass $data
2567 * @return course_request The newly created course request
2569 public static function create($data) {
2570 global $USER, $DB, $CFG;
2571 $data->requester = $USER->id;
2573 // Setting the default category if none set.
2574 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2575 $data->category = $CFG->defaultrequestcategory;
2578 // Summary is a required field so copy the text over
2579 $data->summary = $data->summary_editor['text'];
2580 $data->summaryformat = $data->summary_editor['format'];
2582 $data->id = $DB->insert_record('course_request', $data);
2584 // Create a new course_request object and return it
2585 $request = new course_request($data);
2587 // Notify the admin if required.
2588 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2591 $a->link = "$CFG->wwwroot/course/pending.php";
2592 $a->user = fullname($USER);
2593 $subject = get_string('courserequest');
2594 $message = get_string('courserequestnotifyemail', 'admin', $a);
2595 foreach ($users as $user) {
2596 $request->notify($user, $USER, 'courserequested', $subject, $message);
2604 * Returns an array of options to use with a summary editor
2606 * @uses course_request::$summaryeditoroptions
2607 * @return array An array of options to use with the editor
2609 public static function summary_editor_options() {
2611 if (self::$summaryeditoroptions === null) {
2612 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2614 return self::$summaryeditoroptions;
2618 * Loads the properties for this course request object. Id is required and if
2619 * only id is provided then we load the rest of the properties from the database
2621 * @param stdClass|int $properties Either an object containing properties
2622 * or the course_request id to load
2624 public function __construct($properties) {
2626 if (empty($properties->id)) {
2627 if (empty($properties)) {
2628 throw new coding_exception('You must provide a course request id when creating a course_request object');
2631 $properties = new stdClass;
2632 $properties->id = (int)$id;
2635 if (empty($properties->requester)) {
2636 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2637 print_error('unknowncourserequest');
2640 $this->properties = $properties;
2642 $this->properties->collision = null;
2646 * Returns the requested property
2648 * @param string $key
2651 public function __get($key) {
2652 return $this->properties->$key;
2656 * Override this to ensure empty($request->blah) calls return a reliable answer...
2658 * This is required because we define the __get method
2661 * @return bool True is it not empty, false otherwise
2663 public function __isset($key) {
2664 return (!empty($this->properties->$key));
2668 * Returns the user who requested this course
2670 * Uses a static var to cache the results and cut down the number of db queries
2672 * @staticvar array $requesters An array of cached users
2673 * @return stdClass The user who requested the course
2675 public function get_requester() {
2677 static $requesters= array();
2678 if (!array_key_exists($this->properties->requester, $requesters)) {
2679 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2681 return $requesters[$this->properties->requester];
2685 * Checks that the shortname used by the course does not conflict with any other
2686 * courses that exist
2688 * @param string|null $shortnamemark The string to append to the requests shortname
2689 * should a conflict be found
2690 * @return bool true is there is a conflict, false otherwise
2692 public function check_shortname_collision($shortnamemark = '[*]') {
2695 if ($this->properties->collision !== null) {
2696 return $this->properties->collision;
2699 if (empty($this->properties->shortname)) {
2700 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2701 $this->properties->collision = false;
2702 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2703 if (!empty($shortnamemark)) {
2704 $this->properties->shortname .= ' '.$shortnamemark;
2706 $this->properties->collision = true;
2708 $this->properties->collision = false;
2710 return $this->properties->collision;
2714 * Returns the category where this course request should be created
2716 * Note that we don't check here that user has a capability to view
2717 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2718 * 'moodle/course:changecategory'
2722 public function get_category() {
2724 require_once($CFG->libdir.'/coursecatlib.php');
2725 // If the category is not set, if the current user does not have the rights to change the category, or if the
2726 // category does not exist, we set the default category to the course to be approved.
2727 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2728 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2729 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2730 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2733 $category = coursecat::get_default();
2739 * This function approves the request turning it into a course
2741 * This function converts the course request into a course, at the same time
2742 * transferring any files used in the summary to the new course and then removing
2743 * the course request and the files associated with it.
2745 * @return int The id of the course that was created from this request
2747 public function approve() {
2748 global $CFG, $DB, $USER;
2750 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2752 $courseconfig = get_config('moodlecourse');
2754 // Transfer appropriate settings
2755 $data = clone($this->properties);
2757 unset($data->reason);
2758 unset($data->requester);
2761 $category = $this->get_category();
2762 $data->category = $category->id;
2763 // Set misc settings
2764 $data->requested = 1;
2766 // Apply course default settings
2767 $data->format = $courseconfig->format;
2768 $data->newsitems = $courseconfig->newsitems;
2769 $data->showgrades = $courseconfig->showgrades;
2770 $data->showreports = $courseconfig->showreports;
2771 $data->maxbytes = $courseconfig->maxbytes;
2772 $data->groupmode = $courseconfig->groupmode;
2773 $data->groupmodeforce = $courseconfig->groupmodeforce;
2774 $data->visible = $courseconfig->visible;
2775 $data->visibleold = $data->visible;
2776 $data->lang = $courseconfig->lang;
2778 $course = create_course($data);
2779 $context = context_course::instance($course->id, MUST_EXIST);
2781 // add enrol instances
2782 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2783 if ($manual = enrol_get_plugin('manual')) {
2784 $manual->add_default_instance($course);
2788 // enrol the requester as teacher if necessary
2789 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2790 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2795 $a = new stdClass();
2796 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2797 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2798 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
2804 * Reject a course request
2806 * This function rejects a course request, emailing the requesting user the
2807 * provided notice and then removing the request from the database
2809 * @param string $notice The message to display to the user
2811 public function reject($notice) {
2813 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2814 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2819 * Deletes the course request and any associated files
2821 public function delete() {
2823 $DB->delete_records('course_request', array('id' => $this->properties->id));
2827 * Send a message from one user to another using events_trigger
2829 * @param object $touser
2830 * @param object $fromuser
2831 * @param string $name
2832 * @param string $subject
2833 * @param string $message
2835 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
2836 $eventdata = new stdClass();
2837 $eventdata->component = 'moodle';
2838 $eventdata->name = $name;
2839 $eventdata->userfrom = $fromuser;
2840 $eventdata->userto = $touser;
2841 $eventdata->subject = $subject;
2842 $eventdata->fullmessage = $message;
2843 $eventdata->fullmessageformat = FORMAT_PLAIN;
2844 $eventdata->fullmessagehtml = '';
2845 $eventdata->smallmessage = '';
2846 $eventdata->notification = 1;
2847 message_send($eventdata);
2852 * Return a list of page types
2853 * @param string $pagetype current page type
2854 * @param context $parentcontext Block's parent context
2855 * @param context $currentcontext Current context of block
2856 * @return array array of page types
2858 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2859 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2860 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2861 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2862 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2864 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2865 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2866 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2868 // Otherwise consider it a page inside a course even if $currentcontext is null
2869 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2870 'course-*' => get_string('page-course-x', 'pagetype'),
2871 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2878 * Determine whether course ajax should be enabled for the specified course
2880 * @param stdClass $course The course to test against
2881 * @return boolean Whether course ajax is enabled or note
2883 function course_ajax_enabled($course) {
2884 global $CFG, $PAGE, $SITE;
2886 // Ajax must be enabled globally
2887 if (!$CFG->enableajax) {
2891 // The user must be editing for AJAX to be included
2892 if (!$PAGE->user_is_editing()) {
2896 // Check that the theme suports
2897 if (!$PAGE->theme->enablecourseajax) {
2901 // Check that the course format supports ajax functionality
2902 // The site 'format' doesn't have information on course format support
2903 if ($SITE->id !== $course->id) {
2904 $courseformatajaxsupport = course_format_ajax_support($course->format);
2905 if (!$courseformatajaxsupport->capable) {
2910 // All conditions have been met so course ajax should be enabled
2915 * Include the relevant javascript and language strings for the resource
2916 * toolbox YUI module
2918 * @param integer $id The ID of the course being applied to
2919 * @param array $usedmodules An array containing the names of the modules in use on the page
2920 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
2921 * @param stdClass $config An object containing configuration parameters for ajax modules including:
2922 * * resourceurl The URL to post changes to for resource changes
2923 * * sectionurl The URL to post changes to for section changes
2924 * * pageparams Additional parameters to pass through in the post
2927 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
2928 global $PAGE, $SITE;
2930 // Ensure that ajax should be included
2931 if (!course_ajax_enabled($course)) {
2936 $config = new stdClass();
2939 // The URL to use for resource changes
2940 if (!isset($config->resourceurl)) {
2941 $config->resourceurl = '/course/rest.php';
2944 // The URL to use for section changes
2945 if (!isset($config->sectionurl)) {
2946 $config->sectionurl = '/course/rest.php';
2949 // Any additional parameters which need to be included on page submission
2950 if (!isset($config->pageparams)) {
2951 $config->pageparams = array();
2954 // Include toolboxes
2955 $PAGE->requires->yui_module('moodle-course-toolboxes',
2956 'M.course.init_resource_toolbox',
2958 'courseid' => $course->id,
2959 'ajaxurl' => $config->resourceurl,
2960 'config' => $config,
2963 $PAGE->requires->yui_module('moodle-course-toolboxes',
2964 'M.course.init_section_toolbox',
2966 'courseid' => $course->id,
2967 'format' => $course->format,
2968 'ajaxurl' => $config->sectionurl,
2969 'config' => $config,
2973 // Include course dragdrop
2974 if ($course->id != $SITE->id) {
2975 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
2977 'courseid' => $course->id,
2978 'ajaxurl' => $config->sectionurl,
2979 'config' => $config,
2982 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
2984 'courseid' => $course->id,
2985 'ajaxurl' => $config->resourceurl,
2986 'config' => $config,
2990 // Require various strings for the command toolbox
2991 $PAGE->requires->strings_for_js(array(
2994 'deletechecktypename',
2996 'edittitleinstructions',
3002 'clicktochangeinbrackets',
3009 'emptydragdropregion'
3012 // Include format-specific strings
3013 if ($course->id != $SITE->id) {
3014 $PAGE->requires->strings_for_js(array(
3017 ), 'format_' . $course->format);
3020 // For confirming resource deletion we need the name of the module in question
3021 foreach ($usedmodules as $module => $modname) {
3022 $PAGE->requires->string_for_js('pluginname', $module);
3025 // Load drag and drop upload AJAX.
3026 dndupload_add_to_course($course, $enabledmodules);
3032 * Returns the sorted list of available course formats, filtered by enabled if necessary
3034 * @param bool $enabledonly return only formats that are enabled
3035 * @return array array of sorted format names
3037 function get_sorted_course_formats($enabledonly = false) {
3039 $formats = core_component::get_plugin_list('format');
3041 if (!empty($CFG->format_plugins_sortorder)) {
3042 $order = explode(',', $CFG->format_plugins_sortorder);
3043 $order = array_merge(array_intersect($order, array_keys($formats)),
3044 array_diff(array_keys($formats), $order));
3046 $order = array_keys($formats);
3048 if (!$enabledonly) {
3051 $sortedformats = array();
3052 foreach ($order as $formatname) {
3053 if (!get_config('format_'.$formatname, 'disabled')) {
3054 $sortedformats[] = $formatname;
3057 return $sortedformats;
3061 * The URL to use for the specified course (with section)
3063 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3064 * @param int|stdClass $section Section object from database or just field course_sections.section
3065 * if omitted the course view page is returned
3066 * @param array $options options for view URL. At the moment core uses:
3067 * 'navigation' (bool) if true and section has no separate page, the function returns null
3068 * 'sr' (int) used by multipage formats to specify to which section to return
3069 * @return moodle_url The url of course
3071 function course_get_url($courseorid, $section = null, $options = array()) {
3072 return course_get_format($courseorid)->get_view_url($section, $options);
3079 * - capability checks and other checks
3080 * - create the module from the module info
3082 * @param object $module
3083 * @return object the created module info
3085 function create_module($moduleinfo) {
3088 require_once($CFG->dirroot . '/course/modlib.php');
3090 // Check manadatory attributs.
3091 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3092 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3093 $mandatoryfields[] = 'introeditor';
3095 foreach($mandatoryfields as $mandatoryfield) {
3096 if (!isset($moduleinfo->{$mandatoryfield})) {
3097 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3101 // Some additional checks (capability / existing instances).
3102 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3103 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3105 // Load module library.
3106 include_modulelib($module->name);
3109 $moduleinfo->module = $module->id;
3110 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3119 * - capability and other checks
3120 * - update the module
3122 * @param object $module
3123 * @return object the updated module info
3125 function update_module($moduleinfo) {
3128 require_once($CFG->dirroot . '/course/modlib.php');
3130 // Check the course module exists.
3131 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3133 // Check the course exists.
3134 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3136 // Some checks (capaibility / existing instances).
3137 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3139 // Load module library.
3140 include_modulelib($module->name);
3142 // Retrieve few information needed by update_moduleinfo.
3143 $moduleinfo->modulename = $cm->modname;
3144 if (!isset($moduleinfo->scale)) {
3145 $moduleinfo->scale = 0;
3147 $moduleinfo->type = 'mod';
3149 // Update the module.
3150 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3156 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3157 * Sorts by descending order of time.
3159 * @param stdClass $a First object
3160 * @param stdClass $b Second object
3161 * @return int 0,1,-1 representing the order
3163 function compare_activities_by_time_desc($a, $b) {
3164 // Make sure the activities actually have a timestamp property.
3165 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3168 // We treat instances without timestamp as if they have a timestamp of 0.
3169 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3172 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3175 if ($a->timestamp == $b->timestamp) {
3178 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3182 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3183 * Sorts by ascending order of time.
3185 * @param stdClass $a First object
3186 * @param stdClass $b Second object
3187 * @return int 0,1,-1 representing the order
3189 function compare_activities_by_time_asc($a, $b) {
3190 // Make sure the activities actually have a timestamp property.
3191 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3194 // We treat instances without timestamp as if they have a timestamp of 0.
3195 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3198 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3201 if ($a->timestamp == $b->timestamp) {
3204 return ($a->timestamp < $b->timestamp) ? -1 : 1;