Merge branch 'MDL-38821_master' of git://github.com/dmonllao/moodle
[moodle.git] / course / lib.php
blob9f76d7699beab350506f01936feffc502afabc22
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');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'calendar':
71 case 'category':
72 case 'mnet course':
73 if (strpos($url, '../') === 0) {
74 $url = ltrim($url, '.');
75 } else {
76 $url = "/course/$url";
78 break;
79 case 'user':
80 case 'blog':
81 $url = "/$module/$url";
82 break;
83 case 'upload':
84 $url = $url;
85 break;
86 case 'coursetags':
87 $url = '/'.$url;
88 break;
89 case 'library':
90 case '':
91 $url = '/';
92 break;
93 case 'message':
94 $url = "/message/$url";
95 break;
96 case 'notes':
97 $url = "/notes/$url";
98 break;
99 case 'tag':
100 $url = "/tag/$url";
101 break;
102 case 'role':
103 $url = '/'.$url;
104 break;
105 default:
106 $url = "/mod/$module/$url";
107 break;
110 //now let's sanitise urls - there might be some ugly nasties:-(
111 $parts = explode('?', $url);
112 $script = array_shift($parts);
113 if (strpos($script, 'http') === 0) {
114 $script = clean_param($script, PARAM_URL);
115 } else {
116 $script = clean_param($script, PARAM_PATH);
119 $query = '';
120 if ($parts) {
121 $query = implode('', $parts);
122 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
123 $parts = explode('&', $query);
124 $eq = urlencode('=');
125 foreach ($parts as $key=>$part) {
126 $part = urlencode(urldecode($part));
127 $part = str_replace($eq, '=', $part);
128 $parts[$key] = $part;
130 $query = '?'.implode('&amp;', $parts);
133 return $script.$query;
137 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
138 $modname="", $modid=0, $modaction="", $groupid=0) {
139 global $CFG, $DB;
141 // It is assumed that $date is the GMT time of midnight for that day,
142 // and so the next 86400 seconds worth of logs are printed.
144 /// Setup for group handling.
146 // TODO: I don't understand group/context/etc. enough to be able to do
147 // something interesting with it here
148 // What is the context of a remote course?
150 /// If the group mode is separate, and this user does not have editing privileges,
151 /// then only the user's group can be viewed.
152 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
153 // $groupid = get_current_group($course->id);
155 /// If this course doesn't have groups, no groupid can be specified.
156 //else if (!$course->groupmode) {
157 // $groupid = 0;
160 $groupid = 0;
162 $joins = array();
163 $where = '';
165 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
166 FROM {mnet_log} l
167 LEFT JOIN {user} u ON l.userid = u.id
168 WHERE ";
169 $params = array();
171 $where .= "l.hostid = :hostid";
172 $params['hostid'] = $hostid;
174 // TODO: Is 1 really a magic number referring to the sitename?
175 if ($course != SITEID || $modid != 0) {
176 $where .= " AND l.course=:courseid";
177 $params['courseid'] = $course;
180 if ($modname) {
181 $where .= " AND l.module = :modname";
182 $params['modname'] = $modname;
185 if ('site_errors' === $modid) {
186 $where .= " AND ( l.action='error' OR l.action='infected' )";
187 } else if ($modid) {
188 //TODO: This assumes that modids are the same across sites... probably
189 //not true
190 $where .= " AND l.cmid = :modid";
191 $params['modid'] = $modid;
194 if ($modaction) {
195 $firstletter = substr($modaction, 0, 1);
196 if ($firstletter == '-') {
197 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
198 $params['modaction'] = '%'.substr($modaction, 1).'%';
199 } else {
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
201 $params['modaction'] = '%'.$modaction.'%';
205 if ($user) {
206 $where .= " AND l.userid = :user";
207 $params['user'] = $user;
210 if ($date) {
211 $enddate = $date + 86400;
212 $where .= " AND l.time > :date AND l.time < :enddate";
213 $params['date'] = $date;
214 $params['enddate'] = $enddate;
217 $result = array();
218 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
219 if(!empty($result['totalcount'])) {
220 $where .= " ORDER BY $order";
221 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
222 } else {
223 $result['logs'] = array();
225 return $result;
228 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
229 $modname="", $modid=0, $modaction="", $groupid=0) {
230 global $DB, $SESSION, $USER;
231 // It is assumed that $date is the GMT time of midnight for that day,
232 // and so the next 86400 seconds worth of logs are printed.
234 /// Setup for group handling.
236 /// If the group mode is separate, and this user does not have editing privileges,
237 /// then only the user's group can be viewed.
238 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
239 if (isset($SESSION->currentgroup[$course->id])) {
240 $groupid = $SESSION->currentgroup[$course->id];
241 } else {
242 $groupid = groups_get_all_groups($course->id, $USER->id);
243 if (is_array($groupid)) {
244 $groupid = array_shift(array_keys($groupid));
245 $SESSION->currentgroup[$course->id] = $groupid;
246 } else {
247 $groupid = 0;
251 /// If this course doesn't have groups, no groupid can be specified.
252 else if (!$course->groupmode) {
253 $groupid = 0;
256 $joins = array();
257 $params = array();
259 if ($course->id != SITEID || $modid != 0) {
260 $joins[] = "l.course = :courseid";
261 $params['courseid'] = $course->id;
264 if ($modname) {
265 $joins[] = "l.module = :modname";
266 $params['modname'] = $modname;
269 if ('site_errors' === $modid) {
270 $joins[] = "( l.action='error' OR l.action='infected' )";
271 } else if ($modid) {
272 $joins[] = "l.cmid = :modid";
273 $params['modid'] = $modid;
276 if ($modaction) {
277 $firstletter = substr($modaction, 0, 1);
278 if ($firstletter == '-') {
279 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
280 $params['modaction'] = '%'.substr($modaction, 1).'%';
281 } else {
282 $joins[] = $DB->sql_like('l.action', ':modaction', false);
283 $params['modaction'] = '%'.$modaction.'%';
288 /// Getting all members of a group.
289 if ($groupid and !$user) {
290 if ($gusers = groups_get_members($groupid)) {
291 $gusers = array_keys($gusers);
292 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
293 } else {
294 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
297 else if ($user) {
298 $joins[] = "l.userid = :userid";
299 $params['userid'] = $user;
302 if ($date) {
303 $enddate = $date + 86400;
304 $joins[] = "l.time > :date AND l.time < :enddate";
305 $params['date'] = $date;
306 $params['enddate'] = $enddate;
309 $selector = implode(' AND ', $joins);
311 $totalcount = 0; // Initialise
312 $result = array();
313 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
314 $result['totalcount'] = $totalcount;
315 return $result;
319 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
320 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
322 global $CFG, $DB, $OUTPUT;
324 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
325 $modname, $modid, $modaction, $groupid)) {
326 echo $OUTPUT->notification("No logs found!");
327 echo $OUTPUT->footer();
328 exit;
331 $courses = array();
333 if ($course->id == SITEID) {
334 $courses[0] = '';
335 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
336 foreach ($ccc as $cc) {
337 $courses[$cc->id] = $cc->shortname;
340 } else {
341 $courses[$course->id] = $course->shortname;
344 $totalcount = $logs['totalcount'];
345 $count=0;
346 $ldcache = array();
347 $tt = getdate(time());
348 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
350 $strftimedatetime = get_string("strftimedatetime");
352 echo "<div class=\"info\">\n";
353 print_string("displayingrecords", "", $totalcount);
354 echo "</div>\n";
356 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
358 $table = new html_table();
359 $table->classes = array('logtable','generaltable');
360 $table->align = array('right', 'left', 'left');
361 $table->head = array(
362 get_string('time'),
363 get_string('ip_address'),
364 get_string('fullnameuser'),
365 get_string('action'),
366 get_string('info')
368 $table->data = array();
370 if ($course->id == SITEID) {
371 array_unshift($table->align, 'left');
372 array_unshift($table->head, get_string('course'));
375 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
376 if (empty($logs['logs'])) {
377 $logs['logs'] = array();
380 foreach ($logs['logs'] as $log) {
382 if (isset($ldcache[$log->module][$log->action])) {
383 $ld = $ldcache[$log->module][$log->action];
384 } else {
385 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
386 $ldcache[$log->module][$log->action] = $ld;
388 if ($ld && is_numeric($log->info)) {
389 // ugly hack to make sure fullname is shown correctly
390 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
391 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
392 } else {
393 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
397 //Filter log->info
398 $log->info = format_string($log->info);
400 // If $log->url has been trimmed short by the db size restriction
401 // code in add_to_log, keep a note so we don't add a link to a broken url
402 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
404 $row = array();
405 if ($course->id == SITEID) {
406 if (empty($log->course)) {
407 $row[] = get_string('site');
408 } else {
409 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
413 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
415 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
416 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
418 $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))));
420 $displayaction="$log->module $log->action";
421 if ($brokenurl) {
422 $row[] = $displayaction;
423 } else {
424 $link = make_log_url($log->module,$log->url);
425 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
427 $row[] = $log->info;
428 $table->data[] = $row;
431 echo html_writer::table($table);
432 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
436 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
437 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
439 global $CFG, $DB, $OUTPUT;
441 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
442 $modname, $modid, $modaction, $groupid)) {
443 echo $OUTPUT->notification("No logs found!");
444 echo $OUTPUT->footer();
445 exit;
448 if ($course->id == SITEID) {
449 $courses[0] = '';
450 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
451 foreach ($ccc as $cc) {
452 $courses[$cc->id] = $cc->shortname;
457 $totalcount = $logs['totalcount'];
458 $count=0;
459 $ldcache = array();
460 $tt = getdate(time());
461 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
463 $strftimedatetime = get_string("strftimedatetime");
465 echo "<div class=\"info\">\n";
466 print_string("displayingrecords", "", $totalcount);
467 echo "</div>\n";
469 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
471 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
472 echo "<tr>";
473 if ($course->id == SITEID) {
474 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
476 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
477 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
478 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
479 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
480 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
481 echo "</tr>\n";
483 if (empty($logs['logs'])) {
484 echo "</table>\n";
485 return;
488 $row = 1;
489 foreach ($logs['logs'] as $log) {
491 $log->info = $log->coursename;
492 $row = ($row + 1) % 2;
494 if (isset($ldcache[$log->module][$log->action])) {
495 $ld = $ldcache[$log->module][$log->action];
496 } else {
497 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
498 $ldcache[$log->module][$log->action] = $ld;
500 if (0 && $ld && !empty($log->info)) {
501 // ugly hack to make sure fullname is shown correctly
502 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
503 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
504 } else {
505 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
509 //Filter log->info
510 $log->info = format_string($log->info);
512 echo '<tr class="r'.$row.'">';
513 if ($course->id == SITEID) {
514 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
515 echo "<td class=\"r$row c0\" >\n";
516 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
517 echo "</td>\n";
519 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
520 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
521 echo "<td class=\"r$row c2\" >\n";
522 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
523 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
524 echo "</td>\n";
525 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
526 echo "<td class=\"r$row c3\" >\n";
527 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
528 echo "</td>\n";
529 echo "<td class=\"r$row c4\">\n";
530 echo $log->action .': '.$log->module;
531 echo "</td>\n";
532 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
533 echo "</tr>\n";
535 echo "</table>\n";
537 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
541 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
542 $modid, $modaction, $groupid) {
543 global $DB, $CFG;
545 require_once($CFG->libdir . '/csvlib.class.php');
547 $csvexporter = new csv_export_writer('tab');
549 $header = array();
550 $header[] = get_string('course');
551 $header[] = get_string('time');
552 $header[] = get_string('ip_address');
553 $header[] = get_string('fullnameuser');
554 $header[] = get_string('action');
555 $header[] = get_string('info');
557 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
558 $modname, $modid, $modaction, $groupid)) {
559 return false;
562 $courses = array();
564 if ($course->id == SITEID) {
565 $courses[0] = '';
566 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
567 foreach ($ccc as $cc) {
568 $courses[$cc->id] = $cc->shortname;
571 } else {
572 $courses[$course->id] = $course->shortname;
575 $count=0;
576 $ldcache = array();
577 $tt = getdate(time());
578 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
580 $strftimedatetime = get_string("strftimedatetime");
582 $csvexporter->set_filename('logs', '.txt');
583 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
584 $csvexporter->add_data($title);
585 $csvexporter->add_data($header);
587 if (empty($logs['logs'])) {
588 return true;
591 foreach ($logs['logs'] as $log) {
592 if (isset($ldcache[$log->module][$log->action])) {
593 $ld = $ldcache[$log->module][$log->action];
594 } else {
595 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
596 $ldcache[$log->module][$log->action] = $ld;
598 if ($ld && is_numeric($log->info)) {
599 // ugly hack to make sure fullname is shown correctly
600 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
601 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
602 } else {
603 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
607 //Filter log->info
608 $log->info = format_string($log->info);
609 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
611 $coursecontext = context_course::instance($course->id);
612 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
613 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
614 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
615 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
616 $csvexporter->add_data($row);
618 $csvexporter->download_file();
619 return true;
623 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
624 $modid, $modaction, $groupid) {
626 global $CFG, $DB;
628 require_once("$CFG->libdir/excellib.class.php");
630 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
631 $modname, $modid, $modaction, $groupid)) {
632 return false;
635 $courses = array();
637 if ($course->id == SITEID) {
638 $courses[0] = '';
639 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
640 foreach ($ccc as $cc) {
641 $courses[$cc->id] = $cc->shortname;
644 } else {
645 $courses[$course->id] = $course->shortname;
648 $count=0;
649 $ldcache = array();
650 $tt = getdate(time());
651 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
653 $strftimedatetime = get_string("strftimedatetime");
655 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
656 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
657 $filename .= '.xls';
659 $workbook = new MoodleExcelWorkbook('-');
660 $workbook->send($filename);
662 $worksheet = array();
663 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
664 get_string('fullnameuser'), get_string('action'), get_string('info'));
666 // Creating worksheets
667 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
668 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
669 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
670 $worksheet[$wsnumber]->set_column(1, 1, 30);
671 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
672 userdate(time(), $strftimedatetime));
673 $col = 0;
674 foreach ($headers as $item) {
675 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
676 $col++;
680 if (empty($logs['logs'])) {
681 $workbook->close();
682 return true;
685 $formatDate =& $workbook->add_format();
686 $formatDate->set_num_format(get_string('log_excel_date_format'));
688 $row = FIRSTUSEDEXCELROW;
689 $wsnumber = 1;
690 $myxls =& $worksheet[$wsnumber];
691 foreach ($logs['logs'] as $log) {
692 if (isset($ldcache[$log->module][$log->action])) {
693 $ld = $ldcache[$log->module][$log->action];
694 } else {
695 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
696 $ldcache[$log->module][$log->action] = $ld;
698 if ($ld && is_numeric($log->info)) {
699 // ugly hack to make sure fullname is shown correctly
700 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
701 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
702 } else {
703 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
707 // Filter log->info
708 $log->info = format_string($log->info);
709 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
711 if ($nroPages>1) {
712 if ($row > EXCELROWS) {
713 $wsnumber++;
714 $myxls =& $worksheet[$wsnumber];
715 $row = FIRSTUSEDEXCELROW;
719 $coursecontext = context_course::instance($course->id);
721 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
722 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
723 $myxls->write($row, 2, $log->ip, '');
724 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
725 $myxls->write($row, 3, $fullname, '');
726 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
727 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
728 $myxls->write($row, 5, $log->info, '');
730 $row++;
733 $workbook->close();
734 return true;
737 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
738 $modid, $modaction, $groupid) {
740 global $CFG, $DB;
742 require_once("$CFG->libdir/odslib.class.php");
744 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
745 $modname, $modid, $modaction, $groupid)) {
746 return false;
749 $courses = array();
751 if ($course->id == SITEID) {
752 $courses[0] = '';
753 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
754 foreach ($ccc as $cc) {
755 $courses[$cc->id] = $cc->shortname;
758 } else {
759 $courses[$course->id] = $course->shortname;
762 $count=0;
763 $ldcache = array();
764 $tt = getdate(time());
765 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
767 $strftimedatetime = get_string("strftimedatetime");
769 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
770 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
771 $filename .= '.ods';
773 $workbook = new MoodleODSWorkbook('-');
774 $workbook->send($filename);
776 $worksheet = array();
777 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
778 get_string('fullnameuser'), get_string('action'), get_string('info'));
780 // Creating worksheets
781 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
782 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
783 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
784 $worksheet[$wsnumber]->set_column(1, 1, 30);
785 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
786 userdate(time(), $strftimedatetime));
787 $col = 0;
788 foreach ($headers as $item) {
789 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
790 $col++;
794 if (empty($logs['logs'])) {
795 $workbook->close();
796 return true;
799 $formatDate =& $workbook->add_format();
800 $formatDate->set_num_format(get_string('log_excel_date_format'));
802 $row = FIRSTUSEDEXCELROW;
803 $wsnumber = 1;
804 $myxls =& $worksheet[$wsnumber];
805 foreach ($logs['logs'] as $log) {
806 if (isset($ldcache[$log->module][$log->action])) {
807 $ld = $ldcache[$log->module][$log->action];
808 } else {
809 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
810 $ldcache[$log->module][$log->action] = $ld;
812 if ($ld && is_numeric($log->info)) {
813 // ugly hack to make sure fullname is shown correctly
814 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
815 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
816 } else {
817 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
821 // Filter log->info
822 $log->info = format_string($log->info);
823 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
825 if ($nroPages>1) {
826 if ($row > EXCELROWS) {
827 $wsnumber++;
828 $myxls =& $worksheet[$wsnumber];
829 $row = FIRSTUSEDEXCELROW;
833 $coursecontext = context_course::instance($course->id);
835 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
836 $myxls->write_date($row, 1, $log->time);
837 $myxls->write_string($row, 2, $log->ip);
838 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
839 $myxls->write_string($row, 3, $fullname);
840 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
841 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
842 $myxls->write_string($row, 5, $log->info);
844 $row++;
847 $workbook->close();
848 return true;
852 * For a given course, returns an array of course activity objects
853 * Each item in the array contains he following properties:
855 function get_array_of_activities($courseid) {
856 // cm - course module id
857 // mod - name of the module (eg forum)
858 // section - the number of the section (eg week or topic)
859 // name - the name of the instance
860 // visible - is the instance visible or not
861 // groupingid - grouping id
862 // groupmembersonly - is this instance visible to group members only
863 // extra - contains extra string to include in any link
864 global $CFG, $DB;
865 if(!empty($CFG->enableavailability)) {
866 require_once($CFG->libdir.'/conditionlib.php');
869 $course = $DB->get_record('course', array('id'=>$courseid));
871 if (empty($course)) {
872 throw new moodle_exception('courseidnotfound');
875 $mod = array();
877 $rawmods = get_course_mods($courseid);
878 if (empty($rawmods)) {
879 return $mod; // always return array
882 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
883 foreach ($sections as $section) {
884 if (!empty($section->sequence)) {
885 $sequence = explode(",", $section->sequence);
886 foreach ($sequence as $seq) {
887 if (empty($rawmods[$seq])) {
888 continue;
890 $mod[$seq] = new stdClass();
891 $mod[$seq]->id = $rawmods[$seq]->instance;
892 $mod[$seq]->cm = $rawmods[$seq]->id;
893 $mod[$seq]->mod = $rawmods[$seq]->modname;
895 // Oh dear. Inconsistent names left here for backward compatibility.
896 $mod[$seq]->section = $section->section;
897 $mod[$seq]->sectionid = $rawmods[$seq]->section;
899 $mod[$seq]->module = $rawmods[$seq]->module;
900 $mod[$seq]->added = $rawmods[$seq]->added;
901 $mod[$seq]->score = $rawmods[$seq]->score;
902 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
903 $mod[$seq]->visible = $rawmods[$seq]->visible;
904 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
905 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
906 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
907 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
908 $mod[$seq]->indent = $rawmods[$seq]->indent;
909 $mod[$seq]->completion = $rawmods[$seq]->completion;
910 $mod[$seq]->extra = "";
911 $mod[$seq]->completiongradeitemnumber =
912 $rawmods[$seq]->completiongradeitemnumber;
913 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
914 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
915 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
916 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
917 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
918 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
919 if (!empty($CFG->enableavailability)) {
920 condition_info::fill_availability_conditions($rawmods[$seq]);
921 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
922 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
923 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
926 $modname = $mod[$seq]->mod;
927 $functionname = $modname."_get_coursemodule_info";
929 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
930 continue;
933 include_once("$CFG->dirroot/mod/$modname/lib.php");
935 if ($hasfunction = function_exists($functionname)) {
936 if ($info = $functionname($rawmods[$seq])) {
937 if (!empty($info->icon)) {
938 $mod[$seq]->icon = $info->icon;
940 if (!empty($info->iconcomponent)) {
941 $mod[$seq]->iconcomponent = $info->iconcomponent;
943 if (!empty($info->name)) {
944 $mod[$seq]->name = $info->name;
946 if ($info instanceof cached_cm_info) {
947 // When using cached_cm_info you can include three new fields
948 // that aren't available for legacy code
949 if (!empty($info->content)) {
950 $mod[$seq]->content = $info->content;
952 if (!empty($info->extraclasses)) {
953 $mod[$seq]->extraclasses = $info->extraclasses;
955 if (!empty($info->iconurl)) {
956 $mod[$seq]->iconurl = $info->iconurl;
958 if (!empty($info->onclick)) {
959 $mod[$seq]->onclick = $info->onclick;
961 if (!empty($info->customdata)) {
962 $mod[$seq]->customdata = $info->customdata;
964 } else {
965 // When using a stdclass, the (horrible) deprecated ->extra field
966 // is available for BC
967 if (!empty($info->extra)) {
968 $mod[$seq]->extra = $info->extra;
973 // When there is no modname_get_coursemodule_info function,
974 // but showdescriptions is enabled, then we use the 'intro'
975 // and 'introformat' fields in the module table
976 if (!$hasfunction && $rawmods[$seq]->showdescription) {
977 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
978 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
979 // Set content from intro and introformat. Filters are disabled
980 // because we filter it with format_text at display time
981 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
982 $modvalues, $rawmods[$seq]->id, false);
984 // To save making another query just below, put name in here
985 $mod[$seq]->name = $modvalues->name;
988 if (!isset($mod[$seq]->name)) {
989 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
992 // Minimise the database size by unsetting default options when they are
993 // 'empty'. This list corresponds to code in the cm_info constructor.
994 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
995 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
996 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
997 'availableuntil', 'conditionscompletion', 'conditionsgrade',
998 'completionview', 'completionexpected', 'score', 'showdescription')
999 as $property) {
1000 if (property_exists($mod[$seq], $property) &&
1001 empty($mod[$seq]->{$property})) {
1002 unset($mod[$seq]->{$property});
1005 // Special case: this value is usually set to null, but may be 0
1006 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1007 is_null($mod[$seq]->completiongradeitemnumber)) {
1008 unset($mod[$seq]->completiongradeitemnumber);
1014 return $mod;
1018 * Returns the localised human-readable names of all used modules
1020 * @param bool $plural if true returns the plural forms of the names
1021 * @return array where key is the module name (component name without 'mod_') and
1022 * the value is the human-readable string. Array sorted alphabetically by value
1024 function get_module_types_names($plural = false) {
1025 static $modnames = null;
1026 global $DB, $CFG;
1027 if ($modnames === null) {
1028 $modnames = array(0 => array(), 1 => array());
1029 if ($allmods = $DB->get_records("modules")) {
1030 foreach ($allmods as $mod) {
1031 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1032 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1033 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1036 collatorlib::asort($modnames[0]);
1037 collatorlib::asort($modnames[1]);
1040 return $modnames[(int)$plural];
1044 * Set highlighted section. Only one section can be highlighted at the time.
1046 * @param int $courseid course id
1047 * @param int $marker highlight section with this number, 0 means remove higlightin
1048 * @return void
1050 function course_set_marker($courseid, $marker) {
1051 global $DB;
1052 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1053 format_base::reset_course_cache($courseid);
1057 * For a given course section, marks it visible or hidden,
1058 * and does the same for every activity in that section
1060 * @param int $courseid course id
1061 * @param int $sectionnumber The section number to adjust
1062 * @param int $visibility The new visibility
1063 * @return array A list of resources which were hidden in the section
1065 function set_section_visible($courseid, $sectionnumber, $visibility) {
1066 global $DB;
1068 $resourcestotoggle = array();
1069 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1070 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1071 if (!empty($section->sequence)) {
1072 $modules = explode(",", $section->sequence);
1073 foreach ($modules as $moduleid) {
1074 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1075 if ($visibility) {
1076 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1077 set_coursemodule_visible($moduleid, $cm->visibleold);
1078 } else {
1079 // We hide the section, so we hide the module but we store the original state in visibleold.
1080 set_coursemodule_visible($moduleid, 0);
1081 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1086 rebuild_course_cache($courseid, true);
1088 // Determine which modules are visible for AJAX update
1089 if (!empty($modules)) {
1090 list($insql, $params) = $DB->get_in_or_equal($modules);
1091 $select = 'id ' . $insql . ' AND visible = ?';
1092 array_push($params, $visibility);
1093 if (!$visibility) {
1094 $select .= ' AND visibleold = 1';
1096 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1099 return $resourcestotoggle;
1103 * Retrieve all metadata for the requested modules
1105 * @param object $course The Course
1106 * @param array $modnames An array containing the list of modules and their
1107 * names
1108 * @param int $sectionreturn The section to return to
1109 * @return array A list of stdClass objects containing metadata about each
1110 * module
1112 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1113 global $CFG, $OUTPUT;
1115 // get_module_metadata will be called once per section on the page and courses may show
1116 // different modules to one another
1117 static $modlist = array();
1118 if (!isset($modlist[$course->id])) {
1119 $modlist[$course->id] = array();
1122 $return = array();
1123 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1124 if ($sectionreturn !== null) {
1125 $urlbase->param('sr', $sectionreturn);
1127 foreach($modnames as $modname => $modnamestr) {
1128 if (!course_allowed_module($course, $modname)) {
1129 continue;
1131 if (isset($modlist[$course->id][$modname])) {
1132 // This module is already cached
1133 $return[$modname] = $modlist[$course->id][$modname];
1134 continue;
1137 // Include the module lib
1138 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1139 if (!file_exists($libfile)) {
1140 continue;
1142 include_once($libfile);
1144 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1145 $gettypesfunc = $modname.'_get_types';
1146 if (function_exists($gettypesfunc)) {
1147 $types = $gettypesfunc();
1148 if (is_array($types) && count($types) > 0) {
1149 $group = new stdClass();
1150 $group->name = $modname;
1151 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1152 foreach($types as $type) {
1153 if ($type->typestr === '--') {
1154 continue;
1156 if (strpos($type->typestr, '--') === 0) {
1157 $group->title = str_replace('--', '', $type->typestr);
1158 continue;
1160 // Set the Sub Type metadata
1161 $subtype = new stdClass();
1162 $subtype->title = $type->typestr;
1163 $subtype->type = str_replace('&amp;', '&', $type->type);
1164 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1165 $subtype->archetype = $type->modclass;
1167 // The group archetype should match the subtype archetypes and all subtypes
1168 // should have the same archetype
1169 $group->archetype = $subtype->archetype;
1171 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1172 $subtype->help = get_string('help' . $subtype->name, $modname);
1174 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1175 $group->types[] = $subtype;
1177 $modlist[$course->id][$modname] = $group;
1179 } else {
1180 $module = new stdClass();
1181 $module->title = $modnamestr;
1182 $module->name = $modname;
1183 $module->link = new moodle_url($urlbase, array('add' => $modname));
1184 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1185 $sm = get_string_manager();
1186 if ($sm->string_exists('modulename_help', $modname)) {
1187 $module->help = get_string('modulename_help', $modname);
1188 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1189 $link = get_string('modulename_link', $modname);
1190 $linktext = get_string('morehelp');
1191 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1194 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1195 $modlist[$course->id][$modname] = $module;
1197 if (isset($modlist[$course->id][$modname])) {
1198 $return[$modname] = $modlist[$course->id][$modname];
1199 } else {
1200 debugging("Invalid module metadata configuration for {$modname}");
1204 return $return;
1208 * Return the course category context for the category with id $categoryid, except
1209 * that if $categoryid is 0, return the system context.
1211 * @param integer $categoryid a category id or 0.
1212 * @return object the corresponding context
1214 function get_category_or_system_context($categoryid) {
1215 if ($categoryid) {
1216 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1217 } else {
1218 return context_system::instance();
1223 * This function generates a structured array of courses and categories.
1225 * The depth of categories is limited by $CFG->maxcategorydepth however there
1226 * is no limit on the number of courses!
1228 * Suitable for use with the course renderers course_category_tree method:
1229 * $renderer = $PAGE->get_renderer('core','course');
1230 * echo $renderer->course_category_tree(get_course_category_tree());
1232 * @global moodle_database $DB
1233 * @param int $id
1234 * @param int $depth
1236 function get_course_category_tree($id = 0, $depth = 0) {
1237 global $DB, $CFG;
1238 require_once($CFG->libdir. '/coursecatlib.php');
1239 if (!$coursecat = coursecat::get($id, IGNORE_MISSING)) {
1240 return array();
1242 $categories = array();
1243 $categoryids = array();
1244 foreach ($coursecat->get_children() as $child) {
1245 $categories[] = $category = (object)convert_to_array($child);
1246 $categoryids[$category->id] = $category;
1247 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
1248 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
1249 foreach ($subcategories as $subid=>$subcat) {
1250 $categoryids[$subid] = $subcat;
1252 $category->courses = array();
1256 if ($depth > 0) {
1257 // This is a recursive call so return the required array
1258 return array($categories, $categoryids);
1261 if (empty($categoryids)) {
1262 // No categories available (probably all hidden).
1263 return array();
1266 // The depth is 0 this function has just been called so we can finish it off
1268 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1269 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
1270 $sql = "SELECT
1271 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
1272 $ccselect
1273 FROM {course} c
1274 $ccjoin
1275 WHERE c.category $catsql ORDER BY c.sortorder ASC";
1276 if ($courses = $DB->get_records_sql($sql, $catparams)) {
1277 // loop throught them
1278 foreach ($courses as $course) {
1279 if ($course->id == SITEID) {
1280 continue;
1282 context_instance_preload($course);
1283 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
1284 $categoryids[$course->category]->courses[$course->id] = $course;
1288 return $categories;
1292 * Recursive function to print out all the categories in a nice format
1293 * with or without courses included
1295 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1296 global $CFG;
1297 require_once($CFG->libdir. '/coursecatlib.php');
1299 // maxcategorydepth == 0 meant no limit
1300 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
1301 return;
1304 // make sure category is visible to the current user
1305 if ($category) {
1306 if (!$coursecat = coursecat::get($category->id, IGNORE_MISSING)) {
1307 return;
1309 } else {
1310 $coursecat = coursecat::get(0);
1313 if (!$categorycourses) {
1314 $categorycourses = get_category_courses_array($coursecat->id);
1317 if ($coursecat->id) {
1318 print_category_info($category, $depth, $showcourses, $categorycourses[$category->id]);
1321 if ($categories = $coursecat->get_children()) { // Print all the children recursively
1322 $countcats = count($categories);
1323 $count = 0;
1324 $first = true;
1325 $last = false;
1326 foreach ($categories as $cat) {
1327 $count++;
1328 if ($count == $countcats) {
1329 $last = true;
1331 $up = $first ? false : true;
1332 $down = $last ? false : true;
1333 $first = false;
1335 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses, $categorycourses);
1341 * Gets an array whose keys are category ids and whose values are arrays of courses in the corresponding category.
1343 * @param int $categoryid
1344 * @return array
1346 function get_category_courses_array($categoryid = 0) {
1347 $tree = get_course_category_tree($categoryid);
1348 $flattened = array();
1349 foreach ($tree as $category) {
1350 get_category_courses_array_recursively($flattened, $category);
1352 return $flattened;
1356 * Recursive function to help flatten the course category tree.
1358 * Do not call this function directly, instead calll its parent function {@link get_category_courses_array}
1360 * @param array &$flattened An array passed by reference in which to store courses for each category.
1361 * @param stdClass $category The category to get courses for.
1363 function get_category_courses_array_recursively(array &$flattened, $category) {
1364 $flattened[$category->id] = $category->courses;
1365 foreach ($category->categories as $childcategory) {
1366 get_category_courses_array_recursively($flattened, $childcategory);
1371 * Returns full course categories trees to be used in html_writer::select()
1373 * Calls {@link coursecat::make_categories_list()} to build the tree and
1374 * adds whitespace to denote nesting
1376 * @return array array mapping coursecat id to the display name
1378 function make_categories_options() {
1379 global $CFG;
1380 require_once($CFG->libdir. '/coursecatlib.php');
1381 $cats = coursecat::make_categories_list();
1382 foreach ($cats as $key => $value) {
1383 $cats[$key] = str_repeat('&nbsp;', coursecat::get($key)->depth - 1). $value;
1385 return $cats;
1389 * Prints the category information.
1391 * This function is only used by print_whole_category_list() above
1393 * @param stdClass $category
1394 * @param int $depth The depth of the category.
1395 * @param bool $showcourses If set to true course information will also be printed.
1396 * @param array|null $courses An array of courses belonging to the category, or null if you don't have it yet.
1398 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1399 global $CFG, $DB, $OUTPUT;
1401 $strsummary = get_string('summary');
1403 $catlinkcss = null;
1404 if (!$category->visible) {
1405 $catlinkcss = array('class'=>'dimmed');
1407 static $coursecount = null;
1408 if (null === $coursecount) {
1409 // only need to check this once
1410 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
1413 if ($showcourses and $coursecount) {
1414 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
1415 } else {
1416 $catimage = "&nbsp;";
1419 if (is_null($courses)) {
1420 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
1422 $context = context_coursecat::instance($category->id);
1423 $fullname = format_string($category->name, true, array('context' => $context));
1425 if ($showcourses and $coursecount) {
1426 echo '<div class="categorylist clearfix">';
1427 $cat = '';
1428 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
1429 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
1430 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
1432 $html = '';
1433 if ($depth > 0) {
1434 for ($i=0; $i< $depth; $i++) {
1435 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
1436 $cat = '';
1438 } else {
1439 $html = $cat;
1441 echo html_writer::tag('div', $html, array('class'=>'category'));
1442 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
1444 // does the depth exceed maxcategorydepth
1445 // maxcategorydepth == 0 or unset meant no limit
1446 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
1447 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
1448 foreach ($courses as $course) {
1449 $linkcss = null;
1450 if (!$course->visible) {
1451 $linkcss = array('class'=>'dimmed');
1454 $coursename = get_course_display_name_for_list($course);
1455 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
1457 // print enrol info
1458 $courseicon = '';
1459 if ($icons = enrol_get_course_info_icons($course)) {
1460 foreach ($icons as $pix_icon) {
1461 $courseicon = $OUTPUT->render($pix_icon);
1465 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
1467 if ($course->summary) {
1468 $link = new moodle_url('/course/info.php?id='.$course->id);
1469 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
1470 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
1471 array('title'=>$strsummary));
1473 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
1476 $html = '';
1477 for ($i=0; $i <= $depth; $i++) {
1478 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
1479 $coursecontent = '';
1481 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
1484 echo '</div>';
1485 } else {
1486 echo '<div class="categorylist">';
1487 $html = '';
1488 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
1489 if (count($courses) > 0) {
1490 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
1493 if ($depth > 0) {
1494 for ($i=0; $i< $depth; $i++) {
1495 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
1496 $cat = '';
1498 } else {
1499 $html = $cat;
1502 echo html_writer::tag('div', $html, array('class'=>'category'));
1503 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
1504 echo '</div>';
1509 * Print the buttons relating to course requests.
1511 * @param object $systemcontext the system context.
1513 function print_course_request_buttons($systemcontext) {
1514 global $CFG, $DB, $OUTPUT;
1515 if (empty($CFG->enablecourserequests)) {
1516 return;
1518 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
1519 /// Print a button to request a new course
1520 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
1522 /// Print a button to manage pending requests
1523 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
1524 $disabled = !$DB->record_exists('course_request', array());
1525 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
1530 * Does the user have permission to edit things in this category?
1532 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1533 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1535 function can_edit_in_category($categoryid = 0) {
1536 $context = get_category_or_system_context($categoryid);
1537 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1541 * Print courses in category. If category is 0 then all courses are printed.
1542 * @param int|stdClass $category category object or id.
1543 * @return bool true if courses found and printed, else false.
1545 function print_courses($category) {
1546 global $CFG, $OUTPUT;
1547 require_once($CFG->libdir. '/coursecatlib.php');
1549 if (!is_object($category) && $category==0) {
1550 $categories = coursecat::get(0)->get_children(); // Parent = 0 ie top-level categories only
1551 if (is_array($categories) && count($categories) == 1) {
1552 $category = array_shift($categories);
1553 $courses = get_courses_wmanagers($category->id,
1554 'c.sortorder ASC',
1555 array('summary','summaryformat'));
1556 } else {
1557 $courses = get_courses_wmanagers('all',
1558 'c.sortorder ASC',
1559 array('summary','summaryformat'));
1561 unset($categories);
1562 } else {
1563 $courses = get_courses_wmanagers($category->id,
1564 'c.sortorder ASC',
1565 array('summary','summaryformat'));
1568 if ($courses) {
1569 echo html_writer::start_tag('ul', array('class'=>'unlist'));
1570 foreach ($courses as $course) {
1571 $coursecontext = context_course::instance($course->id);
1572 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
1573 echo html_writer::start_tag('li');
1574 print_course($course);
1575 echo html_writer::end_tag('li');
1578 echo html_writer::end_tag('ul');
1579 } else {
1580 echo $OUTPUT->heading(get_string("nocoursesyet"));
1581 $context = context_system::instance();
1582 if (has_capability('moodle/course:create', $context)) {
1583 $options = array();
1584 if (!empty($category->id)) {
1585 $options['category'] = $category->id;
1586 } else {
1587 $options['category'] = $CFG->defaultrequestcategory;
1589 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
1590 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
1591 echo html_writer::end_tag('div');
1592 return false;
1595 return true;
1599 * Print a description of a course, suitable for browsing in a list.
1601 * @param object $course the course object.
1602 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
1604 function print_course($course, $highlightterms = '') {
1605 global $CFG, $USER, $DB, $OUTPUT;
1607 $context = context_course::instance($course->id);
1609 // Rewrite file URLs so that they are correct
1610 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
1612 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
1613 echo html_writer::start_tag('div', array('class'=>'info'));
1614 echo html_writer::start_tag('h3', array('class'=>'name'));
1616 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
1618 $coursename = get_course_display_name_for_list($course);
1619 $linktext = highlight($highlightterms, format_string($coursename));
1620 $linkparams = array('title'=>get_string('entercourse'));
1621 if (empty($course->visible)) {
1622 $linkparams['class'] = 'dimmed';
1624 echo html_writer::link($linkhref, $linktext, $linkparams);
1625 echo html_writer::end_tag('h3');
1627 /// first find all roles that are supposed to be displayed
1628 if (!empty($CFG->coursecontact)) {
1629 $managerroles = explode(',', $CFG->coursecontact);
1630 $rusers = array();
1632 if (!isset($course->managers)) {
1633 list($sort, $sortparams) = users_order_by_sql('u');
1634 $rusers = get_role_users($managerroles, $context, true,
1635 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
1636 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
1637 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
1638 } else {
1639 // use the managers array if we have it for perf reasosn
1640 // populate the datastructure like output of get_role_users();
1641 foreach ($course->managers as $manager) {
1642 $user = clone($manager->user);
1643 $user->roleid = $manager->roleid;
1644 $user->rolename = $manager->rolename;
1645 $user->roleshortname = $manager->roleshortname;
1646 $user->rolecoursealias = $manager->rolecoursealias;
1647 $rusers[$user->id] = $user;
1651 $namesarray = array();
1652 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1653 foreach ($rusers as $ra) {
1654 if (isset($namesarray[$ra->id])) {
1655 // only display a user once with the higest sortorder role
1656 continue;
1659 $role = new stdClass();
1660 $role->id = $ra->roleid;
1661 $role->name = $ra->rolename;
1662 $role->shortname = $ra->roleshortname;
1663 $role->coursealias = $ra->rolecoursealias;
1664 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
1666 $fullname = fullname($ra, $canviewfullnames);
1667 $namesarray[$ra->id] = $rolename.': '.
1668 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
1671 if (!empty($namesarray)) {
1672 echo html_writer::start_tag('ul', array('class'=>'teachers'));
1673 foreach ($namesarray as $name) {
1674 echo html_writer::tag('li', $name);
1676 echo html_writer::end_tag('ul');
1679 echo html_writer::end_tag('div'); // End of info div
1681 echo html_writer::start_tag('div', array('class'=>'summary'));
1682 $options = new stdClass();
1683 $options->noclean = true;
1684 $options->para = false;
1685 $options->overflowdiv = true;
1686 if (!isset($course->summaryformat)) {
1687 $course->summaryformat = FORMAT_MOODLE;
1689 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
1690 if ($icons = enrol_get_course_info_icons($course)) {
1691 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
1692 foreach ($icons as $icon) {
1693 $icon->attributes["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
1694 echo $OUTPUT->render($icon);
1696 echo html_writer::end_tag('div'); // End of enrolmenticons div
1698 echo html_writer::end_tag('div'); // End of summary div
1699 echo html_writer::end_tag('div'); // End of coursebox div
1703 * Prints custom user information on the home page.
1704 * Over time this can include all sorts of information
1706 function print_my_moodle() {
1707 global $USER, $CFG, $DB, $OUTPUT;
1709 if (!isloggedin() or isguestuser()) {
1710 print_error('nopermissions', '', '', 'See My Moodle');
1713 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
1714 $rhosts = array();
1715 $rcourses = array();
1716 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1717 $rcourses = get_my_remotecourses($USER->id);
1718 $rhosts = get_my_remotehosts();
1721 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1723 if (!empty($courses)) {
1724 echo '<ul class="unlist">';
1725 foreach ($courses as $course) {
1726 if ($course->id == SITEID) {
1727 continue;
1729 echo '<li>';
1730 print_course($course);
1731 echo "</li>\n";
1733 echo "</ul>\n";
1736 // MNET
1737 if (!empty($rcourses)) {
1738 // at the IDP, we know of all the remote courses
1739 foreach ($rcourses as $course) {
1740 print_remote_course($course, "100%");
1742 } elseif (!empty($rhosts)) {
1743 // non-IDP, we know of all the remote servers, but not courses
1744 foreach ($rhosts as $host) {
1745 print_remote_host($host, "100%");
1748 unset($course);
1749 unset($host);
1751 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
1752 echo "<table width=\"100%\"><tr><td align=\"center\">";
1753 print_course_search("", false, "short");
1754 echo "</td><td align=\"center\">";
1755 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
1756 echo "</td></tr></table>\n";
1759 } else {
1760 if ($DB->count_records("course_categories") > 1) {
1761 echo $OUTPUT->box_start("categorybox");
1762 print_whole_category_list();
1763 echo $OUTPUT->box_end();
1764 } else {
1765 print_courses(0);
1771 function print_course_search($value="", $return=false, $format="plain") {
1772 global $CFG;
1773 static $count = 0;
1775 $count++;
1777 $id = 'coursesearch';
1779 if ($count > 1) {
1780 $id .= $count;
1783 $strsearchcourses= get_string("searchcourses");
1785 if ($format == 'plain') {
1786 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1787 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1788 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1789 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
1790 $output .= '<input type="submit" value="'.get_string('go').'" />';
1791 $output .= '</fieldset></form>';
1792 } else if ($format == 'short') {
1793 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1794 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1795 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
1796 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" value="'.s($value).'" />';
1797 $output .= '<input type="submit" value="'.get_string('go').'" />';
1798 $output .= '</fieldset></form>';
1799 } else if ($format == 'navbar') {
1800 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
1801 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1802 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
1803 $output .= '<input type="text" id="navsearchbox" size="20" name="search" value="'.s($value).'" />';
1804 $output .= '<input type="submit" value="'.get_string('go').'" />';
1805 $output .= '</fieldset></form>';
1808 if ($return) {
1809 return $output;
1811 echo $output;
1814 function print_remote_course($course, $width="100%") {
1815 global $CFG, $USER;
1817 $linkcss = '';
1819 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
1821 echo '<div class="coursebox remotecoursebox clearfix">';
1822 echo '<div class="info">';
1823 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1824 $linkcss.' href="'.$url.'">'
1825 . format_string($course->fullname) .'</a><br />'
1826 . format_string($course->hostname) . ' : '
1827 . format_string($course->cat_name) . ' : '
1828 . format_string($course->shortname). '</div>';
1829 echo '</div><div class="summary">';
1830 $options = new stdClass();
1831 $options->noclean = true;
1832 $options->para = false;
1833 $options->overflowdiv = true;
1834 echo format_text($course->summary, $course->summaryformat, $options);
1835 echo '</div>';
1836 echo '</div>';
1839 function print_remote_host($host, $width="100%") {
1840 global $OUTPUT;
1842 $linkcss = '';
1844 echo '<div class="coursebox clearfix">';
1845 echo '<div class="info">';
1846 echo '<div class="name">';
1847 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
1848 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1849 . s($host['name']).'</a> - ';
1850 echo $host['count'] . ' ' . get_string('courses');
1851 echo '</div>';
1852 echo '</div>';
1853 echo '</div>';
1857 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1859 function add_course_module($mod) {
1860 global $DB;
1862 $mod->added = time();
1863 unset($mod->id);
1865 $cmid = $DB->insert_record("course_modules", $mod);
1866 rebuild_course_cache($mod->course, true);
1867 return $cmid;
1871 * Creates missing course section(s) and rebuilds course cache
1873 * @param int|stdClass $courseorid course id or course object
1874 * @param int|array $sections list of relative section numbers to create
1875 * @return bool if there were any sections created
1877 function course_create_sections_if_missing($courseorid, $sections) {
1878 global $DB;
1879 if (!is_array($sections)) {
1880 $sections = array($sections);
1882 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1883 if (is_object($courseorid)) {
1884 $courseorid = $courseorid->id;
1886 $coursechanged = false;
1887 foreach ($sections as $sectionnum) {
1888 if (!in_array($sectionnum, $existing)) {
1889 $cw = new stdClass();
1890 $cw->course = $courseorid;
1891 $cw->section = $sectionnum;
1892 $cw->summary = '';
1893 $cw->summaryformat = FORMAT_HTML;
1894 $cw->sequence = '';
1895 $id = $DB->insert_record("course_sections", $cw);
1896 $coursechanged = true;
1899 if ($coursechanged) {
1900 rebuild_course_cache($courseorid, true);
1902 return $coursechanged;
1906 * Adds an existing module to the section
1908 * Updates both tables {course_sections} and {course_modules}
1910 * @param int|stdClass $courseorid course id or course object
1911 * @param int $cmid id of the module already existing in course_modules table
1912 * @param int $sectionnum relative number of the section (field course_sections.section)
1913 * If section does not exist it will be created
1914 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1915 * before which the module needs to be included. Null for inserting in the
1916 * end of the section
1917 * @return int The course_sections ID where the module is inserted
1919 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1920 global $DB, $COURSE;
1921 if (is_object($beforemod)) {
1922 $beforemod = $beforemod->id;
1924 if (is_object($courseorid)) {
1925 $courseid = $courseorid->id;
1926 } else {
1927 $courseid = $courseorid;
1929 course_create_sections_if_missing($courseorid, $sectionnum);
1930 // Do not try to use modinfo here, there is no guarantee it is valid!
1931 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
1932 $modarray = explode(",", trim($section->sequence));
1933 if (empty($section->sequence)) {
1934 $newsequence = "$cmid";
1935 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1936 $insertarray = array($cmid, $beforemod);
1937 array_splice($modarray, $key[0], 1, $insertarray);
1938 $newsequence = implode(",", $modarray);
1939 } else {
1940 $newsequence = "$section->sequence,$cmid";
1942 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1943 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1944 if (is_object($courseorid)) {
1945 rebuild_course_cache($courseorid->id, true);
1946 } else {
1947 rebuild_course_cache($courseorid, true);
1949 return $section->id; // Return course_sections ID that was used.
1952 function set_coursemodule_groupmode($id, $groupmode) {
1953 global $DB;
1954 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1955 if ($cm->groupmode != $groupmode) {
1956 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1957 rebuild_course_cache($cm->course, true);
1959 return ($cm->groupmode != $groupmode);
1962 function set_coursemodule_idnumber($id, $idnumber) {
1963 global $DB;
1964 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1965 if ($cm->idnumber != $idnumber) {
1966 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1967 rebuild_course_cache($cm->course, true);
1969 return ($cm->idnumber != $idnumber);
1973 * Set the visibility of a module and inherent properties.
1975 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1976 * has been moved to {@link set_section_visible()} which was the only place from which
1977 * the parameter was used.
1979 * @param int $id of the module
1980 * @param int $visible state of the module
1981 * @return bool false when the module was not found, true otherwise
1983 function set_coursemodule_visible($id, $visible) {
1984 global $DB, $CFG;
1985 require_once($CFG->libdir.'/gradelib.php');
1987 // Trigger developer's attention when using the previously removed argument.
1988 if (func_num_args() > 2) {
1989 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1990 has been removed.', DEBUG_DEVELOPER);
1993 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1994 return false;
1997 // Create events and propagate visibility to associated grade items if the value has changed.
1998 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1999 if ($cm->visible == $visible) {
2000 return true;
2003 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2004 return false;
2006 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2007 foreach($events as $event) {
2008 if ($visible) {
2009 show_event($event);
2010 } else {
2011 hide_event($event);
2016 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2017 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2018 if ($grade_items) {
2019 foreach ($grade_items as $grade_item) {
2020 $grade_item->set_hidden(!$visible);
2024 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2025 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2026 $cminfo = new stdClass();
2027 $cminfo->id = $id;
2028 $cminfo->visible = $visible;
2029 $cminfo->visibleold = $visible;
2030 $DB->update_record('course_modules', $cminfo);
2032 rebuild_course_cache($cm->course, true);
2033 return true;
2037 * This function will handles the whole deletion process of a module. This includes calling
2038 * the modules delete_instance function, deleting files, events, grades, conditional data,
2039 * the data in the course_module and course_sections table and adding a module deletion
2040 * event to the DB.
2042 * @param int $cmid the course module id
2043 * @since 2.5
2045 function course_delete_module($cmid) {
2046 global $CFG, $DB, $USER;
2048 require_once($CFG->libdir.'/gradelib.php');
2049 require_once($CFG->dirroot.'/blog/lib.php');
2051 // Get the course module.
2052 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
2053 return true;
2056 // Get the module context.
2057 $modcontext = context_module::instance($cm->id);
2059 // Get the course module name.
2060 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
2062 // Get the file location of the delete_instance function for this module.
2063 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
2065 // Include the file required to call the delete_instance function for this module.
2066 if (file_exists($modlib)) {
2067 require_once($modlib);
2068 } else {
2069 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
2070 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
2073 $deleteinstancefunction = $modulename . '_delete_instance';
2075 // Ensure the delete_instance function exists for this module.
2076 if (!function_exists($deleteinstancefunction)) {
2077 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
2078 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
2081 // Call the delete_instance function, if it returns false throw an exception.
2082 if (!$deleteinstancefunction($cm->instance)) {
2083 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
2084 "Cannot delete the module $modulename (instance).");
2087 // Remove all module files in case modules forget to do that.
2088 $fs = get_file_storage();
2089 $fs->delete_area_files($modcontext->id);
2091 // Delete events from calendar.
2092 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
2093 foreach($events as $event) {
2094 delete_event($event->id);
2098 // Delete grade items, outcome items and grades attached to modules.
2099 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
2100 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
2101 foreach ($grade_items as $grade_item) {
2102 $grade_item->delete('moddelete');
2106 // Delete completion and availability data; it is better to do this even if the
2107 // features are not turned on, in case they were turned on previously (these will be
2108 // very quick on an empty table).
2109 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2110 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2111 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2112 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2113 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2115 // Delete the context.
2116 delete_context(CONTEXT_MODULE, $cm->id);
2118 // Delete the module from the course_modules table.
2119 $DB->delete_records('course_modules', array('id' => $cm->id));
2121 // Delete module from that section.
2122 if (!delete_mod_from_section($cm->id, $cm->section)) {
2123 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
2124 "Cannot delete the module $modulename (instance) from section.");
2127 // Trigger a mod_deleted event with information about this module.
2128 $eventdata = new stdClass();
2129 $eventdata->modulename = $modulename;
2130 $eventdata->cmid = $cm->id;
2131 $eventdata->courseid = $cm->course;
2132 $eventdata->userid = $USER->id;
2133 events_trigger('mod_deleted', $eventdata);
2135 add_to_log($cm->course, 'course', "delete mod",
2136 "view.php?id=$cm->course",
2137 "$modulename $cm->instance", $cm->id);
2139 rebuild_course_cache($cm->course, true);
2142 function delete_mod_from_section($modid, $sectionid) {
2143 global $DB;
2145 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2147 $modarray = explode(",", $section->sequence);
2149 if ($key = array_keys ($modarray, $modid)) {
2150 array_splice($modarray, $key[0], 1);
2151 $newsequence = implode(",", $modarray);
2152 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2153 rebuild_course_cache($section->course, true);
2154 return true;
2155 } else {
2156 return false;
2160 return false;
2164 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2166 * @param object $course course object
2167 * @param int $section Section number (not id!!!)
2168 * @param int $move (-1 or 1)
2169 * @return boolean true if section moved successfully
2170 * @todo MDL-33379 remove this function in 2.5
2172 function move_section($course, $section, $move) {
2173 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2175 /// Moves a whole course section up and down within the course
2176 global $USER;
2178 if (!$move) {
2179 return true;
2182 $sectiondest = $section + $move;
2184 // compartibility with course formats using field 'numsections'
2185 $courseformatoptions = course_get_format($course)->get_format_options();
2186 if (array_key_exists('numsections', $courseformatoptions) &&
2187 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2188 return false;
2191 $retval = move_section_to($course, $section, $sectiondest);
2192 return $retval;
2196 * Moves a section within a course, from a position to another.
2197 * Be very careful: $section and $destination refer to section number,
2198 * not id!.
2200 * @param object $course
2201 * @param int $section Section number (not id!!!)
2202 * @param int $destination
2203 * @return boolean Result
2205 function move_section_to($course, $section, $destination) {
2206 /// Moves a whole course section up and down within the course
2207 global $USER, $DB;
2209 if (!$destination && $destination != 0) {
2210 return true;
2213 // compartibility with course formats using field 'numsections'
2214 $courseformatoptions = course_get_format($course)->get_format_options();
2215 if ((array_key_exists('numsections', $courseformatoptions) &&
2216 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
2217 return false;
2220 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2221 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2222 'section ASC, id ASC', 'id, section')) {
2223 return false;
2226 $movedsections = reorder_sections($sections, $section, $destination);
2228 // Update all sections. Do this in 2 steps to avoid breaking database
2229 // uniqueness constraint
2230 $transaction = $DB->start_delegated_transaction();
2231 foreach ($movedsections as $id => $position) {
2232 if ($sections[$id] !== $position) {
2233 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2236 foreach ($movedsections as $id => $position) {
2237 if ($sections[$id] !== $position) {
2238 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2242 // If we move the highlighted section itself, then just highlight the destination.
2243 // Adjust the higlighted section location if we move something over it either direction.
2244 if ($section == $course->marker) {
2245 course_set_marker($course->id, $destination);
2246 } elseif ($section > $course->marker && $course->marker >= $destination) {
2247 course_set_marker($course->id, $course->marker+1);
2248 } elseif ($section < $course->marker && $course->marker <= $destination) {
2249 course_set_marker($course->id, $course->marker-1);
2252 $transaction->allow_commit();
2253 rebuild_course_cache($course->id, true);
2254 return true;
2258 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2259 * an original position number and a target position number, rebuilds the array so that the
2260 * move is made without any duplication of section positions.
2261 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2262 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2264 * @param array $sections
2265 * @param int $origin_position
2266 * @param int $target_position
2267 * @return array
2269 function reorder_sections($sections, $origin_position, $target_position) {
2270 if (!is_array($sections)) {
2271 return false;
2274 // We can't move section position 0
2275 if ($origin_position < 1) {
2276 echo "We can't move section position 0";
2277 return false;
2280 // Locate origin section in sections array
2281 if (!$origin_key = array_search($origin_position, $sections)) {
2282 echo "searched position not in sections array";
2283 return false; // searched position not in sections array
2286 // Extract origin section
2287 $origin_section = $sections[$origin_key];
2288 unset($sections[$origin_key]);
2290 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2291 $found = false;
2292 $append_array = array();
2293 foreach ($sections as $id => $position) {
2294 if ($found) {
2295 $append_array[$id] = $position;
2296 unset($sections[$id]);
2298 if ($position == $target_position) {
2299 if ($target_position < $origin_position) {
2300 $append_array[$id] = $position;
2301 unset($sections[$id]);
2303 $found = true;
2307 // Append moved section
2308 $sections[$origin_key] = $origin_section;
2310 // Append rest of array (if applicable)
2311 if (!empty($append_array)) {
2312 foreach ($append_array as $id => $position) {
2313 $sections[$id] = $position;
2317 // Renumber positions
2318 $position = 0;
2319 foreach ($sections as $id => $p) {
2320 $sections[$id] = $position;
2321 $position++;
2324 return $sections;
2329 * Move the module object $mod to the specified $section
2330 * If $beforemod exists then that is the module
2331 * before which $modid should be inserted
2332 * All parameters are objects
2334 function moveto_module($mod, $section, $beforemod=NULL) {
2335 global $OUTPUT, $DB;
2337 /// Remove original module from original section
2338 if (! delete_mod_from_section($mod->id, $mod->section)) {
2339 echo $OUTPUT->notification("Could not delete module from existing section");
2342 // if moving to a hidden section then hide module
2343 if ($mod->section != $section->id) {
2344 if (!$section->visible && $mod->visible) {
2345 // Set this in the object because it is sent as a response to ajax calls.
2346 $mod->visible = 0;
2347 set_coursemodule_visible($mod->id, 0);
2348 // Set visibleold to 1 so module will be visible when section is made visible.
2349 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
2351 if ($section->visible && !$mod->visible) {
2352 set_coursemodule_visible($mod->id, $mod->visibleold);
2353 // Set this in the object because it is sent as a response to ajax calls.
2354 $mod->visible = $mod->visibleold;
2358 /// Add the module into the new section
2359 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
2360 return true;
2364 * Returns the list of all editing actions that current user can perform on the module
2366 * @param cm_info $mod The module to produce editing buttons for
2367 * @param int $indent The current indenting (default -1 means no move left-right actions)
2368 * @param int $sr The section to link back to (used for creating the links)
2369 * @return array array of action_link or pix_icon objects
2371 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
2372 global $COURSE, $SITE;
2374 static $str;
2376 $coursecontext = context_course::instance($mod->course);
2377 $modcontext = context_module::instance($mod->id);
2379 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
2380 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
2382 // no permission to edit anything
2383 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
2384 return array();
2387 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2389 if (!isset($str)) {
2390 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
2391 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
2392 $str->assign = get_string('assignroles', 'role');
2393 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
2394 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
2395 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
2396 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
2397 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
2398 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
2401 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2403 if ($sr !== null) {
2404 $baseurl->param('sr', $sr);
2406 $actions = array();
2408 // AJAX edit title
2409 if ($mod->has_view() && $hasmanageactivities &&
2410 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
2411 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
2412 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2413 $actions['title'] = new action_link(
2414 new moodle_url($baseurl, array('update' => $mod->id)),
2415 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2416 null,
2417 array('class' => 'editing_title', 'title' => $str->edittitle)
2421 // leftright
2422 if ($hasmanageactivities) {
2423 if (right_to_left()) { // Exchange arrows on RTL
2424 $rightarrow = 't/left';
2425 $leftarrow = 't/right';
2426 } else {
2427 $rightarrow = 't/right';
2428 $leftarrow = 't/left';
2431 if ($indent > 0) {
2432 $actions['moveleft'] = new action_link(
2433 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
2434 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2435 null,
2436 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
2439 if ($indent >= 0) {
2440 $actions['moveright'] = new action_link(
2441 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
2442 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2443 null,
2444 array('class' => 'editing_moveright', 'title' => $str->moveright)
2449 // move
2450 if ($hasmanageactivities) {
2451 $actions['move'] = new action_link(
2452 new moodle_url($baseurl, array('copy' => $mod->id)),
2453 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2454 null,
2455 array('class' => 'editing_move', 'title' => $str->move)
2459 // Update
2460 if ($hasmanageactivities) {
2461 $actions['update'] = new action_link(
2462 new moodle_url($baseurl, array('update' => $mod->id)),
2463 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2464 null,
2465 array('class' => 'editing_update', 'title' => $str->update)
2469 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2470 // note that restoring on front page is never allowed
2471 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
2472 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
2473 $actions['duplicate'] = new action_link(
2474 new moodle_url($baseurl, array('duplicate' => $mod->id)),
2475 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2476 null,
2477 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
2481 // Delete
2482 if ($hasmanageactivities) {
2483 $actions['delete'] = new action_link(
2484 new moodle_url($baseurl, array('delete' => $mod->id)),
2485 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2486 null,
2487 array('class' => 'editing_delete', 'title' => $str->delete)
2491 // hideshow
2492 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2493 if ($mod->visible) {
2494 $actions['hide'] = new action_link(
2495 new moodle_url($baseurl, array('hide' => $mod->id)),
2496 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2497 null,
2498 array('class' => 'editing_hide', 'title' => $str->hide)
2500 } else {
2501 $actions['show'] = new action_link(
2502 new moodle_url($baseurl, array('show' => $mod->id)),
2503 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2504 null,
2505 array('class' => 'editing_show', 'title' => $str->show)
2510 // groupmode
2511 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
2512 if ($mod->coursegroupmodeforce) {
2513 $modgroupmode = $mod->coursegroupmode;
2514 } else {
2515 $modgroupmode = $mod->groupmode;
2517 if ($modgroupmode == SEPARATEGROUPS) {
2518 $groupmode = NOGROUPS;
2519 $grouptitle = $str->groupsseparate;
2520 $forcedgrouptitle = $str->forcedgroupsseparate;
2521 $actionname = 'groupsseparate';
2522 $groupimage = 't/groups';
2523 } else if ($modgroupmode == VISIBLEGROUPS) {
2524 $groupmode = SEPARATEGROUPS;
2525 $grouptitle = $str->groupsvisible;
2526 $forcedgrouptitle = $str->forcedgroupsvisible;
2527 $actionname = 'groupsvisible';
2528 $groupimage = 't/groupv';
2529 } else {
2530 $groupmode = VISIBLEGROUPS;
2531 $grouptitle = $str->groupsnone;
2532 $forcedgrouptitle = $str->forcedgroupsnone;
2533 $actionname = 'groupsnone';
2534 $groupimage = 't/groupn';
2536 if (!$mod->coursegroupmodeforce) {
2537 $actions[$actionname] = new action_link(
2538 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
2539 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2540 null,
2541 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
2543 } else {
2544 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
2548 // Assign
2549 if (has_capability('moodle/role:assign', $modcontext)){
2550 $actions['assign'] = new action_link(
2551 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
2552 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2553 null,
2554 array('class' => 'editing_assign', 'title' => $str->assign)
2558 return $actions;
2562 * given a course object with shortname & fullname, this function will
2563 * truncate the the number of chars allowed and add ... if it was too long
2565 function course_format_name ($course,$max=100) {
2567 $context = context_course::instance($course->id);
2568 $shortname = format_string($course->shortname, true, array('context' => $context));
2569 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2570 $str = $shortname.': '. $fullname;
2571 if (textlib::strlen($str) <= $max) {
2572 return $str;
2574 else {
2575 return textlib::substr($str,0,$max-3).'...';
2580 * Is the user allowed to add this type of module to this course?
2581 * @param object $course the course settings. Only $course->id is used.
2582 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2583 * @return bool whether the current user is allowed to add this type of module to this course.
2585 function course_allowed_module($course, $modname) {
2586 if (is_numeric($modname)) {
2587 throw new coding_exception('Function course_allowed_module no longer
2588 supports numeric module ids. Please update your code to pass the module name.');
2591 $capability = 'mod/' . $modname . ':addinstance';
2592 if (!get_capability_info($capability)) {
2593 // Debug warning that the capability does not exist, but no more than once per page.
2594 static $warned = array();
2595 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2596 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2597 debugging('The module ' . $modname . ' does not define the standard capability ' .
2598 $capability , DEBUG_DEVELOPER);
2599 $warned[$modname] = 1;
2602 // If the capability does not exist, the module can always be added.
2603 return true;
2606 $coursecontext = context_course::instance($course->id);
2607 return has_capability($capability, $coursecontext);
2611 * Efficiently moves many courses around while maintaining
2612 * sortorder in order.
2614 * @param array $courseids is an array of course ids
2615 * @param int $categoryid
2616 * @return bool success
2618 function move_courses($courseids, $categoryid) {
2619 global $CFG, $DB, $OUTPUT;
2621 if (empty($courseids)) {
2622 // nothing to do
2623 return;
2626 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2627 return false;
2630 $courseids = array_reverse($courseids);
2631 $newparent = context_coursecat::instance($category->id);
2632 $i = 1;
2634 foreach ($courseids as $courseid) {
2635 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2636 $course = new stdClass();
2637 $course->id = $courseid;
2638 $course->category = $category->id;
2639 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2640 if ($category->visible == 0) {
2641 // hide the course when moving into hidden category,
2642 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2643 $course->visible = 0;
2646 $DB->update_record('course', $course);
2647 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
2649 $context = context_course::instance($course->id);
2650 context_moved($context, $newparent);
2653 fix_course_sortorder();
2654 cache_helper::purge_by_event('changesincourse');
2656 return true;
2660 * Returns the display name of the given section that the course prefers
2662 * Implementation of this function is provided by course format
2663 * @see format_base::get_section_name()
2665 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2666 * @param int|stdClass $section Section object from database or just field course_sections.section
2667 * @return string Display name that the course format prefers, e.g. "Week 2"
2669 function get_section_name($courseorid, $section) {
2670 return course_get_format($courseorid)->get_section_name($section);
2674 * Tells if current course format uses sections
2676 * @param string $format Course format ID e.g. 'weeks' $course->format
2677 * @return bool
2679 function course_format_uses_sections($format) {
2680 $course = new stdClass();
2681 $course->format = $format;
2682 return course_get_format($course)->uses_sections();
2686 * Returns the information about the ajax support in the given source format
2688 * The returned object's property (boolean)capable indicates that
2689 * the course format supports Moodle course ajax features.
2690 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2692 * @param string $format
2693 * @return stdClass
2695 function course_format_ajax_support($format) {
2696 $course = new stdClass();
2697 $course->format = $format;
2698 return course_get_format($course)->supports_ajax();
2702 * Can the current user delete this course?
2703 * Course creators have exception,
2704 * 1 day after the creation they can sill delete the course.
2705 * @param int $courseid
2706 * @return boolean
2708 function can_delete_course($courseid) {
2709 global $USER, $DB;
2711 $context = context_course::instance($courseid);
2713 if (has_capability('moodle/course:delete', $context)) {
2714 return true;
2717 // hack: now try to find out if creator created this course recently (1 day)
2718 if (!has_capability('moodle/course:create', $context)) {
2719 return false;
2722 $since = time() - 60*60*24;
2724 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2725 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2727 return $DB->record_exists_select('log', $select, $params);
2731 * Save the Your name for 'Some role' strings.
2733 * @param integer $courseid the id of this course.
2734 * @param array $data the data that came from the course settings form.
2736 function save_local_role_names($courseid, $data) {
2737 global $DB;
2738 $context = context_course::instance($courseid);
2740 foreach ($data as $fieldname => $value) {
2741 if (strpos($fieldname, 'role_') !== 0) {
2742 continue;
2744 list($ignored, $roleid) = explode('_', $fieldname);
2746 // make up our mind whether we want to delete, update or insert
2747 if (!$value) {
2748 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2750 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2751 $rolename->name = $value;
2752 $DB->update_record('role_names', $rolename);
2754 } else {
2755 $rolename = new stdClass;
2756 $rolename->contextid = $context->id;
2757 $rolename->roleid = $roleid;
2758 $rolename->name = $value;
2759 $DB->insert_record('role_names', $rolename);
2765 * Create a course and either return a $course object
2767 * Please note this functions does not verify any access control,
2768 * the calling code is responsible for all validation (usually it is the form definition).
2770 * @param array $editoroptions course description editor options
2771 * @param object $data - all the data needed for an entry in the 'course' table
2772 * @return object new course instance
2774 function create_course($data, $editoroptions = NULL) {
2775 global $CFG, $DB;
2777 //check the categoryid - must be given for all new courses
2778 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2780 //check if the shortname already exist
2781 if (!empty($data->shortname)) {
2782 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2783 throw new moodle_exception('shortnametaken');
2787 //check if the id number already exist
2788 if (!empty($data->idnumber)) {
2789 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2790 throw new moodle_exception('idnumbertaken');
2794 $data->timecreated = time();
2795 $data->timemodified = $data->timecreated;
2797 // place at beginning of any category
2798 $data->sortorder = 0;
2800 if ($editoroptions) {
2801 // summary text is updated later, we need context to store the files first
2802 $data->summary = '';
2803 $data->summary_format = FORMAT_HTML;
2806 if (!isset($data->visible)) {
2807 // data not from form, add missing visibility info
2808 $data->visible = $category->visible;
2810 $data->visibleold = $data->visible;
2812 $newcourseid = $DB->insert_record('course', $data);
2813 $context = context_course::instance($newcourseid, MUST_EXIST);
2815 if ($editoroptions) {
2816 // Save the files used in the summary editor and store
2817 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2818 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2819 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2822 // update course format options
2823 course_get_format($newcourseid)->update_course_format_options($data);
2825 $course = course_get_format($newcourseid)->get_course();
2827 // Setup the blocks
2828 blocks_add_default_course_blocks($course);
2830 // Create a default section.
2831 course_create_sections_if_missing($course, 0);
2833 fix_course_sortorder();
2834 // purge appropriate caches in case fix_course_sortorder() did not change anything
2835 cache_helper::purge_by_event('changesincourse');
2837 // new context created - better mark it as dirty
2838 mark_context_dirty($context->path);
2840 // Save any custom role names.
2841 save_local_role_names($course->id, (array)$data);
2843 // set up enrolments
2844 enrol_course_updated(true, $course, $data);
2846 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2848 // Trigger events
2849 events_trigger('course_created', $course);
2851 return $course;
2855 * Update a course.
2857 * Please note this functions does not verify any access control,
2858 * the calling code is responsible for all validation (usually it is the form definition).
2860 * @param object $data - all the data needed for an entry in the 'course' table
2861 * @param array $editoroptions course description editor options
2862 * @return void
2864 function update_course($data, $editoroptions = NULL) {
2865 global $CFG, $DB;
2867 $data->timemodified = time();
2869 $oldcourse = course_get_format($data->id)->get_course();
2870 $context = context_course::instance($oldcourse->id);
2872 if ($editoroptions) {
2873 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2876 if (!isset($data->category) or empty($data->category)) {
2877 // prevent nulls and 0 in category field
2878 unset($data->category);
2880 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2882 if (!isset($data->visible)) {
2883 // data not from form, add missing visibility info
2884 $data->visible = $oldcourse->visible;
2887 if ($data->visible != $oldcourse->visible) {
2888 // reset the visibleold flag when manually hiding/unhiding course
2889 $data->visibleold = $data->visible;
2890 } else {
2891 if ($movecat) {
2892 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2893 if (empty($newcategory->visible)) {
2894 // make sure when moving into hidden category the course is hidden automatically
2895 $data->visible = 0;
2900 // Update with the new data
2901 $DB->update_record('course', $data);
2902 // make sure the modinfo cache is reset
2903 rebuild_course_cache($data->id);
2905 // update course format options with full course data
2906 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2908 $course = $DB->get_record('course', array('id'=>$data->id));
2910 if ($movecat) {
2911 $newparent = context_coursecat::instance($course->category);
2912 context_moved($context, $newparent);
2915 fix_course_sortorder();
2916 // purge appropriate caches in case fix_course_sortorder() did not change anything
2917 cache_helper::purge_by_event('changesincourse');
2919 // Test for and remove blocks which aren't appropriate anymore
2920 blocks_remove_inappropriate($course);
2922 // Save any custom role names.
2923 save_local_role_names($course->id, $data);
2925 // update enrol settings
2926 enrol_course_updated(false, $course, $data);
2928 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2930 // Trigger events
2931 events_trigger('course_updated', $course);
2933 if ($oldcourse->format !== $course->format) {
2934 // Remove all options stored for the previous format
2935 // We assume that new course format migrated everything it needed watching trigger
2936 // 'course_updated' and in method format_XXX::update_course_format_options()
2937 $DB->delete_records('course_format_options',
2938 array('courseid' => $course->id, 'format' => $oldcourse->format));
2943 * Average number of participants
2944 * @return integer
2946 function average_number_of_participants() {
2947 global $DB, $SITE;
2949 //count total of enrolments for visible course (except front page)
2950 $sql = 'SELECT COUNT(*) FROM (
2951 SELECT DISTINCT ue.userid, e.courseid
2952 FROM {user_enrolments} ue, {enrol} e, {course} c
2953 WHERE ue.enrolid = e.id
2954 AND e.courseid <> :siteid
2955 AND c.id = e.courseid
2956 AND c.visible = 1) total';
2957 $params = array('siteid' => $SITE->id);
2958 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2961 //count total of visible courses (minus front page)
2962 $coursetotal = $DB->count_records('course', array('visible' => 1));
2963 $coursetotal = $coursetotal - 1 ;
2965 //average of enrolment
2966 if (empty($coursetotal)) {
2967 $participantaverage = 0;
2968 } else {
2969 $participantaverage = $enrolmenttotal / $coursetotal;
2972 return $participantaverage;
2976 * Average number of course modules
2977 * @return integer
2979 function average_number_of_courses_modules() {
2980 global $DB, $SITE;
2982 //count total of visible course module (except front page)
2983 $sql = 'SELECT COUNT(*) FROM (
2984 SELECT cm.course, cm.module
2985 FROM {course} c, {course_modules} cm
2986 WHERE c.id = cm.course
2987 AND c.id <> :siteid
2988 AND cm.visible = 1
2989 AND c.visible = 1) total';
2990 $params = array('siteid' => $SITE->id);
2991 $moduletotal = $DB->count_records_sql($sql, $params);
2994 //count total of visible courses (minus front page)
2995 $coursetotal = $DB->count_records('course', array('visible' => 1));
2996 $coursetotal = $coursetotal - 1 ;
2998 //average of course module
2999 if (empty($coursetotal)) {
3000 $coursemoduleaverage = 0;
3001 } else {
3002 $coursemoduleaverage = $moduletotal / $coursetotal;
3005 return $coursemoduleaverage;
3009 * This class pertains to course requests and contains methods associated with
3010 * create, approving, and removing course requests.
3012 * Please note we do not allow embedded images here because there is no context
3013 * to store them with proper access control.
3015 * @copyright 2009 Sam Hemelryk
3016 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3017 * @since Moodle 2.0
3019 * @property-read int $id
3020 * @property-read string $fullname
3021 * @property-read string $shortname
3022 * @property-read string $summary
3023 * @property-read int $summaryformat
3024 * @property-read int $summarytrust
3025 * @property-read string $reason
3026 * @property-read int $requester
3028 class course_request {
3031 * This is the stdClass that stores the properties for the course request
3032 * and is externally accessed through the __get magic method
3033 * @var stdClass
3035 protected $properties;
3038 * An array of options for the summary editor used by course request forms.
3039 * This is initially set by {@link summary_editor_options()}
3040 * @var array
3041 * @static
3043 protected static $summaryeditoroptions;
3046 * Static function to prepare the summary editor for working with a course
3047 * request.
3049 * @static
3050 * @param null|stdClass $data Optional, an object containing the default values
3051 * for the form, these may be modified when preparing the
3052 * editor so this should be called before creating the form
3053 * @return stdClass An object that can be used to set the default values for
3054 * an mforms form
3056 public static function prepare($data=null) {
3057 if ($data === null) {
3058 $data = new stdClass;
3060 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
3061 return $data;
3065 * Static function to create a new course request when passed an array of properties
3066 * for it.
3068 * This function also handles saving any files that may have been used in the editor
3070 * @static
3071 * @param stdClass $data
3072 * @return course_request The newly created course request
3074 public static function create($data) {
3075 global $USER, $DB, $CFG;
3076 $data->requester = $USER->id;
3078 // Setting the default category if none set.
3079 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
3080 $data->category = $CFG->defaultrequestcategory;
3083 // Summary is a required field so copy the text over
3084 $data->summary = $data->summary_editor['text'];
3085 $data->summaryformat = $data->summary_editor['format'];
3087 $data->id = $DB->insert_record('course_request', $data);
3089 // Create a new course_request object and return it
3090 $request = new course_request($data);
3092 // Notify the admin if required.
3093 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
3095 $a = new stdClass;
3096 $a->link = "$CFG->wwwroot/course/pending.php";
3097 $a->user = fullname($USER);
3098 $subject = get_string('courserequest');
3099 $message = get_string('courserequestnotifyemail', 'admin', $a);
3100 foreach ($users as $user) {
3101 $request->notify($user, $USER, 'courserequested', $subject, $message);
3105 return $request;
3109 * Returns an array of options to use with a summary editor
3111 * @uses course_request::$summaryeditoroptions
3112 * @return array An array of options to use with the editor
3114 public static function summary_editor_options() {
3115 global $CFG;
3116 if (self::$summaryeditoroptions === null) {
3117 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
3119 return self::$summaryeditoroptions;
3123 * Loads the properties for this course request object. Id is required and if
3124 * only id is provided then we load the rest of the properties from the database
3126 * @param stdClass|int $properties Either an object containing properties
3127 * or the course_request id to load
3129 public function __construct($properties) {
3130 global $DB;
3131 if (empty($properties->id)) {
3132 if (empty($properties)) {
3133 throw new coding_exception('You must provide a course request id when creating a course_request object');
3135 $id = $properties;
3136 $properties = new stdClass;
3137 $properties->id = (int)$id;
3138 unset($id);
3140 if (empty($properties->requester)) {
3141 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
3142 print_error('unknowncourserequest');
3144 } else {
3145 $this->properties = $properties;
3147 $this->properties->collision = null;
3151 * Returns the requested property
3153 * @param string $key
3154 * @return mixed
3156 public function __get($key) {
3157 return $this->properties->$key;
3161 * Override this to ensure empty($request->blah) calls return a reliable answer...
3163 * This is required because we define the __get method
3165 * @param mixed $key
3166 * @return bool True is it not empty, false otherwise
3168 public function __isset($key) {
3169 return (!empty($this->properties->$key));
3173 * Returns the user who requested this course
3175 * Uses a static var to cache the results and cut down the number of db queries
3177 * @staticvar array $requesters An array of cached users
3178 * @return stdClass The user who requested the course
3180 public function get_requester() {
3181 global $DB;
3182 static $requesters= array();
3183 if (!array_key_exists($this->properties->requester, $requesters)) {
3184 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
3186 return $requesters[$this->properties->requester];
3190 * Checks that the shortname used by the course does not conflict with any other
3191 * courses that exist
3193 * @param string|null $shortnamemark The string to append to the requests shortname
3194 * should a conflict be found
3195 * @return bool true is there is a conflict, false otherwise
3197 public function check_shortname_collision($shortnamemark = '[*]') {
3198 global $DB;
3200 if ($this->properties->collision !== null) {
3201 return $this->properties->collision;
3204 if (empty($this->properties->shortname)) {
3205 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
3206 $this->properties->collision = false;
3207 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
3208 if (!empty($shortnamemark)) {
3209 $this->properties->shortname .= ' '.$shortnamemark;
3211 $this->properties->collision = true;
3212 } else {
3213 $this->properties->collision = false;
3215 return $this->properties->collision;
3219 * Returns the category where this course request should be created
3221 * Note that we don't check here that user has a capability to view
3222 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
3223 * 'moodle/course:changecategory'
3225 * @return coursecat
3227 public function get_category() {
3228 global $CFG;
3229 require_once($CFG->libdir.'/coursecatlib.php');
3230 // If the category is not set, if the current user does not have the rights to change the category, or if the
3231 // category does not exist, we set the default category to the course to be approved.
3232 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
3233 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
3234 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
3235 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
3237 if (!$category) {
3238 $category = coursecat::get_default();
3240 return $category;
3244 * This function approves the request turning it into a course
3246 * This function converts the course request into a course, at the same time
3247 * transferring any files used in the summary to the new course and then removing
3248 * the course request and the files associated with it.
3250 * @return int The id of the course that was created from this request
3252 public function approve() {
3253 global $CFG, $DB, $USER;
3255 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
3257 $courseconfig = get_config('moodlecourse');
3259 // Transfer appropriate settings
3260 $data = clone($this->properties);
3261 unset($data->id);
3262 unset($data->reason);
3263 unset($data->requester);
3265 // Set category
3266 $category = $this->get_category();
3267 $data->category = $category->id;
3268 // Set misc settings
3269 $data->requested = 1;
3271 // Apply course default settings
3272 $data->format = $courseconfig->format;
3273 $data->newsitems = $courseconfig->newsitems;
3274 $data->showgrades = $courseconfig->showgrades;
3275 $data->showreports = $courseconfig->showreports;
3276 $data->maxbytes = $courseconfig->maxbytes;
3277 $data->groupmode = $courseconfig->groupmode;
3278 $data->groupmodeforce = $courseconfig->groupmodeforce;
3279 $data->visible = $courseconfig->visible;
3280 $data->visibleold = $data->visible;
3281 $data->lang = $courseconfig->lang;
3283 $course = create_course($data);
3284 $context = context_course::instance($course->id, MUST_EXIST);
3286 // add enrol instances
3287 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3288 if ($manual = enrol_get_plugin('manual')) {
3289 $manual->add_default_instance($course);
3293 // enrol the requester as teacher if necessary
3294 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3295 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3298 $this->delete();
3300 $a = new stdClass();
3301 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3302 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3303 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3305 return $course->id;
3309 * Reject a course request
3311 * This function rejects a course request, emailing the requesting user the
3312 * provided notice and then removing the request from the database
3314 * @param string $notice The message to display to the user
3316 public function reject($notice) {
3317 global $USER, $DB;
3318 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3319 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3320 $this->delete();
3324 * Deletes the course request and any associated files
3326 public function delete() {
3327 global $DB;
3328 $DB->delete_records('course_request', array('id' => $this->properties->id));
3332 * Send a message from one user to another using events_trigger
3334 * @param object $touser
3335 * @param object $fromuser
3336 * @param string $name
3337 * @param string $subject
3338 * @param string $message
3340 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3341 $eventdata = new stdClass();
3342 $eventdata->component = 'moodle';
3343 $eventdata->name = $name;
3344 $eventdata->userfrom = $fromuser;
3345 $eventdata->userto = $touser;
3346 $eventdata->subject = $subject;
3347 $eventdata->fullmessage = $message;
3348 $eventdata->fullmessageformat = FORMAT_PLAIN;
3349 $eventdata->fullmessagehtml = '';
3350 $eventdata->smallmessage = '';
3351 $eventdata->notification = 1;
3352 message_send($eventdata);
3357 * Return a list of page types
3358 * @param string $pagetype current page type
3359 * @param stdClass $parentcontext Block's parent context
3360 * @param stdClass $currentcontext Current context of block
3362 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3363 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
3364 if (isset($currentcontext)) {
3365 // if above course context ,display all course fomats
3366 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
3367 if ($course->id == SITEID) {
3368 return array('*'=>get_string('page-x', 'pagetype'));
3371 return array('*'=>get_string('page-x', 'pagetype'),
3372 'course-*'=>get_string('page-course-x', 'pagetype'),
3373 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
3378 * Determine whether course ajax should be enabled for the specified course
3380 * @param stdClass $course The course to test against
3381 * @return boolean Whether course ajax is enabled or note
3383 function course_ajax_enabled($course) {
3384 global $CFG, $PAGE, $SITE;
3386 // Ajax must be enabled globally
3387 if (!$CFG->enableajax) {
3388 return false;
3391 // The user must be editing for AJAX to be included
3392 if (!$PAGE->user_is_editing()) {
3393 return false;
3396 // Check that the theme suports
3397 if (!$PAGE->theme->enablecourseajax) {
3398 return false;
3401 // Check that the course format supports ajax functionality
3402 // The site 'format' doesn't have information on course format support
3403 if ($SITE->id !== $course->id) {
3404 $courseformatajaxsupport = course_format_ajax_support($course->format);
3405 if (!$courseformatajaxsupport->capable) {
3406 return false;
3410 // All conditions have been met so course ajax should be enabled
3411 return true;
3415 * Include the relevant javascript and language strings for the resource
3416 * toolbox YUI module
3418 * @param integer $id The ID of the course being applied to
3419 * @param array $usedmodules An array containing the names of the modules in use on the page
3420 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3421 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3422 * * resourceurl The URL to post changes to for resource changes
3423 * * sectionurl The URL to post changes to for section changes
3424 * * pageparams Additional parameters to pass through in the post
3425 * @return bool
3427 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3428 global $PAGE, $SITE;
3430 // Ensure that ajax should be included
3431 if (!course_ajax_enabled($course)) {
3432 return false;
3435 if (!$config) {
3436 $config = new stdClass();
3439 // The URL to use for resource changes
3440 if (!isset($config->resourceurl)) {
3441 $config->resourceurl = '/course/rest.php';
3444 // The URL to use for section changes
3445 if (!isset($config->sectionurl)) {
3446 $config->sectionurl = '/course/rest.php';
3449 // Any additional parameters which need to be included on page submission
3450 if (!isset($config->pageparams)) {
3451 $config->pageparams = array();
3454 // Include toolboxes
3455 $PAGE->requires->yui_module('moodle-course-toolboxes',
3456 'M.course.init_resource_toolbox',
3457 array(array(
3458 'courseid' => $course->id,
3459 'ajaxurl' => $config->resourceurl,
3460 'config' => $config,
3463 $PAGE->requires->yui_module('moodle-course-toolboxes',
3464 'M.course.init_section_toolbox',
3465 array(array(
3466 'courseid' => $course->id,
3467 'format' => $course->format,
3468 'ajaxurl' => $config->sectionurl,
3469 'config' => $config,
3473 // Include course dragdrop
3474 if ($course->id != $SITE->id) {
3475 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3476 array(array(
3477 'courseid' => $course->id,
3478 'ajaxurl' => $config->sectionurl,
3479 'config' => $config,
3480 )), null, true);
3482 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3483 array(array(
3484 'courseid' => $course->id,
3485 'ajaxurl' => $config->resourceurl,
3486 'config' => $config,
3487 )), null, true);
3490 // Require various strings for the command toolbox
3491 $PAGE->requires->strings_for_js(array(
3492 'moveleft',
3493 'deletechecktype',
3494 'deletechecktypename',
3495 'edittitle',
3496 'edittitleinstructions',
3497 'show',
3498 'hide',
3499 'groupsnone',
3500 'groupsvisible',
3501 'groupsseparate',
3502 'clicktochangeinbrackets',
3503 'markthistopic',
3504 'markedthistopic',
3505 'move',
3506 'movesection',
3507 ), 'moodle');
3509 // Include format-specific strings
3510 if ($course->id != $SITE->id) {
3511 $PAGE->requires->strings_for_js(array(
3512 'showfromothers',
3513 'hidefromothers',
3514 ), 'format_' . $course->format);
3517 // For confirming resource deletion we need the name of the module in question
3518 foreach ($usedmodules as $module => $modname) {
3519 $PAGE->requires->string_for_js('pluginname', $module);
3522 // Load drag and drop upload AJAX.
3523 dndupload_add_to_course($course, $enabledmodules);
3525 return true;
3529 * Returns the sorted list of available course formats, filtered by enabled if necessary
3531 * @param bool $enabledonly return only formats that are enabled
3532 * @return array array of sorted format names
3534 function get_sorted_course_formats($enabledonly = false) {
3535 global $CFG;
3536 $formats = get_plugin_list('format');
3538 if (!empty($CFG->format_plugins_sortorder)) {
3539 $order = explode(',', $CFG->format_plugins_sortorder);
3540 $order = array_merge(array_intersect($order, array_keys($formats)),
3541 array_diff(array_keys($formats), $order));
3542 } else {
3543 $order = array_keys($formats);
3545 if (!$enabledonly) {
3546 return $order;
3548 $sortedformats = array();
3549 foreach ($order as $formatname) {
3550 if (!get_config('format_'.$formatname, 'disabled')) {
3551 $sortedformats[] = $formatname;
3554 return $sortedformats;
3558 * The URL to use for the specified course (with section)
3560 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3561 * @param int|stdClass $section Section object from database or just field course_sections.section
3562 * if omitted the course view page is returned
3563 * @param array $options options for view URL. At the moment core uses:
3564 * 'navigation' (bool) if true and section has no separate page, the function returns null
3565 * 'sr' (int) used by multipage formats to specify to which section to return
3566 * @return moodle_url The url of course
3568 function course_get_url($courseorid, $section = null, $options = array()) {
3569 return course_get_format($courseorid)->get_view_url($section, $options);
3573 * Create a module.
3575 * It includes:
3576 * - capability checks and other checks
3577 * - create the module from the module info
3579 * @param object $module
3580 * @return object the created module info
3582 function create_module($moduleinfo) {
3583 global $DB, $CFG;
3585 require_once($CFG->dirroot . '/course/modlib.php');
3587 // Check manadatory attributs.
3588 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3589 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3590 $mandatoryfields[] = 'introeditor';
3592 foreach($mandatoryfields as $mandatoryfield) {
3593 if (!isset($moduleinfo->{$mandatoryfield})) {
3594 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3598 // Some additional checks (capability / existing instances).
3599 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3600 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3602 // Load module library.
3603 include_modulelib($module->name);
3605 // Add the module.
3606 $moduleinfo->module = $module->id;
3607 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3609 return $moduleinfo;
3613 * Update a module.
3615 * It includes:
3616 * - capability and other checks
3617 * - update the module
3619 * @param object $module
3620 * @return object the updated module info
3622 function update_module($moduleinfo) {
3623 global $DB, $CFG;
3625 require_once($CFG->dirroot . '/course/modlib.php');
3627 // Check the course module exists.
3628 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3630 // Check the course exists.
3631 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3633 // Some checks (capaibility / existing instances).
3634 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3636 // Load module library.
3637 include_modulelib($module->name);
3639 // Retrieve few information needed by update_moduleinfo.
3640 $moduleinfo->modulename = $cm->modname;
3641 if (!isset($moduleinfo->scale)) {
3642 $moduleinfo->scale = 0;
3644 $moduleinfo->type = 'mod';
3646 // Update the module.
3647 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3649 return $moduleinfo;
3653 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3654 * Sorts by descending order of time.
3656 * @param stdClass $a First object
3657 * @param stdClass $b Second object
3658 * @return int 0,1,-1 representing the order
3660 function compare_activities_by_time_desc($a, $b) {
3661 // Make sure the activities actually have a timestamp property.
3662 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3663 return 0;
3665 // We treat instances without timestamp as if they have a timestamp of 0.
3666 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3667 return 1;
3669 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3670 return -1;
3672 if ($a->timestamp == $b->timestamp) {
3673 return 0;
3675 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3679 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3680 * Sorts by ascending order of time.
3682 * @param stdClass $a First object
3683 * @param stdClass $b Second object
3684 * @return int 0,1,-1 representing the order
3686 function compare_activities_by_time_asc($a, $b) {
3687 // Make sure the activities actually have a timestamp property.
3688 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3689 return 0;
3691 // We treat instances without timestamp as if they have a timestamp of 0.
3692 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3693 return -1;
3695 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3696 return 1;
3698 if ($a->timestamp == $b->timestamp) {
3699 return 0;
3701 return ($a->timestamp < $b->timestamp) ? -1 : 1;