Merge branch '41997-25' of git://github.com/samhemelryk/moodle into MOODLE_25_STABLE
[moodle.git] / course / lib.php
blobf31e2e28c650a29cf49d9e801bbdbfc25e97f739
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
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
23 * @package core
24 * @subpackage course
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
37 /**
38 * Number of courses to display when summaries are included.
39 * @var int
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) {
62 switch ($module) {
63 case 'course':
64 if (strpos($url, 'report/') === 0) {
65 // there is only one report type, course reports are deprecated
66 $url = "/$url";
67 break;
69 case 'file':
70 case 'login':
71 case 'lib':
72 case 'admin':
73 case 'calendar':
74 case 'category':
75 case 'mnet course':
76 if (strpos($url, '../') === 0) {
77 $url = ltrim($url, '.');
78 } else {
79 $url = "/course/$url";
81 break;
82 case 'user':
83 case 'blog':
84 $url = "/$module/$url";
85 break;
86 case 'upload':
87 $url = $url;
88 break;
89 case 'coursetags':
90 $url = '/'.$url;
91 break;
92 case 'library':
93 case '':
94 $url = '/';
95 break;
96 case 'message':
97 $url = "/message/$url";
98 break;
99 case 'notes':
100 $url = "/notes/$url";
101 break;
102 case 'tag':
103 $url = "/tag/$url";
104 break;
105 case 'role':
106 $url = '/'.$url;
107 break;
108 case 'grade':
109 $url = "/grade/$url";
110 break;
111 default:
112 $url = "/mod/$module/$url";
113 break;
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);
121 } else {
122 $script = clean_param($script, PARAM_PATH);
125 $query = '';
126 if ($parts) {
127 $query = implode('', $parts);
128 $query = str_replace('&amp;', '&', $query); // both & and &amp; 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('&amp;', $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) {
145 global $CFG, $DB;
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) {
163 // $groupid = 0;
166 $groupid = 0;
168 $joins = array();
169 $where = '';
171 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
172 FROM {mnet_log} l
173 LEFT JOIN {user} u ON l.userid = u.id
174 WHERE ";
175 $params = array();
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;
186 if ($modname) {
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' )";
193 } else if ($modid) {
194 //TODO: This assumes that modids are the same across sites... probably
195 //not true
196 $where .= " AND l.cmid = :modid";
197 $params['modid'] = $modid;
200 if ($modaction) {
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).'%';
205 } else {
206 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
207 $params['modaction'] = '%'.$modaction.'%';
211 if ($user) {
212 $where .= " AND l.userid = :user";
213 $params['user'] = $user;
216 if ($date) {
217 $enddate = $date + 86400;
218 $where .= " AND l.time > :date AND l.time < :enddate";
219 $params['date'] = $date;
220 $params['enddate'] = $enddate;
223 $result = array();
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);
228 } else {
229 $result['logs'] = array();
231 return $result;
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];
247 } else {
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;
252 } else {
253 $groupid = 0;
257 /// If this course doesn't have groups, no groupid can be specified.
258 else if (!$course->groupmode) {
259 $groupid = 0;
262 $joins = array();
263 $params = array();
265 if ($course->id != SITEID || $modid != 0) {
266 $joins[] = "l.course = :courseid";
267 $params['courseid'] = $course->id;
270 if ($modname) {
271 $joins[] = "l.module = :modname";
272 $params['modname'] = $modname;
275 if ('site_errors' === $modid) {
276 $joins[] = "( l.action='error' OR l.action='infected' )";
277 } else if ($modid) {
278 $joins[] = "l.cmid = :modid";
279 $params['modid'] = $modid;
282 if ($modaction) {
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).'%';
287 } else {
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) . ')';
299 } else {
300 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
303 else if ($user) {
304 $joins[] = "l.userid = :userid";
305 $params['userid'] = $user;
308 if ($date) {
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
318 $result = array();
319 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
320 $result['totalcount'] = $totalcount;
321 return $result;
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();
334 exit;
337 $courses = array();
339 if ($course->id == SITEID) {
340 $courses[0] = '';
341 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
342 foreach ($ccc as $cc) {
343 $courses[$cc->id] = $cc->shortname;
346 } else {
347 $courses[$course->id] = $course->shortname;
350 $totalcount = $logs['totalcount'];
351 $count=0;
352 $ldcache = array();
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);
360 echo "</div>\n";
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(
368 get_string('time'),
369 get_string('ip_address'),
370 get_string('fullnameuser'),
371 get_string('action'),
372 get_string('info')
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];
390 } else {
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);
398 } else {
399 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
403 //Filter 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=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
410 $row = array();
411 if ($course->id == SITEID) {
412 if (empty($log->course)) {
413 $row[] = get_string('site');
414 } else {
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";
427 if ($brokenurl) {
428 $row[] = $displayaction;
429 } else {
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));
433 $row[] = $log->info;
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();
451 exit;
454 if ($course->id == SITEID) {
455 $courses[0] = '';
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'];
464 $count=0;
465 $ldcache = array();
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);
473 echo "</div>\n";
475 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
477 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
478 echo "<tr>";
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";
487 echo "</tr>\n";
489 if (empty($logs['logs'])) {
490 echo "</table>\n";
491 return;
494 $row = 1;
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];
502 } else {
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);
510 } else {
511 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
515 //Filter 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";
523 echo "</td>\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)));
530 echo "</td>\n";
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";
534 echo "</td>\n";
535 echo "<td class=\"r$row c4\">\n";
536 echo $log->action .': '.$log->module;
537 echo "</td>\n";
538 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
539 echo "</tr>\n";
541 echo "</table>\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) {
549 global $DB, $CFG;
551 require_once($CFG->libdir . '/csvlib.class.php');
553 $csvexporter = new csv_export_writer('tab');
555 $header = array();
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)) {
565 return false;
568 $courses = array();
570 if ($course->id == SITEID) {
571 $courses[0] = '';
572 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
573 foreach ($ccc as $cc) {
574 $courses[$cc->id] = $cc->shortname;
577 } else {
578 $courses[$course->id] = $course->shortname;
581 $count=0;
582 $ldcache = array();
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'])) {
594 return true;
597 foreach ($logs['logs'] as $log) {
598 if (isset($ldcache[$log->module][$log->action])) {
599 $ld = $ldcache[$log->module][$log->action];
600 } else {
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);
608 } else {
609 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
613 //Filter 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();
625 return true;
629 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
630 $modid, $modaction, $groupid) {
632 global $CFG, $DB;
634 require_once("$CFG->libdir/excellib.class.php");
636 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
637 $modname, $modid, $modaction, $groupid)) {
638 return false;
641 $courses = array();
643 if ($course->id == SITEID) {
644 $courses[0] = '';
645 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
646 foreach ($ccc as $cc) {
647 $courses[$cc->id] = $cc->shortname;
650 } else {
651 $courses[$course->id] = $course->shortname;
654 $count=0;
655 $ldcache = array();
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);
663 $filename .= '.xls';
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));
679 $col = 0;
680 foreach ($headers as $item) {
681 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
682 $col++;
686 if (empty($logs['logs'])) {
687 $workbook->close();
688 return true;
691 $formatDate =& $workbook->add_format();
692 $formatDate->set_num_format(get_string('log_excel_date_format'));
694 $row = FIRSTUSEDEXCELROW;
695 $wsnumber = 1;
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];
700 } else {
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);
708 } else {
709 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
713 // Filter log->info
714 $log->info = format_string($log->info);
715 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
717 if ($nroPages>1) {
718 if ($row > EXCELROWS) {
719 $wsnumber++;
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, '');
736 $row++;
739 $workbook->close();
740 return true;
743 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
744 $modid, $modaction, $groupid) {
746 global $CFG, $DB;
748 require_once("$CFG->libdir/odslib.class.php");
750 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
751 $modname, $modid, $modaction, $groupid)) {
752 return false;
755 $courses = array();
757 if ($course->id == SITEID) {
758 $courses[0] = '';
759 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
760 foreach ($ccc as $cc) {
761 $courses[$cc->id] = $cc->shortname;
764 } else {
765 $courses[$course->id] = $course->shortname;
768 $count=0;
769 $ldcache = array();
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);
777 $filename .= '.ods';
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));
793 $col = 0;
794 foreach ($headers as $item) {
795 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
796 $col++;
800 if (empty($logs['logs'])) {
801 $workbook->close();
802 return true;
805 $formatDate =& $workbook->add_format();
806 $formatDate->set_num_format(get_string('log_excel_date_format'));
808 $row = FIRSTUSEDEXCELROW;
809 $wsnumber = 1;
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];
814 } else {
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);
822 } else {
823 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
827 // Filter log->info
828 $log->info = format_string($log->info);
829 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
831 if ($nroPages>1) {
832 if ($row > EXCELROWS) {
833 $wsnumber++;
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);
850 $row++;
853 $workbook->close();
854 return true;
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
870 global $CFG, $DB;
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');
881 $mod = array();
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])) {
894 continue;
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")) {
936 continue;
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 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
963 $url = new moodle_url($info->iconurl);
964 $mod[$seq]->iconurl = $url->out(false);
966 if (!empty($info->onclick)) {
967 $mod[$seq]->onclick = $info->onclick;
969 if (!empty($info->customdata)) {
970 $mod[$seq]->customdata = $info->customdata;
972 } else {
973 // When using a stdclass, the (horrible) deprecated ->extra field
974 // is available for BC
975 if (!empty($info->extra)) {
976 $mod[$seq]->extra = $info->extra;
981 // When there is no modname_get_coursemodule_info function,
982 // but showdescriptions is enabled, then we use the 'intro'
983 // and 'introformat' fields in the module table
984 if (!$hasfunction && $rawmods[$seq]->showdescription) {
985 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
986 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
987 // Set content from intro and introformat. Filters are disabled
988 // because we filter it with format_text at display time
989 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
990 $modvalues, $rawmods[$seq]->id, false);
992 // To save making another query just below, put name in here
993 $mod[$seq]->name = $modvalues->name;
996 if (!isset($mod[$seq]->name)) {
997 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1000 // Minimise the database size by unsetting default options when they are
1001 // 'empty'. This list corresponds to code in the cm_info constructor.
1002 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1003 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1004 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1005 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1006 'completionview', 'completionexpected', 'score', 'showdescription')
1007 as $property) {
1008 if (property_exists($mod[$seq], $property) &&
1009 empty($mod[$seq]->{$property})) {
1010 unset($mod[$seq]->{$property});
1013 // Special case: this value is usually set to null, but may be 0
1014 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1015 is_null($mod[$seq]->completiongradeitemnumber)) {
1016 unset($mod[$seq]->completiongradeitemnumber);
1022 return $mod;
1026 * Returns the localised human-readable names of all used modules
1028 * @param bool $plural if true returns the plural forms of the names
1029 * @return array where key is the module name (component name without 'mod_') and
1030 * the value is the human-readable string. Array sorted alphabetically by value
1032 function get_module_types_names($plural = false) {
1033 static $modnames = null;
1034 global $DB, $CFG;
1035 if ($modnames === null) {
1036 $modnames = array(0 => array(), 1 => array());
1037 if ($allmods = $DB->get_records("modules")) {
1038 foreach ($allmods as $mod) {
1039 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1040 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1041 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1044 collatorlib::asort($modnames[0]);
1045 collatorlib::asort($modnames[1]);
1048 return $modnames[(int)$plural];
1052 * Set highlighted section. Only one section can be highlighted at the time.
1054 * @param int $courseid course id
1055 * @param int $marker highlight section with this number, 0 means remove higlightin
1056 * @return void
1058 function course_set_marker($courseid, $marker) {
1059 global $DB;
1060 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1061 format_base::reset_course_cache($courseid);
1065 * For a given course section, marks it visible or hidden,
1066 * and does the same for every activity in that section
1068 * @param int $courseid course id
1069 * @param int $sectionnumber The section number to adjust
1070 * @param int $visibility The new visibility
1071 * @return array A list of resources which were hidden in the section
1073 function set_section_visible($courseid, $sectionnumber, $visibility) {
1074 global $DB;
1076 $resourcestotoggle = array();
1077 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1078 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1079 if (!empty($section->sequence)) {
1080 $modules = explode(",", $section->sequence);
1081 foreach ($modules as $moduleid) {
1082 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1083 if ($visibility) {
1084 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1085 set_coursemodule_visible($moduleid, $cm->visibleold);
1086 } else {
1087 // We hide the section, so we hide the module but we store the original state in visibleold.
1088 set_coursemodule_visible($moduleid, 0);
1089 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1094 rebuild_course_cache($courseid, true);
1096 // Determine which modules are visible for AJAX update
1097 if (!empty($modules)) {
1098 list($insql, $params) = $DB->get_in_or_equal($modules);
1099 $select = 'id ' . $insql . ' AND visible = ?';
1100 array_push($params, $visibility);
1101 if (!$visibility) {
1102 $select .= ' AND visibleold = 1';
1104 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1107 return $resourcestotoggle;
1111 * Retrieve all metadata for the requested modules
1113 * @param object $course The Course
1114 * @param array $modnames An array containing the list of modules and their
1115 * names
1116 * @param int $sectionreturn The section to return to
1117 * @return array A list of stdClass objects containing metadata about each
1118 * module
1120 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1121 global $CFG, $OUTPUT;
1123 // get_module_metadata will be called once per section on the page and courses may show
1124 // different modules to one another
1125 static $modlist = array();
1126 if (!isset($modlist[$course->id])) {
1127 $modlist[$course->id] = array();
1130 $return = array();
1131 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1132 if ($sectionreturn !== null) {
1133 $urlbase->param('sr', $sectionreturn);
1135 foreach($modnames as $modname => $modnamestr) {
1136 if (!course_allowed_module($course, $modname)) {
1137 continue;
1139 if (isset($modlist[$course->id][$modname])) {
1140 // This module is already cached
1141 $return[$modname] = $modlist[$course->id][$modname];
1142 continue;
1145 // Include the module lib
1146 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1147 if (!file_exists($libfile)) {
1148 continue;
1150 include_once($libfile);
1152 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1153 $gettypesfunc = $modname.'_get_types';
1154 if (function_exists($gettypesfunc)) {
1155 $types = $gettypesfunc();
1156 if (is_array($types) && count($types) > 0) {
1157 $group = new stdClass();
1158 $group->name = $modname;
1159 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1160 foreach($types as $type) {
1161 if ($type->typestr === '--') {
1162 continue;
1164 if (strpos($type->typestr, '--') === 0) {
1165 $group->title = str_replace('--', '', $type->typestr);
1166 continue;
1168 // Set the Sub Type metadata
1169 $subtype = new stdClass();
1170 $subtype->title = $type->typestr;
1171 $subtype->type = str_replace('&amp;', '&', $type->type);
1172 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1173 $subtype->archetype = $type->modclass;
1175 // The group archetype should match the subtype archetypes and all subtypes
1176 // should have the same archetype
1177 $group->archetype = $subtype->archetype;
1179 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1180 $subtype->help = get_string('help' . $subtype->name, $modname);
1182 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1183 $group->types[] = $subtype;
1185 $modlist[$course->id][$modname] = $group;
1187 } else {
1188 $module = new stdClass();
1189 $module->title = $modnamestr;
1190 $module->name = $modname;
1191 $module->link = new moodle_url($urlbase, array('add' => $modname));
1192 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1193 $sm = get_string_manager();
1194 if ($sm->string_exists('modulename_help', $modname)) {
1195 $module->help = get_string('modulename_help', $modname);
1196 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1197 $link = get_string('modulename_link', $modname);
1198 $linktext = get_string('morehelp');
1199 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1202 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1203 $modlist[$course->id][$modname] = $module;
1205 if (isset($modlist[$course->id][$modname])) {
1206 $return[$modname] = $modlist[$course->id][$modname];
1207 } else {
1208 debugging("Invalid module metadata configuration for {$modname}");
1212 return $return;
1216 * Return the course category context for the category with id $categoryid, except
1217 * that if $categoryid is 0, return the system context.
1219 * @param integer $categoryid a category id or 0.
1220 * @return object the corresponding context
1222 function get_category_or_system_context($categoryid) {
1223 if ($categoryid) {
1224 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1225 } else {
1226 return context_system::instance();
1231 * Returns full course categories trees to be used in html_writer::select()
1233 * Calls {@link coursecat::make_categories_list()} to build the tree and
1234 * adds whitespace to denote nesting
1236 * @return array array mapping coursecat id to the display name
1238 function make_categories_options() {
1239 global $CFG;
1240 require_once($CFG->libdir. '/coursecatlib.php');
1241 $cats = coursecat::make_categories_list('', 0, ' / ');
1242 foreach ($cats as $key => $value) {
1243 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
1244 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
1246 return $cats;
1250 * Print the buttons relating to course requests.
1252 * @param object $context current page context.
1254 function print_course_request_buttons($context) {
1255 global $CFG, $DB, $OUTPUT;
1256 if (empty($CFG->enablecourserequests)) {
1257 return;
1259 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1260 /// Print a button to request a new course
1261 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1263 /// Print a button to manage pending requests
1264 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1265 $disabled = !$DB->record_exists('course_request', array());
1266 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1271 * Does the user have permission to edit things in this category?
1273 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1274 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1276 function can_edit_in_category($categoryid = 0) {
1277 $context = get_category_or_system_context($categoryid);
1278 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1281 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1283 function add_course_module($mod) {
1284 global $DB;
1286 $mod->added = time();
1287 unset($mod->id);
1289 $cmid = $DB->insert_record("course_modules", $mod);
1290 rebuild_course_cache($mod->course, true);
1291 return $cmid;
1295 * Creates missing course section(s) and rebuilds course cache
1297 * @param int|stdClass $courseorid course id or course object
1298 * @param int|array $sections list of relative section numbers to create
1299 * @return bool if there were any sections created
1301 function course_create_sections_if_missing($courseorid, $sections) {
1302 global $DB;
1303 if (!is_array($sections)) {
1304 $sections = array($sections);
1306 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1307 if (is_object($courseorid)) {
1308 $courseorid = $courseorid->id;
1310 $coursechanged = false;
1311 foreach ($sections as $sectionnum) {
1312 if (!in_array($sectionnum, $existing)) {
1313 $cw = new stdClass();
1314 $cw->course = $courseorid;
1315 $cw->section = $sectionnum;
1316 $cw->summary = '';
1317 $cw->summaryformat = FORMAT_HTML;
1318 $cw->sequence = '';
1319 $id = $DB->insert_record("course_sections", $cw);
1320 $coursechanged = true;
1323 if ($coursechanged) {
1324 rebuild_course_cache($courseorid, true);
1326 return $coursechanged;
1330 * Adds an existing module to the section
1332 * Updates both tables {course_sections} and {course_modules}
1334 * Note: This function does not use modinfo PROVIDED that the section you are
1335 * adding the module to already exists. If the section does not exist, it will
1336 * build modinfo if necessary and create the section.
1338 * @param int|stdClass $courseorid course id or course object
1339 * @param int $cmid id of the module already existing in course_modules table
1340 * @param int $sectionnum relative number of the section (field course_sections.section)
1341 * If section does not exist it will be created
1342 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1343 * before which the module needs to be included. Null for inserting in the
1344 * end of the section
1345 * @return int The course_sections ID where the module is inserted
1347 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1348 global $DB, $COURSE;
1349 if (is_object($beforemod)) {
1350 $beforemod = $beforemod->id;
1352 if (is_object($courseorid)) {
1353 $courseid = $courseorid->id;
1354 } else {
1355 $courseid = $courseorid;
1357 // Do not try to use modinfo here, there is no guarantee it is valid!
1358 $section = $DB->get_record('course_sections',
1359 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
1360 if (!$section) {
1361 // This function call requires modinfo.
1362 course_create_sections_if_missing($courseorid, $sectionnum);
1363 $section = $DB->get_record('course_sections',
1364 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
1367 $modarray = explode(",", trim($section->sequence));
1368 if (empty($section->sequence)) {
1369 $newsequence = "$cmid";
1370 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1371 $insertarray = array($cmid, $beforemod);
1372 array_splice($modarray, $key[0], 1, $insertarray);
1373 $newsequence = implode(",", $modarray);
1374 } else {
1375 $newsequence = "$section->sequence,$cmid";
1377 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1378 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1379 if (is_object($courseorid)) {
1380 rebuild_course_cache($courseorid->id, true);
1381 } else {
1382 rebuild_course_cache($courseorid, true);
1384 return $section->id; // Return course_sections ID that was used.
1387 function set_coursemodule_groupmode($id, $groupmode) {
1388 global $DB;
1389 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1390 if ($cm->groupmode != $groupmode) {
1391 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1392 rebuild_course_cache($cm->course, true);
1394 return ($cm->groupmode != $groupmode);
1397 function set_coursemodule_idnumber($id, $idnumber) {
1398 global $DB;
1399 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1400 if ($cm->idnumber != $idnumber) {
1401 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1402 rebuild_course_cache($cm->course, true);
1404 return ($cm->idnumber != $idnumber);
1408 * Set the visibility of a module and inherent properties.
1410 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1411 * has been moved to {@link set_section_visible()} which was the only place from which
1412 * the parameter was used.
1414 * @param int $id of the module
1415 * @param int $visible state of the module
1416 * @return bool false when the module was not found, true otherwise
1418 function set_coursemodule_visible($id, $visible) {
1419 global $DB, $CFG;
1420 require_once($CFG->libdir.'/gradelib.php');
1422 // Trigger developer's attention when using the previously removed argument.
1423 if (func_num_args() > 2) {
1424 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1425 has been removed.', DEBUG_DEVELOPER);
1428 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1429 return false;
1432 // Create events and propagate visibility to associated grade items if the value has changed.
1433 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1434 if ($cm->visible == $visible) {
1435 return true;
1438 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1439 return false;
1441 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1442 foreach($events as $event) {
1443 if ($visible) {
1444 show_event($event);
1445 } else {
1446 hide_event($event);
1451 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1452 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1453 if ($grade_items) {
1454 foreach ($grade_items as $grade_item) {
1455 $grade_item->set_hidden(!$visible);
1459 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1460 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1461 $cminfo = new stdClass();
1462 $cminfo->id = $id;
1463 $cminfo->visible = $visible;
1464 $cminfo->visibleold = $visible;
1465 $DB->update_record('course_modules', $cminfo);
1467 rebuild_course_cache($cm->course, true);
1468 return true;
1472 * This function will handles the whole deletion process of a module. This includes calling
1473 * the modules delete_instance function, deleting files, events, grades, conditional data,
1474 * the data in the course_module and course_sections table and adding a module deletion
1475 * event to the DB.
1477 * @param int $cmid the course module id
1478 * @since 2.5
1480 function course_delete_module($cmid) {
1481 global $CFG, $DB, $USER;
1483 require_once($CFG->libdir.'/gradelib.php');
1484 require_once($CFG->dirroot.'/blog/lib.php');
1486 // Get the course module.
1487 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1488 return true;
1491 // Get the module context.
1492 $modcontext = context_module::instance($cm->id);
1494 // Get the course module name.
1495 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1497 // Get the file location of the delete_instance function for this module.
1498 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1500 // Include the file required to call the delete_instance function for this module.
1501 if (file_exists($modlib)) {
1502 require_once($modlib);
1503 } else {
1504 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1505 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1508 $deleteinstancefunction = $modulename . '_delete_instance';
1510 // Ensure the delete_instance function exists for this module.
1511 if (!function_exists($deleteinstancefunction)) {
1512 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1513 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1516 // Call the delete_instance function, if it returns false throw an exception.
1517 if (!$deleteinstancefunction($cm->instance)) {
1518 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1519 "Cannot delete the module $modulename (instance).");
1522 // Remove all module files in case modules forget to do that.
1523 $fs = get_file_storage();
1524 $fs->delete_area_files($modcontext->id);
1526 // Delete events from calendar.
1527 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1528 foreach($events as $event) {
1529 delete_event($event->id);
1533 // Delete grade items, outcome items and grades attached to modules.
1534 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1535 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1536 foreach ($grade_items as $grade_item) {
1537 $grade_item->delete('moddelete');
1541 // Delete completion and availability data; it is better to do this even if the
1542 // features are not turned on, in case they were turned on previously (these will be
1543 // very quick on an empty table).
1544 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1545 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
1546 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
1547 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1548 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1550 // Delete the context.
1551 delete_context(CONTEXT_MODULE, $cm->id);
1553 // Delete the module from the course_modules table.
1554 $DB->delete_records('course_modules', array('id' => $cm->id));
1556 // Delete module from that section.
1557 if (!delete_mod_from_section($cm->id, $cm->section)) {
1558 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1559 "Cannot delete the module $modulename (instance) from section.");
1562 // Trigger a mod_deleted event with information about this module.
1563 $eventdata = new stdClass();
1564 $eventdata->modulename = $modulename;
1565 $eventdata->cmid = $cm->id;
1566 $eventdata->courseid = $cm->course;
1567 $eventdata->userid = $USER->id;
1568 events_trigger('mod_deleted', $eventdata);
1570 add_to_log($cm->course, 'course', "delete mod",
1571 "view.php?id=$cm->course",
1572 "$modulename $cm->instance", $cm->id);
1574 rebuild_course_cache($cm->course, true);
1577 function delete_mod_from_section($modid, $sectionid) {
1578 global $DB;
1580 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1582 $modarray = explode(",", $section->sequence);
1584 if ($key = array_keys ($modarray, $modid)) {
1585 array_splice($modarray, $key[0], 1);
1586 $newsequence = implode(",", $modarray);
1587 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1588 rebuild_course_cache($section->course, true);
1589 return true;
1590 } else {
1591 return false;
1595 return false;
1599 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
1601 * @param object $course course object
1602 * @param int $section Section number (not id!!!)
1603 * @param int $move (-1 or 1)
1604 * @return boolean true if section moved successfully
1605 * @todo MDL-33379 remove this function in 2.5
1607 function move_section($course, $section, $move) {
1608 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
1610 /// Moves a whole course section up and down within the course
1611 global $USER;
1613 if (!$move) {
1614 return true;
1617 $sectiondest = $section + $move;
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 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
1623 return false;
1626 $retval = move_section_to($course, $section, $sectiondest);
1627 return $retval;
1631 * Moves a section within a course, from a position to another.
1632 * Be very careful: $section and $destination refer to section number,
1633 * not id!.
1635 * @param object $course
1636 * @param int $section Section number (not id!!!)
1637 * @param int $destination
1638 * @return boolean Result
1640 function move_section_to($course, $section, $destination) {
1641 /// Moves a whole course section up and down within the course
1642 global $USER, $DB;
1644 if (!$destination && $destination != 0) {
1645 return true;
1648 // compartibility with course formats using field 'numsections'
1649 $courseformatoptions = course_get_format($course)->get_format_options();
1650 if ((array_key_exists('numsections', $courseformatoptions) &&
1651 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1652 return false;
1655 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1656 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1657 'section ASC, id ASC', 'id, section')) {
1658 return false;
1661 $movedsections = reorder_sections($sections, $section, $destination);
1663 // Update all sections. Do this in 2 steps to avoid breaking database
1664 // uniqueness constraint
1665 $transaction = $DB->start_delegated_transaction();
1666 foreach ($movedsections as $id => $position) {
1667 if ($sections[$id] !== $position) {
1668 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1671 foreach ($movedsections as $id => $position) {
1672 if ($sections[$id] !== $position) {
1673 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1677 // If we move the highlighted section itself, then just highlight the destination.
1678 // Adjust the higlighted section location if we move something over it either direction.
1679 if ($section == $course->marker) {
1680 course_set_marker($course->id, $destination);
1681 } elseif ($section > $course->marker && $course->marker >= $destination) {
1682 course_set_marker($course->id, $course->marker+1);
1683 } elseif ($section < $course->marker && $course->marker <= $destination) {
1684 course_set_marker($course->id, $course->marker-1);
1687 $transaction->allow_commit();
1688 rebuild_course_cache($course->id, true);
1689 return true;
1693 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1694 * an original position number and a target position number, rebuilds the array so that the
1695 * move is made without any duplication of section positions.
1696 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1697 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1699 * @param array $sections
1700 * @param int $origin_position
1701 * @param int $target_position
1702 * @return array
1704 function reorder_sections($sections, $origin_position, $target_position) {
1705 if (!is_array($sections)) {
1706 return false;
1709 // We can't move section position 0
1710 if ($origin_position < 1) {
1711 echo "We can't move section position 0";
1712 return false;
1715 // Locate origin section in sections array
1716 if (!$origin_key = array_search($origin_position, $sections)) {
1717 echo "searched position not in sections array";
1718 return false; // searched position not in sections array
1721 // Extract origin section
1722 $origin_section = $sections[$origin_key];
1723 unset($sections[$origin_key]);
1725 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1726 $found = false;
1727 $append_array = array();
1728 foreach ($sections as $id => $position) {
1729 if ($found) {
1730 $append_array[$id] = $position;
1731 unset($sections[$id]);
1733 if ($position == $target_position) {
1734 if ($target_position < $origin_position) {
1735 $append_array[$id] = $position;
1736 unset($sections[$id]);
1738 $found = true;
1742 // Append moved section
1743 $sections[$origin_key] = $origin_section;
1745 // Append rest of array (if applicable)
1746 if (!empty($append_array)) {
1747 foreach ($append_array as $id => $position) {
1748 $sections[$id] = $position;
1752 // Renumber positions
1753 $position = 0;
1754 foreach ($sections as $id => $p) {
1755 $sections[$id] = $position;
1756 $position++;
1759 return $sections;
1764 * Move the module object $mod to the specified $section
1765 * If $beforemod exists then that is the module
1766 * before which $modid should be inserted
1767 * All parameters are objects
1769 function moveto_module($mod, $section, $beforemod=NULL) {
1770 global $OUTPUT, $DB;
1772 /// Remove original module from original section
1773 if (! delete_mod_from_section($mod->id, $mod->section)) {
1774 echo $OUTPUT->notification("Could not delete module from existing section");
1777 // if moving to a hidden section then hide module
1778 if ($mod->section != $section->id) {
1779 if (!$section->visible && $mod->visible) {
1780 // Set this in the object because it is sent as a response to ajax calls.
1781 $mod->visible = 0;
1782 set_coursemodule_visible($mod->id, 0);
1783 // Set visibleold to 1 so module will be visible when section is made visible.
1784 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1786 if ($section->visible && !$mod->visible) {
1787 set_coursemodule_visible($mod->id, $mod->visibleold);
1788 // Set this in the object because it is sent as a response to ajax calls.
1789 $mod->visible = $mod->visibleold;
1793 /// Add the module into the new section
1794 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1795 return true;
1799 * Returns the list of all editing actions that current user can perform on the module
1801 * @param cm_info $mod The module to produce editing buttons for
1802 * @param int $indent The current indenting (default -1 means no move left-right actions)
1803 * @param int $sr The section to link back to (used for creating the links)
1804 * @return array array of action_link or pix_icon objects
1806 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1807 global $COURSE, $SITE;
1809 static $str;
1811 $coursecontext = context_course::instance($mod->course);
1812 $modcontext = context_module::instance($mod->id);
1814 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1815 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1817 // no permission to edit anything
1818 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1819 return array();
1822 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1824 if (!isset($str)) {
1825 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1826 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
1827 $str->assign = get_string('assignroles', 'role');
1828 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1829 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1830 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1831 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
1832 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
1833 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1836 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1838 if ($sr !== null) {
1839 $baseurl->param('sr', $sr);
1841 $actions = array();
1843 // AJAX edit title
1844 if ($mod->has_view() && $hasmanageactivities &&
1845 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
1846 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
1847 // we will not display link if we are on some other-course page (where we should not see this module anyway)
1848 $actions['title'] = new action_link(
1849 new moodle_url($baseurl, array('update' => $mod->id)),
1850 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
1851 null,
1852 array('class' => 'editing_title', 'title' => $str->edittitle)
1856 // leftright
1857 if ($hasmanageactivities) {
1858 if (right_to_left()) { // Exchange arrows on RTL
1859 $rightarrow = 't/left';
1860 $leftarrow = 't/right';
1861 } else {
1862 $rightarrow = 't/right';
1863 $leftarrow = 't/left';
1866 if ($indent > 0) {
1867 $actions['moveleft'] = new action_link(
1868 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1869 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1870 null,
1871 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
1874 if ($indent >= 0) {
1875 $actions['moveright'] = new action_link(
1876 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1877 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1878 null,
1879 array('class' => 'editing_moveright', 'title' => $str->moveright)
1884 // move
1885 if ($hasmanageactivities) {
1886 $actions['move'] = new action_link(
1887 new moodle_url($baseurl, array('copy' => $mod->id)),
1888 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1889 null,
1890 array('class' => 'editing_move', 'title' => $str->move)
1894 // Update
1895 if ($hasmanageactivities) {
1896 $actions['update'] = new action_link(
1897 new moodle_url($baseurl, array('update' => $mod->id)),
1898 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1899 null,
1900 array('class' => 'editing_update', 'title' => $str->update)
1904 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1905 // note that restoring on front page is never allowed
1906 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
1907 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
1908 $actions['duplicate'] = new action_link(
1909 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1910 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1911 null,
1912 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
1916 // Delete
1917 if ($hasmanageactivities) {
1918 $actions['delete'] = new action_link(
1919 new moodle_url($baseurl, array('delete' => $mod->id)),
1920 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1921 null,
1922 array('class' => 'editing_delete', 'title' => $str->delete)
1926 // hideshow
1927 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1928 if ($mod->visible) {
1929 $actions['hide'] = new action_link(
1930 new moodle_url($baseurl, array('hide' => $mod->id)),
1931 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1932 null,
1933 array('class' => 'editing_hide', 'title' => $str->hide)
1935 } else {
1936 $actions['show'] = new action_link(
1937 new moodle_url($baseurl, array('show' => $mod->id)),
1938 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1939 null,
1940 array('class' => 'editing_show', 'title' => $str->show)
1945 // groupmode
1946 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1947 if ($mod->coursegroupmodeforce) {
1948 $modgroupmode = $mod->coursegroupmode;
1949 } else {
1950 $modgroupmode = $mod->groupmode;
1952 if ($modgroupmode == SEPARATEGROUPS) {
1953 $groupmode = NOGROUPS;
1954 $grouptitle = $str->groupsseparate;
1955 $forcedgrouptitle = $str->forcedgroupsseparate;
1956 $actionname = 'groupsseparate';
1957 $groupimage = 't/groups';
1958 } else if ($modgroupmode == VISIBLEGROUPS) {
1959 $groupmode = SEPARATEGROUPS;
1960 $grouptitle = $str->groupsvisible;
1961 $forcedgrouptitle = $str->forcedgroupsvisible;
1962 $actionname = 'groupsvisible';
1963 $groupimage = 't/groupv';
1964 } else {
1965 $groupmode = VISIBLEGROUPS;
1966 $grouptitle = $str->groupsnone;
1967 $forcedgrouptitle = $str->forcedgroupsnone;
1968 $actionname = 'groupsnone';
1969 $groupimage = 't/groupn';
1971 if (!$mod->coursegroupmodeforce) {
1972 $actions[$actionname] = new action_link(
1973 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
1974 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1975 null,
1976 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
1978 } else {
1979 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
1983 // Assign
1984 if (has_capability('moodle/role:assign', $modcontext)){
1985 $actions['assign'] = new action_link(
1986 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1987 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1988 null,
1989 array('class' => 'editing_assign', 'title' => $str->assign)
1993 return $actions;
1997 * given a course object with shortname & fullname, this function will
1998 * truncate the the number of chars allowed and add ... if it was too long
2000 function course_format_name ($course,$max=100) {
2002 $context = context_course::instance($course->id);
2003 $shortname = format_string($course->shortname, true, array('context' => $context));
2004 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2005 $str = $shortname.': '. $fullname;
2006 if (textlib::strlen($str) <= $max) {
2007 return $str;
2009 else {
2010 return textlib::substr($str,0,$max-3).'...';
2015 * Is the user allowed to add this type of module to this course?
2016 * @param object $course the course settings. Only $course->id is used.
2017 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2018 * @return bool whether the current user is allowed to add this type of module to this course.
2020 function course_allowed_module($course, $modname) {
2021 if (is_numeric($modname)) {
2022 throw new coding_exception('Function course_allowed_module no longer
2023 supports numeric module ids. Please update your code to pass the module name.');
2026 $capability = 'mod/' . $modname . ':addinstance';
2027 if (!get_capability_info($capability)) {
2028 // Debug warning that the capability does not exist, but no more than once per page.
2029 static $warned = array();
2030 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2031 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2032 debugging('The module ' . $modname . ' does not define the standard capability ' .
2033 $capability , DEBUG_DEVELOPER);
2034 $warned[$modname] = 1;
2037 // If the capability does not exist, the module can always be added.
2038 return true;
2041 $coursecontext = context_course::instance($course->id);
2042 return has_capability($capability, $coursecontext);
2046 * Efficiently moves many courses around while maintaining
2047 * sortorder in order.
2049 * @param array $courseids is an array of course ids
2050 * @param int $categoryid
2051 * @return bool success
2053 function move_courses($courseids, $categoryid) {
2054 global $CFG, $DB, $OUTPUT;
2056 if (empty($courseids)) {
2057 // nothing to do
2058 return;
2061 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2062 return false;
2065 $courseids = array_reverse($courseids);
2066 $newparent = context_coursecat::instance($category->id);
2067 $i = 1;
2069 foreach ($courseids as $courseid) {
2070 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2071 $course = new stdClass();
2072 $course->id = $courseid;
2073 $course->category = $category->id;
2074 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2075 if ($category->visible == 0) {
2076 // hide the course when moving into hidden category,
2077 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2078 $course->visible = 0;
2081 $DB->update_record('course', $course);
2082 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
2084 $context = context_course::instance($course->id);
2085 context_moved($context, $newparent);
2088 fix_course_sortorder();
2089 cache_helper::purge_by_event('changesincourse');
2091 return true;
2095 * Returns the display name of the given section that the course prefers
2097 * Implementation of this function is provided by course format
2098 * @see format_base::get_section_name()
2100 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2101 * @param int|stdClass $section Section object from database or just field course_sections.section
2102 * @return string Display name that the course format prefers, e.g. "Week 2"
2104 function get_section_name($courseorid, $section) {
2105 return course_get_format($courseorid)->get_section_name($section);
2109 * Tells if current course format uses sections
2111 * @param string $format Course format ID e.g. 'weeks' $course->format
2112 * @return bool
2114 function course_format_uses_sections($format) {
2115 $course = new stdClass();
2116 $course->format = $format;
2117 return course_get_format($course)->uses_sections();
2121 * Returns the information about the ajax support in the given source format
2123 * The returned object's property (boolean)capable indicates that
2124 * the course format supports Moodle course ajax features.
2125 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2127 * @param string $format
2128 * @return stdClass
2130 function course_format_ajax_support($format) {
2131 $course = new stdClass();
2132 $course->format = $format;
2133 return course_get_format($course)->supports_ajax();
2137 * Can the current user delete this course?
2138 * Course creators have exception,
2139 * 1 day after the creation they can sill delete the course.
2140 * @param int $courseid
2141 * @return boolean
2143 function can_delete_course($courseid) {
2144 global $USER, $DB;
2146 $context = context_course::instance($courseid);
2148 if (has_capability('moodle/course:delete', $context)) {
2149 return true;
2152 // hack: now try to find out if creator created this course recently (1 day)
2153 if (!has_capability('moodle/course:create', $context)) {
2154 return false;
2157 $since = time() - 60*60*24;
2159 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2160 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2162 return $DB->record_exists_select('log', $select, $params);
2166 * Save the Your name for 'Some role' strings.
2168 * @param integer $courseid the id of this course.
2169 * @param array $data the data that came from the course settings form.
2171 function save_local_role_names($courseid, $data) {
2172 global $DB;
2173 $context = context_course::instance($courseid);
2175 foreach ($data as $fieldname => $value) {
2176 if (strpos($fieldname, 'role_') !== 0) {
2177 continue;
2179 list($ignored, $roleid) = explode('_', $fieldname);
2181 // make up our mind whether we want to delete, update or insert
2182 if (!$value) {
2183 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2185 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2186 $rolename->name = $value;
2187 $DB->update_record('role_names', $rolename);
2189 } else {
2190 $rolename = new stdClass;
2191 $rolename->contextid = $context->id;
2192 $rolename->roleid = $roleid;
2193 $rolename->name = $value;
2194 $DB->insert_record('role_names', $rolename);
2200 * Returns options to use in course overviewfiles filemanager
2202 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2203 * may be empty if course does not exist yet (course create form)
2204 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2205 * or null if overviewfiles are disabled
2207 function course_overviewfiles_options($course) {
2208 global $CFG;
2209 if (empty($CFG->courseoverviewfileslimit)) {
2210 return null;
2212 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2213 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2214 $accepted_types = '*';
2215 } else {
2216 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2217 // Make sure extensions are prefixed with dot unless they are valid typegroups
2218 foreach ($accepted_types as $i => $type) {
2219 if (substr($type, 0, 1) !== '.') {
2220 require_once($CFG->libdir. '/filelib.php');
2221 if (!count(file_get_typegroup('extension', $type))) {
2222 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2223 $accepted_types[$i] = '.'. $type;
2224 $corrected = true;
2228 if (!empty($corrected)) {
2229 set_config('courseoverviewfilesext', join(',', $accepted_types));
2232 $options = array(
2233 'maxfiles' => $CFG->courseoverviewfileslimit,
2234 'maxbytes' => $CFG->maxbytes,
2235 'subdirs' => 0,
2236 'accepted_types' => $accepted_types
2238 if (!empty($course->id)) {
2239 $options['context'] = context_course::instance($course->id);
2240 } else if (is_int($course) && $course > 0) {
2241 $options['context'] = context_course::instance($course);
2243 return $options;
2247 * Create a course and either return a $course object
2249 * Please note this functions does not verify any access control,
2250 * the calling code is responsible for all validation (usually it is the form definition).
2252 * @param array $editoroptions course description editor options
2253 * @param object $data - all the data needed for an entry in the 'course' table
2254 * @return object new course instance
2256 function create_course($data, $editoroptions = NULL) {
2257 global $CFG, $DB;
2259 //check the categoryid - must be given for all new courses
2260 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2262 //check if the shortname already exist
2263 if (!empty($data->shortname)) {
2264 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2265 throw new moodle_exception('shortnametaken');
2269 //check if the id number already exist
2270 if (!empty($data->idnumber)) {
2271 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2272 throw new moodle_exception('idnumbertaken');
2276 $data->timecreated = time();
2277 $data->timemodified = $data->timecreated;
2279 // place at beginning of any category
2280 $data->sortorder = 0;
2282 if ($editoroptions) {
2283 // summary text is updated later, we need context to store the files first
2284 $data->summary = '';
2285 $data->summary_format = FORMAT_HTML;
2288 if (!isset($data->visible)) {
2289 // data not from form, add missing visibility info
2290 $data->visible = $category->visible;
2292 $data->visibleold = $data->visible;
2294 $newcourseid = $DB->insert_record('course', $data);
2295 $context = context_course::instance($newcourseid, MUST_EXIST);
2297 if ($editoroptions) {
2298 // Save the files used in the summary editor and store
2299 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2300 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2301 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2303 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2304 // Save the course overviewfiles
2305 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2308 // update course format options
2309 course_get_format($newcourseid)->update_course_format_options($data);
2311 $course = course_get_format($newcourseid)->get_course();
2313 // Setup the blocks
2314 blocks_add_default_course_blocks($course);
2316 // Create a default section.
2317 course_create_sections_if_missing($course, 0);
2319 fix_course_sortorder();
2320 // purge appropriate caches in case fix_course_sortorder() did not change anything
2321 cache_helper::purge_by_event('changesincourse');
2323 // new context created - better mark it as dirty
2324 mark_context_dirty($context->path);
2326 // Save any custom role names.
2327 save_local_role_names($course->id, (array)$data);
2329 // set up enrolments
2330 enrol_course_updated(true, $course, $data);
2332 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2334 // Trigger events
2335 events_trigger('course_created', $course);
2337 return $course;
2341 * Update a course.
2343 * Please note this functions does not verify any access control,
2344 * the calling code is responsible for all validation (usually it is the form definition).
2346 * @param object $data - all the data needed for an entry in the 'course' table
2347 * @param array $editoroptions course description editor options
2348 * @return void
2350 function update_course($data, $editoroptions = NULL) {
2351 global $CFG, $DB;
2353 $data->timemodified = time();
2355 $oldcourse = course_get_format($data->id)->get_course();
2356 $context = context_course::instance($oldcourse->id);
2358 if ($editoroptions) {
2359 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2361 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2362 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2365 // Check we don't have a duplicate shortname.
2366 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2367 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2368 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2372 // Check we don't have a duplicate idnumber.
2373 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2374 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2375 throw new moodle_exception('idnumbertaken', 'error');
2379 if (!isset($data->category) or empty($data->category)) {
2380 // prevent nulls and 0 in category field
2381 unset($data->category);
2383 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2385 if (!isset($data->visible)) {
2386 // data not from form, add missing visibility info
2387 $data->visible = $oldcourse->visible;
2390 if ($data->visible != $oldcourse->visible) {
2391 // reset the visibleold flag when manually hiding/unhiding course
2392 $data->visibleold = $data->visible;
2393 $changesincoursecat = true;
2394 } else {
2395 if ($movecat) {
2396 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2397 if (empty($newcategory->visible)) {
2398 // make sure when moving into hidden category the course is hidden automatically
2399 $data->visible = 0;
2404 // Update with the new data
2405 $DB->update_record('course', $data);
2406 // make sure the modinfo cache is reset
2407 rebuild_course_cache($data->id);
2409 // update course format options with full course data
2410 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2412 $course = $DB->get_record('course', array('id'=>$data->id));
2414 if ($movecat) {
2415 $newparent = context_coursecat::instance($course->category);
2416 context_moved($context, $newparent);
2419 if ($movecat || (isset($data->sortorder) && $oldcourse->sortorder != $data->sortorder)) {
2420 fix_course_sortorder();
2423 // purge appropriate caches in case fix_course_sortorder() did not change anything
2424 cache_helper::purge_by_event('changesincourse');
2425 if ($changesincoursecat) {
2426 cache_helper::purge_by_event('changesincoursecat');
2429 // Test for and remove blocks which aren't appropriate anymore
2430 blocks_remove_inappropriate($course);
2432 // Save any custom role names.
2433 save_local_role_names($course->id, $data);
2435 // update enrol settings
2436 enrol_course_updated(false, $course, $data);
2438 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2440 // Trigger events
2441 events_trigger('course_updated', $course);
2443 if ($oldcourse->format !== $course->format) {
2444 // Remove all options stored for the previous format
2445 // We assume that new course format migrated everything it needed watching trigger
2446 // 'course_updated' and in method format_XXX::update_course_format_options()
2447 $DB->delete_records('course_format_options',
2448 array('courseid' => $course->id, 'format' => $oldcourse->format));
2453 * Average number of participants
2454 * @return integer
2456 function average_number_of_participants() {
2457 global $DB, $SITE;
2459 //count total of enrolments for visible course (except front page)
2460 $sql = 'SELECT COUNT(*) FROM (
2461 SELECT DISTINCT ue.userid, e.courseid
2462 FROM {user_enrolments} ue, {enrol} e, {course} c
2463 WHERE ue.enrolid = e.id
2464 AND e.courseid <> :siteid
2465 AND c.id = e.courseid
2466 AND c.visible = 1) total';
2467 $params = array('siteid' => $SITE->id);
2468 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2471 //count total of visible courses (minus front page)
2472 $coursetotal = $DB->count_records('course', array('visible' => 1));
2473 $coursetotal = $coursetotal - 1 ;
2475 //average of enrolment
2476 if (empty($coursetotal)) {
2477 $participantaverage = 0;
2478 } else {
2479 $participantaverage = $enrolmenttotal / $coursetotal;
2482 return $participantaverage;
2486 * Average number of course modules
2487 * @return integer
2489 function average_number_of_courses_modules() {
2490 global $DB, $SITE;
2492 //count total of visible course module (except front page)
2493 $sql = 'SELECT COUNT(*) FROM (
2494 SELECT cm.course, cm.module
2495 FROM {course} c, {course_modules} cm
2496 WHERE c.id = cm.course
2497 AND c.id <> :siteid
2498 AND cm.visible = 1
2499 AND c.visible = 1) total';
2500 $params = array('siteid' => $SITE->id);
2501 $moduletotal = $DB->count_records_sql($sql, $params);
2504 //count total of visible courses (minus front page)
2505 $coursetotal = $DB->count_records('course', array('visible' => 1));
2506 $coursetotal = $coursetotal - 1 ;
2508 //average of course module
2509 if (empty($coursetotal)) {
2510 $coursemoduleaverage = 0;
2511 } else {
2512 $coursemoduleaverage = $moduletotal / $coursetotal;
2515 return $coursemoduleaverage;
2519 * This class pertains to course requests and contains methods associated with
2520 * create, approving, and removing course requests.
2522 * Please note we do not allow embedded images here because there is no context
2523 * to store them with proper access control.
2525 * @copyright 2009 Sam Hemelryk
2526 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2527 * @since Moodle 2.0
2529 * @property-read int $id
2530 * @property-read string $fullname
2531 * @property-read string $shortname
2532 * @property-read string $summary
2533 * @property-read int $summaryformat
2534 * @property-read int $summarytrust
2535 * @property-read string $reason
2536 * @property-read int $requester
2538 class course_request {
2541 * This is the stdClass that stores the properties for the course request
2542 * and is externally accessed through the __get magic method
2543 * @var stdClass
2545 protected $properties;
2548 * An array of options for the summary editor used by course request forms.
2549 * This is initially set by {@link summary_editor_options()}
2550 * @var array
2551 * @static
2553 protected static $summaryeditoroptions;
2556 * Static function to prepare the summary editor for working with a course
2557 * request.
2559 * @static
2560 * @param null|stdClass $data Optional, an object containing the default values
2561 * for the form, these may be modified when preparing the
2562 * editor so this should be called before creating the form
2563 * @return stdClass An object that can be used to set the default values for
2564 * an mforms form
2566 public static function prepare($data=null) {
2567 if ($data === null) {
2568 $data = new stdClass;
2570 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2571 return $data;
2575 * Static function to create a new course request when passed an array of properties
2576 * for it.
2578 * This function also handles saving any files that may have been used in the editor
2580 * @static
2581 * @param stdClass $data
2582 * @return course_request The newly created course request
2584 public static function create($data) {
2585 global $USER, $DB, $CFG;
2586 $data->requester = $USER->id;
2588 // Setting the default category if none set.
2589 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2590 $data->category = $CFG->defaultrequestcategory;
2593 // Summary is a required field so copy the text over
2594 $data->summary = $data->summary_editor['text'];
2595 $data->summaryformat = $data->summary_editor['format'];
2597 $data->id = $DB->insert_record('course_request', $data);
2599 // Create a new course_request object and return it
2600 $request = new course_request($data);
2602 // Notify the admin if required.
2603 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2605 $a = new stdClass;
2606 $a->link = "$CFG->wwwroot/course/pending.php";
2607 $a->user = fullname($USER);
2608 $subject = get_string('courserequest');
2609 $message = get_string('courserequestnotifyemail', 'admin', $a);
2610 foreach ($users as $user) {
2611 $request->notify($user, $USER, 'courserequested', $subject, $message);
2615 return $request;
2619 * Returns an array of options to use with a summary editor
2621 * @uses course_request::$summaryeditoroptions
2622 * @return array An array of options to use with the editor
2624 public static function summary_editor_options() {
2625 global $CFG;
2626 if (self::$summaryeditoroptions === null) {
2627 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2629 return self::$summaryeditoroptions;
2633 * Loads the properties for this course request object. Id is required and if
2634 * only id is provided then we load the rest of the properties from the database
2636 * @param stdClass|int $properties Either an object containing properties
2637 * or the course_request id to load
2639 public function __construct($properties) {
2640 global $DB;
2641 if (empty($properties->id)) {
2642 if (empty($properties)) {
2643 throw new coding_exception('You must provide a course request id when creating a course_request object');
2645 $id = $properties;
2646 $properties = new stdClass;
2647 $properties->id = (int)$id;
2648 unset($id);
2650 if (empty($properties->requester)) {
2651 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2652 print_error('unknowncourserequest');
2654 } else {
2655 $this->properties = $properties;
2657 $this->properties->collision = null;
2661 * Returns the requested property
2663 * @param string $key
2664 * @return mixed
2666 public function __get($key) {
2667 return $this->properties->$key;
2671 * Override this to ensure empty($request->blah) calls return a reliable answer...
2673 * This is required because we define the __get method
2675 * @param mixed $key
2676 * @return bool True is it not empty, false otherwise
2678 public function __isset($key) {
2679 return (!empty($this->properties->$key));
2683 * Returns the user who requested this course
2685 * Uses a static var to cache the results and cut down the number of db queries
2687 * @staticvar array $requesters An array of cached users
2688 * @return stdClass The user who requested the course
2690 public function get_requester() {
2691 global $DB;
2692 static $requesters= array();
2693 if (!array_key_exists($this->properties->requester, $requesters)) {
2694 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2696 return $requesters[$this->properties->requester];
2700 * Checks that the shortname used by the course does not conflict with any other
2701 * courses that exist
2703 * @param string|null $shortnamemark The string to append to the requests shortname
2704 * should a conflict be found
2705 * @return bool true is there is a conflict, false otherwise
2707 public function check_shortname_collision($shortnamemark = '[*]') {
2708 global $DB;
2710 if ($this->properties->collision !== null) {
2711 return $this->properties->collision;
2714 if (empty($this->properties->shortname)) {
2715 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2716 $this->properties->collision = false;
2717 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2718 if (!empty($shortnamemark)) {
2719 $this->properties->shortname .= ' '.$shortnamemark;
2721 $this->properties->collision = true;
2722 } else {
2723 $this->properties->collision = false;
2725 return $this->properties->collision;
2729 * Returns the category where this course request should be created
2731 * Note that we don't check here that user has a capability to view
2732 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2733 * 'moodle/course:changecategory'
2735 * @return coursecat
2737 public function get_category() {
2738 global $CFG;
2739 require_once($CFG->libdir.'/coursecatlib.php');
2740 // If the category is not set, if the current user does not have the rights to change the category, or if the
2741 // category does not exist, we set the default category to the course to be approved.
2742 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2743 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2744 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2745 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2747 if (!$category) {
2748 $category = coursecat::get_default();
2750 return $category;
2754 * This function approves the request turning it into a course
2756 * This function converts the course request into a course, at the same time
2757 * transferring any files used in the summary to the new course and then removing
2758 * the course request and the files associated with it.
2760 * @return int The id of the course that was created from this request
2762 public function approve() {
2763 global $CFG, $DB, $USER;
2765 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2767 $courseconfig = get_config('moodlecourse');
2769 // Transfer appropriate settings
2770 $data = clone($this->properties);
2771 unset($data->id);
2772 unset($data->reason);
2773 unset($data->requester);
2775 // Set category
2776 $category = $this->get_category();
2777 $data->category = $category->id;
2778 // Set misc settings
2779 $data->requested = 1;
2781 // Apply course default settings
2782 $data->format = $courseconfig->format;
2783 $data->newsitems = $courseconfig->newsitems;
2784 $data->showgrades = $courseconfig->showgrades;
2785 $data->showreports = $courseconfig->showreports;
2786 $data->maxbytes = $courseconfig->maxbytes;
2787 $data->groupmode = $courseconfig->groupmode;
2788 $data->groupmodeforce = $courseconfig->groupmodeforce;
2789 $data->visible = $courseconfig->visible;
2790 $data->visibleold = $data->visible;
2791 $data->lang = $courseconfig->lang;
2793 $course = create_course($data);
2794 $context = context_course::instance($course->id, MUST_EXIST);
2796 // add enrol instances
2797 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2798 if ($manual = enrol_get_plugin('manual')) {
2799 $manual->add_default_instance($course);
2803 // enrol the requester as teacher if necessary
2804 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2805 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2808 $this->delete();
2810 $a = new stdClass();
2811 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2812 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2813 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
2815 return $course->id;
2819 * Reject a course request
2821 * This function rejects a course request, emailing the requesting user the
2822 * provided notice and then removing the request from the database
2824 * @param string $notice The message to display to the user
2826 public function reject($notice) {
2827 global $USER, $DB;
2828 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2829 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2830 $this->delete();
2834 * Deletes the course request and any associated files
2836 public function delete() {
2837 global $DB;
2838 $DB->delete_records('course_request', array('id' => $this->properties->id));
2842 * Send a message from one user to another using events_trigger
2844 * @param object $touser
2845 * @param object $fromuser
2846 * @param string $name
2847 * @param string $subject
2848 * @param string $message
2850 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
2851 $eventdata = new stdClass();
2852 $eventdata->component = 'moodle';
2853 $eventdata->name = $name;
2854 $eventdata->userfrom = $fromuser;
2855 $eventdata->userto = $touser;
2856 $eventdata->subject = $subject;
2857 $eventdata->fullmessage = $message;
2858 $eventdata->fullmessageformat = FORMAT_PLAIN;
2859 $eventdata->fullmessagehtml = '';
2860 $eventdata->smallmessage = '';
2861 $eventdata->notification = 1;
2862 message_send($eventdata);
2867 * Return a list of page types
2868 * @param string $pagetype current page type
2869 * @param context $parentcontext Block's parent context
2870 * @param context $currentcontext Current context of block
2871 * @return array array of page types
2873 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2874 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2875 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2876 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2877 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2879 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2880 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2881 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2882 } else {
2883 // Otherwise consider it a page inside a course even if $currentcontext is null
2884 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2885 'course-*' => get_string('page-course-x', 'pagetype'),
2886 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2889 return $pagetypes;
2893 * Determine whether course ajax should be enabled for the specified course
2895 * @param stdClass $course The course to test against
2896 * @return boolean Whether course ajax is enabled or note
2898 function course_ajax_enabled($course) {
2899 global $CFG, $PAGE, $SITE;
2901 // Ajax must be enabled globally
2902 if (!$CFG->enableajax) {
2903 return false;
2906 // The user must be editing for AJAX to be included
2907 if (!$PAGE->user_is_editing()) {
2908 return false;
2911 // Check that the theme suports
2912 if (!$PAGE->theme->enablecourseajax) {
2913 return false;
2916 // Check that the course format supports ajax functionality
2917 // The site 'format' doesn't have information on course format support
2918 if ($SITE->id !== $course->id) {
2919 $courseformatajaxsupport = course_format_ajax_support($course->format);
2920 if (!$courseformatajaxsupport->capable) {
2921 return false;
2925 // All conditions have been met so course ajax should be enabled
2926 return true;
2930 * Include the relevant javascript and language strings for the resource
2931 * toolbox YUI module
2933 * @param integer $id The ID of the course being applied to
2934 * @param array $usedmodules An array containing the names of the modules in use on the page
2935 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
2936 * @param stdClass $config An object containing configuration parameters for ajax modules including:
2937 * * resourceurl The URL to post changes to for resource changes
2938 * * sectionurl The URL to post changes to for section changes
2939 * * pageparams Additional parameters to pass through in the post
2940 * @return bool
2942 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
2943 global $PAGE, $SITE;
2945 // Ensure that ajax should be included
2946 if (!course_ajax_enabled($course)) {
2947 return false;
2950 if (!$config) {
2951 $config = new stdClass();
2954 // The URL to use for resource changes
2955 if (!isset($config->resourceurl)) {
2956 $config->resourceurl = '/course/rest.php';
2959 // The URL to use for section changes
2960 if (!isset($config->sectionurl)) {
2961 $config->sectionurl = '/course/rest.php';
2964 // Any additional parameters which need to be included on page submission
2965 if (!isset($config->pageparams)) {
2966 $config->pageparams = array();
2969 // Include toolboxes
2970 $PAGE->requires->yui_module('moodle-course-toolboxes',
2971 'M.course.init_resource_toolbox',
2972 array(array(
2973 'courseid' => $course->id,
2974 'ajaxurl' => $config->resourceurl,
2975 'config' => $config,
2978 $PAGE->requires->yui_module('moodle-course-toolboxes',
2979 'M.course.init_section_toolbox',
2980 array(array(
2981 'courseid' => $course->id,
2982 'format' => $course->format,
2983 'ajaxurl' => $config->sectionurl,
2984 'config' => $config,
2988 // Include course dragdrop
2989 if ($course->id != $SITE->id) {
2990 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
2991 array(array(
2992 'courseid' => $course->id,
2993 'ajaxurl' => $config->sectionurl,
2994 'config' => $config,
2995 )), null, true);
2997 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
2998 array(array(
2999 'courseid' => $course->id,
3000 'ajaxurl' => $config->resourceurl,
3001 'config' => $config,
3002 )), null, true);
3005 // Require various strings for the command toolbox
3006 $PAGE->requires->strings_for_js(array(
3007 'moveleft',
3008 'deletechecktype',
3009 'deletechecktypename',
3010 'edittitle',
3011 'edittitleinstructions',
3012 'show',
3013 'hide',
3014 'groupsnone',
3015 'groupsvisible',
3016 'groupsseparate',
3017 'clicktochangeinbrackets',
3018 'markthistopic',
3019 'markedthistopic',
3020 'move',
3021 'movesection',
3022 ), 'moodle');
3024 // Include format-specific strings
3025 if ($course->id != $SITE->id) {
3026 $PAGE->requires->strings_for_js(array(
3027 'showfromothers',
3028 'hidefromothers',
3029 ), 'format_' . $course->format);
3032 // For confirming resource deletion we need the name of the module in question
3033 foreach ($usedmodules as $module => $modname) {
3034 $PAGE->requires->string_for_js('pluginname', $module);
3037 // Load drag and drop upload AJAX.
3038 dndupload_add_to_course($course, $enabledmodules);
3040 return true;
3044 * Returns the sorted list of available course formats, filtered by enabled if necessary
3046 * @param bool $enabledonly return only formats that are enabled
3047 * @return array array of sorted format names
3049 function get_sorted_course_formats($enabledonly = false) {
3050 global $CFG;
3051 $formats = get_plugin_list('format');
3053 if (!empty($CFG->format_plugins_sortorder)) {
3054 $order = explode(',', $CFG->format_plugins_sortorder);
3055 $order = array_merge(array_intersect($order, array_keys($formats)),
3056 array_diff(array_keys($formats), $order));
3057 } else {
3058 $order = array_keys($formats);
3060 if (!$enabledonly) {
3061 return $order;
3063 $sortedformats = array();
3064 foreach ($order as $formatname) {
3065 if (!get_config('format_'.$formatname, 'disabled')) {
3066 $sortedformats[] = $formatname;
3069 return $sortedformats;
3073 * The URL to use for the specified course (with section)
3075 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3076 * @param int|stdClass $section Section object from database or just field course_sections.section
3077 * if omitted the course view page is returned
3078 * @param array $options options for view URL. At the moment core uses:
3079 * 'navigation' (bool) if true and section has no separate page, the function returns null
3080 * 'sr' (int) used by multipage formats to specify to which section to return
3081 * @return moodle_url The url of course
3083 function course_get_url($courseorid, $section = null, $options = array()) {
3084 return course_get_format($courseorid)->get_view_url($section, $options);
3088 * Create a module.
3090 * It includes:
3091 * - capability checks and other checks
3092 * - create the module from the module info
3094 * @param object $module
3095 * @return object the created module info
3097 function create_module($moduleinfo) {
3098 global $DB, $CFG;
3100 require_once($CFG->dirroot . '/course/modlib.php');
3102 // Check manadatory attributs.
3103 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3104 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3105 $mandatoryfields[] = 'introeditor';
3107 foreach($mandatoryfields as $mandatoryfield) {
3108 if (!isset($moduleinfo->{$mandatoryfield})) {
3109 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3113 // Some additional checks (capability / existing instances).
3114 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3115 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3117 // Load module library.
3118 include_modulelib($module->name);
3120 // Add the module.
3121 $moduleinfo->module = $module->id;
3122 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3124 return $moduleinfo;
3128 * Update a module.
3130 * It includes:
3131 * - capability and other checks
3132 * - update the module
3134 * @param object $module
3135 * @return object the updated module info
3137 function update_module($moduleinfo) {
3138 global $DB, $CFG;
3140 require_once($CFG->dirroot . '/course/modlib.php');
3142 // Check the course module exists.
3143 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3145 // Check the course exists.
3146 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3148 // Some checks (capaibility / existing instances).
3149 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3151 // Load module library.
3152 include_modulelib($module->name);
3154 // Retrieve few information needed by update_moduleinfo.
3155 $moduleinfo->modulename = $cm->modname;
3156 if (!isset($moduleinfo->scale)) {
3157 $moduleinfo->scale = 0;
3159 $moduleinfo->type = 'mod';
3161 // Update the module.
3162 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3164 return $moduleinfo;
3168 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3169 * Sorts by descending order of time.
3171 * @param stdClass $a First object
3172 * @param stdClass $b Second object
3173 * @return int 0,1,-1 representing the order
3175 function compare_activities_by_time_desc($a, $b) {
3176 // Make sure the activities actually have a timestamp property.
3177 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3178 return 0;
3180 // We treat instances without timestamp as if they have a timestamp of 0.
3181 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3182 return 1;
3184 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3185 return -1;
3187 if ($a->timestamp == $b->timestamp) {
3188 return 0;
3190 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3194 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3195 * Sorts by ascending order of time.
3197 * @param stdClass $a First object
3198 * @param stdClass $b Second object
3199 * @return int 0,1,-1 representing the order
3201 function compare_activities_by_time_asc($a, $b) {
3202 // Make sure the activities actually have a timestamp property.
3203 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3204 return 0;
3206 // We treat instances without timestamp as if they have a timestamp of 0.
3207 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3208 return -1;
3210 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3211 return 1;
3213 if ($a->timestamp == $b->timestamp) {
3214 return 0;
3216 return ($a->timestamp < $b->timestamp) ? -1 : 1;