MDL-35238 Support deployment from yet another plugins check page too
[moodle.git] / course / lib.php
bloba772578334c283535868eaf6174f626885656b73
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 'mnet course':
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
74 } else {
75 $url = "/course/$url";
77 break;
78 case 'user':
79 case 'blog':
80 $url = "/$module/$url";
81 break;
82 case 'upload':
83 $url = $url;
84 break;
85 case 'coursetags':
86 $url = '/'.$url;
87 break;
88 case 'library':
89 case '':
90 $url = '/';
91 break;
92 case 'message':
93 $url = "/message/$url";
94 break;
95 case 'notes':
96 $url = "/notes/$url";
97 break;
98 case 'tag':
99 $url = "/tag/$url";
100 break;
101 case 'role':
102 $url = '/'.$url;
103 break;
104 default:
105 $url = "/mod/$module/$url";
106 break;
109 //now let's sanitise urls - there might be some ugly nasties:-(
110 $parts = explode('?', $url);
111 $script = array_shift($parts);
112 if (strpos($script, 'http') === 0) {
113 $script = clean_param($script, PARAM_URL);
114 } else {
115 $script = clean_param($script, PARAM_PATH);
118 $query = '';
119 if ($parts) {
120 $query = implode('', $parts);
121 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
122 $parts = explode('&', $query);
123 $eq = urlencode('=');
124 foreach ($parts as $key=>$part) {
125 $part = urlencode(urldecode($part));
126 $part = str_replace($eq, '=', $part);
127 $parts[$key] = $part;
129 $query = '?'.implode('&amp;', $parts);
132 return $script.$query;
136 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
137 $modname="", $modid=0, $modaction="", $groupid=0) {
138 global $CFG, $DB;
140 // It is assumed that $date is the GMT time of midnight for that day,
141 // and so the next 86400 seconds worth of logs are printed.
143 /// Setup for group handling.
145 // TODO: I don't understand group/context/etc. enough to be able to do
146 // something interesting with it here
147 // What is the context of a remote course?
149 /// If the group mode is separate, and this user does not have editing privileges,
150 /// then only the user's group can be viewed.
151 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
152 // $groupid = get_current_group($course->id);
154 /// If this course doesn't have groups, no groupid can be specified.
155 //else if (!$course->groupmode) {
156 // $groupid = 0;
159 $groupid = 0;
161 $joins = array();
162 $where = '';
164 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
165 FROM {mnet_log} l
166 LEFT JOIN {user} u ON l.userid = u.id
167 WHERE ";
168 $params = array();
170 $where .= "l.hostid = :hostid";
171 $params['hostid'] = $hostid;
173 // TODO: Is 1 really a magic number referring to the sitename?
174 if ($course != SITEID || $modid != 0) {
175 $where .= " AND l.course=:courseid";
176 $params['courseid'] = $course;
179 if ($modname) {
180 $where .= " AND l.module = :modname";
181 $params['modname'] = $modname;
184 if ('site_errors' === $modid) {
185 $where .= " AND ( l.action='error' OR l.action='infected' )";
186 } else if ($modid) {
187 //TODO: This assumes that modids are the same across sites... probably
188 //not true
189 $where .= " AND l.cmid = :modid";
190 $params['modid'] = $modid;
193 if ($modaction) {
194 $firstletter = substr($modaction, 0, 1);
195 if ($firstletter == '-') {
196 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
197 $params['modaction'] = '%'.substr($modaction, 1).'%';
198 } else {
199 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
200 $params['modaction'] = '%'.$modaction.'%';
204 if ($user) {
205 $where .= " AND l.userid = :user";
206 $params['user'] = $user;
209 if ($date) {
210 $enddate = $date + 86400;
211 $where .= " AND l.time > :date AND l.time < :enddate";
212 $params['date'] = $date;
213 $params['enddate'] = $enddate;
216 $result = array();
217 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
218 if(!empty($result['totalcount'])) {
219 $where .= " ORDER BY $order";
220 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
221 } else {
222 $result['logs'] = array();
224 return $result;
227 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
228 $modname="", $modid=0, $modaction="", $groupid=0) {
229 global $DB, $SESSION, $USER;
230 // It is assumed that $date is the GMT time of midnight for that day,
231 // and so the next 86400 seconds worth of logs are printed.
233 /// Setup for group handling.
235 /// If the group mode is separate, and this user does not have editing privileges,
236 /// then only the user's group can be viewed.
237 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
238 if (isset($SESSION->currentgroup[$course->id])) {
239 $groupid = $SESSION->currentgroup[$course->id];
240 } else {
241 $groupid = groups_get_all_groups($course->id, $USER->id);
242 if (is_array($groupid)) {
243 $groupid = array_shift(array_keys($groupid));
244 $SESSION->currentgroup[$course->id] = $groupid;
245 } else {
246 $groupid = 0;
250 /// If this course doesn't have groups, no groupid can be specified.
251 else if (!$course->groupmode) {
252 $groupid = 0;
255 $joins = array();
256 $params = array();
258 if ($course->id != SITEID || $modid != 0) {
259 $joins[] = "l.course = :courseid";
260 $params['courseid'] = $course->id;
263 if ($modname) {
264 $joins[] = "l.module = :modname";
265 $params['modname'] = $modname;
268 if ('site_errors' === $modid) {
269 $joins[] = "( l.action='error' OR l.action='infected' )";
270 } else if ($modid) {
271 $joins[] = "l.cmid = :modid";
272 $params['modid'] = $modid;
275 if ($modaction) {
276 $firstletter = substr($modaction, 0, 1);
277 if ($firstletter == '-') {
278 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
279 $params['modaction'] = '%'.substr($modaction, 1).'%';
280 } else {
281 $joins[] = $DB->sql_like('l.action', ':modaction', false);
282 $params['modaction'] = '%'.$modaction.'%';
287 /// Getting all members of a group.
288 if ($groupid and !$user) {
289 if ($gusers = groups_get_members($groupid)) {
290 $gusers = array_keys($gusers);
291 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
292 } else {
293 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
296 else if ($user) {
297 $joins[] = "l.userid = :userid";
298 $params['userid'] = $user;
301 if ($date) {
302 $enddate = $date + 86400;
303 $joins[] = "l.time > :date AND l.time < :enddate";
304 $params['date'] = $date;
305 $params['enddate'] = $enddate;
308 $selector = implode(' AND ', $joins);
310 $totalcount = 0; // Initialise
311 $result = array();
312 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
313 $result['totalcount'] = $totalcount;
314 return $result;
318 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
319 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
321 global $CFG, $DB, $OUTPUT;
323 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
324 $modname, $modid, $modaction, $groupid)) {
325 echo $OUTPUT->notification("No logs found!");
326 echo $OUTPUT->footer();
327 exit;
330 $courses = array();
332 if ($course->id == SITEID) {
333 $courses[0] = '';
334 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
335 foreach ($ccc as $cc) {
336 $courses[$cc->id] = $cc->shortname;
339 } else {
340 $courses[$course->id] = $course->shortname;
343 $totalcount = $logs['totalcount'];
344 $count=0;
345 $ldcache = array();
346 $tt = getdate(time());
347 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
349 $strftimedatetime = get_string("strftimedatetime");
351 echo "<div class=\"info\">\n";
352 print_string("displayingrecords", "", $totalcount);
353 echo "</div>\n";
355 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
357 $table = new html_table();
358 $table->classes = array('logtable','generalbox');
359 $table->align = array('right', 'left', 'left');
360 $table->head = array(
361 get_string('time'),
362 get_string('ip_address'),
363 get_string('fullnameuser'),
364 get_string('action'),
365 get_string('info')
367 $table->data = array();
369 if ($course->id == SITEID) {
370 array_unshift($table->align, 'left');
371 array_unshift($table->head, get_string('course'));
374 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
375 if (empty($logs['logs'])) {
376 $logs['logs'] = array();
379 foreach ($logs['logs'] as $log) {
381 if (isset($ldcache[$log->module][$log->action])) {
382 $ld = $ldcache[$log->module][$log->action];
383 } else {
384 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
385 $ldcache[$log->module][$log->action] = $ld;
387 if ($ld && is_numeric($log->info)) {
388 // ugly hack to make sure fullname is shown correctly
389 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
390 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
391 } else {
392 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
396 //Filter log->info
397 $log->info = format_string($log->info);
399 // If $log->url has been trimmed short by the db size restriction
400 // code in add_to_log, keep a note so we don't add a link to a broken url
401 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
403 $row = array();
404 if ($course->id == SITEID) {
405 if (empty($log->course)) {
406 $row[] = get_string('site');
407 } else {
408 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
412 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
414 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
415 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
417 $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))));
419 $displayaction="$log->module $log->action";
420 if ($brokenurl) {
421 $row[] = $displayaction;
422 } else {
423 $link = make_log_url($log->module,$log->url);
424 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
426 $row[] = $log->info;
427 $table->data[] = $row;
430 echo html_writer::table($table);
431 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
435 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
438 global $CFG, $DB, $OUTPUT;
440 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
442 echo $OUTPUT->notification("No logs found!");
443 echo $OUTPUT->footer();
444 exit;
447 if ($course->id == SITEID) {
448 $courses[0] = '';
449 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
450 foreach ($ccc as $cc) {
451 $courses[$cc->id] = $cc->shortname;
456 $totalcount = $logs['totalcount'];
457 $count=0;
458 $ldcache = array();
459 $tt = getdate(time());
460 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
462 $strftimedatetime = get_string("strftimedatetime");
464 echo "<div class=\"info\">\n";
465 print_string("displayingrecords", "", $totalcount);
466 echo "</div>\n";
468 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
470 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
471 echo "<tr>";
472 if ($course->id == SITEID) {
473 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
475 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
476 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
477 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
478 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
479 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
480 echo "</tr>\n";
482 if (empty($logs['logs'])) {
483 echo "</table>\n";
484 return;
487 $row = 1;
488 foreach ($logs['logs'] as $log) {
490 $log->info = $log->coursename;
491 $row = ($row + 1) % 2;
493 if (isset($ldcache[$log->module][$log->action])) {
494 $ld = $ldcache[$log->module][$log->action];
495 } else {
496 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
497 $ldcache[$log->module][$log->action] = $ld;
499 if (0 && $ld && !empty($log->info)) {
500 // ugly hack to make sure fullname is shown correctly
501 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
502 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
503 } else {
504 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
508 //Filter log->info
509 $log->info = format_string($log->info);
511 echo '<tr class="r'.$row.'">';
512 if ($course->id == SITEID) {
513 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
514 echo "<td class=\"r$row c0\" >\n";
515 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
516 echo "</td>\n";
518 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
519 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
520 echo "<td class=\"r$row c2\" >\n";
521 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
522 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
523 echo "</td>\n";
524 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
525 echo "<td class=\"r$row c3\" >\n";
526 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
527 echo "</td>\n";
528 echo "<td class=\"r$row c4\">\n";
529 echo $log->action .': '.$log->module;
530 echo "</td>\n";;
531 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
532 echo "</tr>\n";
534 echo "</table>\n";
536 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
540 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
541 $modid, $modaction, $groupid) {
542 global $DB, $CFG;
544 require_once($CFG->libdir . '/csvlib.class.php');
546 $csvexporter = new csv_export_writer('tab');
548 $header = array();
549 $header[] = get_string('course');
550 $header[] = get_string('time');
551 $header[] = get_string('ip_address');
552 $header[] = get_string('fullnameuser');
553 $header[] = get_string('action');
554 $header[] = get_string('info');
556 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
557 $modname, $modid, $modaction, $groupid)) {
558 return false;
561 $courses = array();
563 if ($course->id == SITEID) {
564 $courses[0] = '';
565 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
566 foreach ($ccc as $cc) {
567 $courses[$cc->id] = $cc->shortname;
570 } else {
571 $courses[$course->id] = $course->shortname;
574 $count=0;
575 $ldcache = array();
576 $tt = getdate(time());
577 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
579 $strftimedatetime = get_string("strftimedatetime");
581 $csvexporter->set_filename('logs', '.txt');
582 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
583 $csvexporter->add_data($title);
584 $csvexporter->add_data($header);
586 if (empty($logs['logs'])) {
587 return true;
590 foreach ($logs['logs'] as $log) {
591 if (isset($ldcache[$log->module][$log->action])) {
592 $ld = $ldcache[$log->module][$log->action];
593 } else {
594 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
595 $ldcache[$log->module][$log->action] = $ld;
597 if ($ld && !empty($log->info)) {
598 // ugly hack to make sure fullname is shown correctly
599 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
600 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
601 } else {
602 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
606 //Filter log->info
607 $log->info = format_string($log->info);
608 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
610 $coursecontext = context_course::instance($course->id);
611 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
612 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
613 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
614 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
615 $csvexporter->add_data($row);
617 $csvexporter->download_file();
618 return true;
622 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
623 $modid, $modaction, $groupid) {
625 global $CFG, $DB;
627 require_once("$CFG->libdir/excellib.class.php");
629 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
630 $modname, $modid, $modaction, $groupid)) {
631 return false;
634 $courses = array();
636 if ($course->id == SITEID) {
637 $courses[0] = '';
638 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
639 foreach ($ccc as $cc) {
640 $courses[$cc->id] = $cc->shortname;
643 } else {
644 $courses[$course->id] = $course->shortname;
647 $count=0;
648 $ldcache = array();
649 $tt = getdate(time());
650 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
652 $strftimedatetime = get_string("strftimedatetime");
654 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
655 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
656 $filename .= '.xls';
658 $workbook = new MoodleExcelWorkbook('-');
659 $workbook->send($filename);
661 $worksheet = array();
662 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
663 get_string('fullnameuser'), get_string('action'), get_string('info'));
665 // Creating worksheets
666 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
667 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
668 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
669 $worksheet[$wsnumber]->set_column(1, 1, 30);
670 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
671 userdate(time(), $strftimedatetime));
672 $col = 0;
673 foreach ($headers as $item) {
674 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
675 $col++;
679 if (empty($logs['logs'])) {
680 $workbook->close();
681 return true;
684 $formatDate =& $workbook->add_format();
685 $formatDate->set_num_format(get_string('log_excel_date_format'));
687 $row = FIRSTUSEDEXCELROW;
688 $wsnumber = 1;
689 $myxls =& $worksheet[$wsnumber];
690 foreach ($logs['logs'] as $log) {
691 if (isset($ldcache[$log->module][$log->action])) {
692 $ld = $ldcache[$log->module][$log->action];
693 } else {
694 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
695 $ldcache[$log->module][$log->action] = $ld;
697 if ($ld && !empty($log->info)) {
698 // ugly hack to make sure fullname is shown correctly
699 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
700 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
701 } else {
702 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
706 // Filter log->info
707 $log->info = format_string($log->info);
708 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
710 if ($nroPages>1) {
711 if ($row > EXCELROWS) {
712 $wsnumber++;
713 $myxls =& $worksheet[$wsnumber];
714 $row = FIRSTUSEDEXCELROW;
718 $coursecontext = context_course::instance($course->id);
720 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
721 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
722 $myxls->write($row, 2, $log->ip, '');
723 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
724 $myxls->write($row, 3, $fullname, '');
725 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
726 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
727 $myxls->write($row, 5, $log->info, '');
729 $row++;
732 $workbook->close();
733 return true;
736 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
739 global $CFG, $DB;
741 require_once("$CFG->libdir/odslib.class.php");
743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
744 $modname, $modid, $modaction, $groupid)) {
745 return false;
748 $courses = array();
750 if ($course->id == SITEID) {
751 $courses[0] = '';
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id] = $cc->shortname;
757 } else {
758 $courses[$course->id] = $course->shortname;
761 $count=0;
762 $ldcache = array();
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
766 $strftimedatetime = get_string("strftimedatetime");
768 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
770 $filename .= '.ods';
772 $workbook = new MoodleODSWorkbook('-');
773 $workbook->send($filename);
775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullnameuser'), get_string('action'), get_string('info'));
779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
781 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
782 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
786 $col = 0;
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
789 $col++;
793 if (empty($logs['logs'])) {
794 $workbook->close();
795 return true;
798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
801 $row = FIRSTUSEDEXCELROW;
802 $wsnumber = 1;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module][$log->action])) {
806 $ld = $ldcache[$log->module][$log->action];
807 } else {
808 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
809 $ldcache[$log->module][$log->action] = $ld;
811 if ($ld && !empty($log->info)) {
812 // ugly hack to make sure fullname is shown correctly
813 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
814 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
815 } else {
816 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
820 // Filter log->info
821 $log->info = format_string($log->info);
822 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
824 if ($nroPages>1) {
825 if ($row > EXCELROWS) {
826 $wsnumber++;
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW;
832 $coursecontext = context_course::instance($course->id);
834 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
835 $myxls->write_date($row, 1, $log->time);
836 $myxls->write_string($row, 2, $log->ip);
837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
838 $myxls->write_string($row, 3, $fullname);
839 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
840 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
841 $myxls->write_string($row, 5, $log->info);
843 $row++;
846 $workbook->close();
847 return true;
851 function print_overview($courses, array $remote_courses=array()) {
852 global $CFG, $USER, $DB, $OUTPUT;
854 $htmlarray = array();
855 if ($modules = $DB->get_records('modules')) {
856 foreach ($modules as $mod) {
857 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
858 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
859 $fname = $mod->name.'_print_overview';
860 if (function_exists($fname)) {
861 $fname($courses,$htmlarray);
866 foreach ($courses as $course) {
867 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
868 echo $OUTPUT->box_start('coursebox');
869 $attributes = array('title' => s($fullname));
870 if (empty($course->visible)) {
871 $attributes['class'] = 'dimmed';
873 echo $OUTPUT->heading(html_writer::link(
874 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
875 if (array_key_exists($course->id,$htmlarray)) {
876 foreach ($htmlarray[$course->id] as $modname => $html) {
877 echo $html;
880 echo $OUTPUT->box_end();
883 if (!empty($remote_courses)) {
884 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
886 foreach ($remote_courses as $course) {
887 echo $OUTPUT->box_start('coursebox');
888 $attributes = array('title' => s($course->fullname));
889 echo $OUTPUT->heading(html_writer::link(
890 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
891 format_string($course->shortname),
892 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
893 echo $OUTPUT->box_end();
899 * This function trawls through the logs looking for
900 * anything new since the user's last login
902 function print_recent_activity($course) {
903 // $course is an object
904 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
906 $context = context_course::instance($course->id);
908 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
910 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
912 if (!isguestuser()) {
913 if (!empty($USER->lastcourseaccess[$course->id])) {
914 if ($USER->lastcourseaccess[$course->id] > $timestart) {
915 $timestart = $USER->lastcourseaccess[$course->id];
920 echo '<div class="activitydate">';
921 echo get_string('activitysince', '', userdate($timestart));
922 echo '</div>';
923 echo '<div class="activityhead">';
925 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
927 echo "</div>\n";
929 $content = false;
931 /// Firstly, have there been any new enrolments?
933 $users = get_recent_enrolments($course->id, $timestart);
935 //Accessibility: new users now appear in an <OL> list.
936 if ($users) {
937 echo '<div class="newusers">';
938 echo $OUTPUT->heading(get_string("newusers").':', 3);
939 $content = true;
940 echo "<ol class=\"list\">\n";
941 foreach ($users as $user) {
942 $fullname = fullname($user, $viewfullnames);
943 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
945 echo "</ol>\n</div>\n";
948 /// Next, have there been any modifications to the course structure?
950 $modinfo = get_fast_modinfo($course);
952 $changelist = array();
954 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
955 module = 'course' AND
956 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
957 array($timestart, $course->id), "id ASC");
959 if ($logs) {
960 $actions = array('add mod', 'update mod', 'delete mod');
961 $newgones = array(); // added and later deleted items
962 foreach ($logs as $key => $log) {
963 if (!in_array($log->action, $actions)) {
964 continue;
966 $info = explode(' ', $log->info);
968 // note: in most cases I replaced hardcoding of label with use of
969 // $cm->has_view() but it was not possible to do this here because
970 // we don't necessarily have the $cm for it
971 if ($info[0] == 'label') { // Labels are ignored in recent activity
972 continue;
975 if (count($info) != 2) {
976 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
977 continue;
980 $modname = $info[0];
981 $instanceid = $info[1];
983 if ($log->action == 'delete mod') {
984 // unfortunately we do not know if the mod was visible
985 if (!array_key_exists($log->info, $newgones)) {
986 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
987 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
989 } else {
990 if (!isset($modinfo->instances[$modname][$instanceid])) {
991 if ($log->action == 'add mod') {
992 // do not display added and later deleted activities
993 $newgones[$log->info] = true;
995 continue;
997 $cm = $modinfo->instances[$modname][$instanceid];
998 if (!$cm->uservisible) {
999 continue;
1002 if ($log->action == 'add mod') {
1003 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1004 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1006 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1007 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1008 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1014 if (!empty($changelist)) {
1015 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1016 $content = true;
1017 foreach ($changelist as $changeinfo => $change) {
1018 echo '<p class="activity">'.$change['text'].'</p>';
1022 /// Now display new things from each module
1024 $usedmodules = array();
1025 foreach($modinfo->cms as $cm) {
1026 if (isset($usedmodules[$cm->modname])) {
1027 continue;
1029 if (!$cm->uservisible) {
1030 continue;
1032 $usedmodules[$cm->modname] = $cm->modname;
1035 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1036 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1037 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1038 $print_recent_activity = $modname.'_print_recent_activity';
1039 if (function_exists($print_recent_activity)) {
1040 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1041 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1043 } else {
1044 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1048 if (! $content) {
1049 echo '<p class="message">'.get_string('nothingnew').'</p>';
1054 * For a given course, returns an array of course activity objects
1055 * Each item in the array contains he following properties:
1057 function get_array_of_activities($courseid) {
1058 // cm - course module id
1059 // mod - name of the module (eg forum)
1060 // section - the number of the section (eg week or topic)
1061 // name - the name of the instance
1062 // visible - is the instance visible or not
1063 // groupingid - grouping id
1064 // groupmembersonly - is this instance visible to group members only
1065 // extra - contains extra string to include in any link
1066 global $CFG, $DB;
1067 if(!empty($CFG->enableavailability)) {
1068 require_once($CFG->libdir.'/conditionlib.php');
1071 $course = $DB->get_record('course', array('id'=>$courseid));
1073 if (empty($course)) {
1074 throw new moodle_exception('courseidnotfound');
1077 $mod = array();
1079 $rawmods = get_course_mods($courseid);
1080 if (empty($rawmods)) {
1081 return $mod; // always return array
1084 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1085 foreach ($sections as $section) {
1086 if (!empty($section->sequence)) {
1087 $sequence = explode(",", $section->sequence);
1088 foreach ($sequence as $seq) {
1089 if (empty($rawmods[$seq])) {
1090 continue;
1092 $mod[$seq] = new stdClass();
1093 $mod[$seq]->id = $rawmods[$seq]->instance;
1094 $mod[$seq]->cm = $rawmods[$seq]->id;
1095 $mod[$seq]->mod = $rawmods[$seq]->modname;
1097 // Oh dear. Inconsistent names left here for backward compatibility.
1098 $mod[$seq]->section = $section->section;
1099 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1101 $mod[$seq]->module = $rawmods[$seq]->module;
1102 $mod[$seq]->added = $rawmods[$seq]->added;
1103 $mod[$seq]->score = $rawmods[$seq]->score;
1104 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1105 $mod[$seq]->visible = $rawmods[$seq]->visible;
1106 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1107 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1108 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1109 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1110 $mod[$seq]->indent = $rawmods[$seq]->indent;
1111 $mod[$seq]->completion = $rawmods[$seq]->completion;
1112 $mod[$seq]->extra = "";
1113 $mod[$seq]->completiongradeitemnumber =
1114 $rawmods[$seq]->completiongradeitemnumber;
1115 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1116 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1117 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1118 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1119 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1120 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1121 if (!empty($CFG->enableavailability)) {
1122 condition_info::fill_availability_conditions($rawmods[$seq]);
1123 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1124 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1125 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1128 $modname = $mod[$seq]->mod;
1129 $functionname = $modname."_get_coursemodule_info";
1131 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1132 continue;
1135 include_once("$CFG->dirroot/mod/$modname/lib.php");
1137 if ($hasfunction = function_exists($functionname)) {
1138 if ($info = $functionname($rawmods[$seq])) {
1139 if (!empty($info->icon)) {
1140 $mod[$seq]->icon = $info->icon;
1142 if (!empty($info->iconcomponent)) {
1143 $mod[$seq]->iconcomponent = $info->iconcomponent;
1145 if (!empty($info->name)) {
1146 $mod[$seq]->name = $info->name;
1148 if ($info instanceof cached_cm_info) {
1149 // When using cached_cm_info you can include three new fields
1150 // that aren't available for legacy code
1151 if (!empty($info->content)) {
1152 $mod[$seq]->content = $info->content;
1154 if (!empty($info->extraclasses)) {
1155 $mod[$seq]->extraclasses = $info->extraclasses;
1157 if (!empty($info->iconurl)) {
1158 $mod[$seq]->iconurl = $info->iconurl;
1160 if (!empty($info->onclick)) {
1161 $mod[$seq]->onclick = $info->onclick;
1163 if (!empty($info->customdata)) {
1164 $mod[$seq]->customdata = $info->customdata;
1166 } else {
1167 // When using a stdclass, the (horrible) deprecated ->extra field
1168 // is available for BC
1169 if (!empty($info->extra)) {
1170 $mod[$seq]->extra = $info->extra;
1175 // When there is no modname_get_coursemodule_info function,
1176 // but showdescriptions is enabled, then we use the 'intro'
1177 // and 'introformat' fields in the module table
1178 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1179 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1180 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1181 // Set content from intro and introformat. Filters are disabled
1182 // because we filter it with format_text at display time
1183 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1184 $modvalues, $rawmods[$seq]->id, false);
1186 // To save making another query just below, put name in here
1187 $mod[$seq]->name = $modvalues->name;
1190 if (!isset($mod[$seq]->name)) {
1191 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1194 // Minimise the database size by unsetting default options when they are
1195 // 'empty'. This list corresponds to code in the cm_info constructor.
1196 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1197 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1198 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1199 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1200 'completionview', 'completionexpected', 'score', 'showdescription')
1201 as $property) {
1202 if (property_exists($mod[$seq], $property) &&
1203 empty($mod[$seq]->{$property})) {
1204 unset($mod[$seq]->{$property});
1207 // Special case: this value is usually set to null, but may be 0
1208 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1209 is_null($mod[$seq]->completiongradeitemnumber)) {
1210 unset($mod[$seq]->completiongradeitemnumber);
1216 return $mod;
1220 * Returns the localised human-readable names of all used modules
1222 * @param bool $plural if true returns the plural forms of the names
1223 * @return array where key is the module name (component name without 'mod_') and
1224 * the value is the human-readable string. Array sorted alphabetically by value
1226 function get_module_types_names($plural = false) {
1227 static $modnames = null;
1228 global $DB, $CFG;
1229 if ($modnames === null) {
1230 $modnames = array(0 => array(), 1 => array());
1231 if ($allmods = $DB->get_records("modules")) {
1232 foreach ($allmods as $mod) {
1233 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1234 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1235 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1238 collatorlib::asort($modnames[0]);
1239 collatorlib::asort($modnames[1]);
1242 return $modnames[(int)$plural];
1246 * Set highlighted section. Only one section can be highlighted at the time.
1248 * @param int $courseid course id
1249 * @param int $marker highlight section with this number, 0 means remove higlightin
1250 * @return void
1252 function course_set_marker($courseid, $marker) {
1253 global $DB;
1254 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1258 * For a given course section, marks it visible or hidden,
1259 * and does the same for every activity in that section
1261 * @param int $courseid course id
1262 * @param int $sectionnumber The section number to adjust
1263 * @param int $visibility The new visibility
1264 * @return array A list of resources which were hidden in the section
1266 function set_section_visible($courseid, $sectionnumber, $visibility) {
1267 global $DB;
1269 $resourcestotoggle = array();
1270 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1271 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1272 if (!empty($section->sequence)) {
1273 $modules = explode(",", $section->sequence);
1274 foreach ($modules as $moduleid) {
1275 set_coursemodule_visible($moduleid, $visibility, true);
1278 rebuild_course_cache($courseid, true);
1280 // Determine which modules are visible for AJAX update
1281 if (!empty($modules)) {
1282 list($insql, $params) = $DB->get_in_or_equal($modules);
1283 $select = 'id ' . $insql . ' AND visible = ?';
1284 array_push($params, $visibility);
1285 if (!$visibility) {
1286 $select .= ' AND visibleold = 1';
1288 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1291 return $resourcestotoggle;
1295 * Obtains shared data that is used in print_section when displaying a
1296 * course-module entry.
1298 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1300 * This data is also used in other areas of the code.
1301 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1302 * @param object $course Moodle course object
1303 * @return array An array with the following values in this order:
1304 * $content (optional extra content for after link),
1305 * $instancename (text of link)
1307 function get_print_section_cm_text(cm_info $cm, $course) {
1308 global $OUTPUT;
1310 // Get content from modinfo if specified. Content displays either
1311 // in addition to the standard link (below), or replaces it if
1312 // the link is turned off by setting ->url to null.
1313 if (($content = $cm->get_content()) !== '') {
1314 // Improve filter performance by preloading filter setttings for all
1315 // activities on the course (this does nothing if called multiple
1316 // times)
1317 filter_preload_activities($cm->get_modinfo());
1319 // Get module context
1320 $modulecontext = context_module::instance($cm->id);
1321 $labelformatoptions = new stdClass();
1322 $labelformatoptions->noclean = true;
1323 $labelformatoptions->overflowdiv = true;
1324 $labelformatoptions->context = $modulecontext;
1325 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1326 } else {
1327 $content = '';
1330 // Get course context
1331 $coursecontext = context_course::instance($course->id);
1332 $stringoptions = new stdClass;
1333 $stringoptions->context = $coursecontext;
1334 $instancename = format_string($cm->name, true, $stringoptions);
1335 return array($content, $instancename);
1339 * Prints a section full of activity modules
1341 * @param stdClass $course The course
1342 * @param stdClass|section_info $section The section object containing properties id and section
1343 * @param array $mods (argument not used)
1344 * @param array $modnamesused (argument not used)
1345 * @param bool $absolute All links are absolute
1346 * @param string $width Width of the container
1347 * @param bool $hidecompletion Hide completion status
1348 * @param int $sectionreturn The section to return to
1349 * @return void
1351 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1352 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1354 static $initialised;
1356 static $groupbuttons;
1357 static $groupbuttonslink;
1358 static $isediting;
1359 static $ismoving;
1360 static $strmovehere;
1361 static $strmovefull;
1362 static $strunreadpostsone;
1364 if (!isset($initialised)) {
1365 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1366 $groupbuttonslink = (!$course->groupmodeforce);
1367 $isediting = $PAGE->user_is_editing();
1368 $ismoving = $isediting && ismoving($course->id);
1369 if ($ismoving) {
1370 $strmovehere = get_string("movehere");
1371 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1373 $initialised = true;
1376 $modinfo = get_fast_modinfo($course);
1377 $completioninfo = new completion_info($course);
1379 //Accessibility: replace table with list <ul>, but don't output empty list.
1380 if (!empty($modinfo->sections[$section->section])) {
1382 // Fix bug #5027, don't want style=\"width:$width\".
1383 echo "<ul class=\"section img-text\">\n";
1385 foreach ($modinfo->sections[$section->section] as $modnumber) {
1386 $mod = $modinfo->cms[$modnumber];
1388 if ($ismoving and $mod->id == $USER->activitycopy) {
1389 // do not display moving mod
1390 continue;
1393 // We can continue (because it will not be displayed at all)
1394 // if:
1395 // 1) The activity is not visible to users
1396 // and
1397 // 2a) The 'showavailability' option is not set (if that is set,
1398 // we need to display the activity so we can show
1399 // availability info)
1400 // or
1401 // 2b) The 'availableinfo' is empty, i.e. the activity was
1402 // hidden in a way that leaves no info, such as using the
1403 // eye icon.
1404 if (!$mod->uservisible &&
1405 (empty($mod->showavailability) ||
1406 empty($mod->availableinfo))) {
1407 // visibility shortcut
1408 continue;
1411 // In some cases the activity is visible to user, but it is
1412 // dimmed. This is done if viewhiddenactivities is true and if:
1413 // 1. the activity is not visible, or
1414 // 2. the activity has dates set which do not include current, or
1415 // 3. the activity has any other conditions set (regardless of whether
1416 // current user meets them)
1417 $modcontext = context_module::instance($mod->id);
1418 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1419 $accessiblebutdim = false;
1420 if ($canviewhidden) {
1421 $accessiblebutdim = !$mod->visible;
1422 if (!empty($CFG->enableavailability)) {
1423 $accessiblebutdim = $accessiblebutdim ||
1424 $mod->availablefrom > time() ||
1425 ($mod->availableuntil && $mod->availableuntil < time()) ||
1426 count($mod->conditionsgrade) > 0 ||
1427 count($mod->conditionscompletion) > 0;
1431 $liclasses = array();
1432 $liclasses[] = 'activity';
1433 $liclasses[] = $mod->modname;
1434 $liclasses[] = 'modtype_'.$mod->modname;
1435 $extraclasses = $mod->get_extra_classes();
1436 if ($extraclasses) {
1437 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1439 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1440 if ($ismoving) {
1441 echo '<a title="'.$strmovefull.'"'.
1442 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1443 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1444 ' alt="'.$strmovehere.'" /></a><br />
1448 $classes = array('mod-indent');
1449 if (!empty($mod->indent)) {
1450 $classes[] = 'mod-indent-'.$mod->indent;
1451 if ($mod->indent > 15) {
1452 $classes[] = 'mod-indent-huge';
1455 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1457 // Get data about this course-module
1458 list($content, $instancename) =
1459 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1461 //Accessibility: for files get description via icon, this is very ugly hack!
1462 $altname = '';
1463 $altname = $mod->modfullname;
1464 // Avoid unnecessary duplication: if e.g. a forum name already
1465 // includes the word forum (or Forum, etc) then it is unhelpful
1466 // to include that in the accessible description that is added.
1467 if (false !== strpos(textlib::strtolower($instancename),
1468 textlib::strtolower($altname))) {
1469 $altname = '';
1471 // File type after name, for alphabetic lists (screen reader).
1472 if ($altname) {
1473 $altname = get_accesshide(' '.$altname);
1476 // We may be displaying this just in order to show information
1477 // about visibility, without the actual link
1478 $contentpart = '';
1479 if ($mod->uservisible) {
1480 // Nope - in this case the link is fully working for user
1481 $linkclasses = '';
1482 $textclasses = '';
1483 if ($accessiblebutdim) {
1484 $linkclasses .= ' dimmed conditionalhidden';
1485 $textclasses .= ' dimmed_text conditionalhidden';
1486 $accesstext = '<span class="accesshide">'.
1487 get_string('hiddenfromstudents').': </span>';
1488 } else {
1489 $accesstext = '';
1491 if ($linkclasses) {
1492 $linkcss = 'class="' . trim($linkclasses) . '" ';
1493 } else {
1494 $linkcss = '';
1496 if ($textclasses) {
1497 $textcss = 'class="' . trim($textclasses) . '" ';
1498 } else {
1499 $textcss = '';
1502 // Get on-click attribute value if specified
1503 $onclick = $mod->get_on_click();
1504 if ($onclick) {
1505 $onclick = ' onclick="' . $onclick . '"';
1508 if ($url = $mod->get_url()) {
1509 // Display link itself
1510 echo '<a ' . $linkcss . $mod->extra . $onclick .
1511 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1512 '" class="activityicon" alt="' . $mod->modfullname . '" /> ' .
1513 $accesstext . '<span class="instancename">' .
1514 $instancename . $altname . '</span></a>';
1516 // If specified, display extra content after link
1517 if ($content) {
1518 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1519 '">' . $content . '</div>';
1521 } else {
1522 // No link, so display only content
1523 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1524 $accesstext . $content . '</div>';
1527 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1528 $groupings = groups_get_all_groupings($course->id);
1529 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1531 } else {
1532 $textclasses = $extraclasses;
1533 $textclasses .= ' dimmed_text';
1534 if ($textclasses) {
1535 $textcss = 'class="' . trim($textclasses) . '" ';
1536 } else {
1537 $textcss = '';
1539 $accesstext = '<span class="accesshide">' .
1540 get_string('notavailableyet', 'condition') .
1541 ': </span>';
1543 if ($url = $mod->get_url()) {
1544 // Display greyed-out text of link
1545 echo '<div ' . $textcss . $mod->extra .
1546 ' >' . '<img src="' . $mod->get_icon_url() .
1547 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1548 '</span></div>';
1550 // Do not display content after link when it is greyed out like this.
1551 } else {
1552 // No link, so display only content (also greyed)
1553 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1554 $accesstext . $content . '</div>';
1558 // Module can put text after the link (e.g. forum unread)
1559 echo $mod->get_after_link();
1561 // If there is content but NO link (eg label), then display the
1562 // content here (BEFORE any icons). In this case cons must be
1563 // displayed after the content so that it makes more sense visually
1564 // and for accessibility reasons, e.g. if you have a one-line label
1565 // it should work similarly (at least in terms of ordering) to an
1566 // activity.
1567 if (empty($url)) {
1568 echo $contentpart;
1571 if ($isediting) {
1572 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1573 if (! $mod->groupmodelink = $groupbuttonslink) {
1574 $mod->groupmode = $course->groupmode;
1577 } else {
1578 $mod->groupmode = false;
1580 echo '&nbsp;&nbsp;';
1581 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1582 echo $mod->get_after_edit_icons();
1585 // Completion
1586 $completion = $hidecompletion
1587 ? COMPLETION_TRACKING_NONE
1588 : $completioninfo->is_enabled($mod);
1589 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1590 !isguestuser() && $mod->uservisible) {
1591 $completiondata = $completioninfo->get_data($mod,true);
1592 $completionicon = '';
1593 if ($isediting) {
1594 switch ($completion) {
1595 case COMPLETION_TRACKING_MANUAL :
1596 $completionicon = 'manual-enabled'; break;
1597 case COMPLETION_TRACKING_AUTOMATIC :
1598 $completionicon = 'auto-enabled'; break;
1599 default: // wtf
1601 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1602 switch($completiondata->completionstate) {
1603 case COMPLETION_INCOMPLETE:
1604 $completionicon = 'manual-n'; break;
1605 case COMPLETION_COMPLETE:
1606 $completionicon = 'manual-y'; break;
1608 } else { // Automatic
1609 switch($completiondata->completionstate) {
1610 case COMPLETION_INCOMPLETE:
1611 $completionicon = 'auto-n'; break;
1612 case COMPLETION_COMPLETE:
1613 $completionicon = 'auto-y'; break;
1614 case COMPLETION_COMPLETE_PASS:
1615 $completionicon = 'auto-pass'; break;
1616 case COMPLETION_COMPLETE_FAIL:
1617 $completionicon = 'auto-fail'; break;
1620 if ($completionicon) {
1621 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1622 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1623 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1624 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1625 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1626 $newstate =
1627 $completiondata->completionstate==COMPLETION_COMPLETE
1628 ? COMPLETION_INCOMPLETE
1629 : COMPLETION_COMPLETE;
1630 // In manual mode the icon is a toggle form...
1632 // If this completion state is used by the
1633 // conditional activities system, we need to turn
1634 // off the JS.
1635 if (!empty($CFG->enableavailability) &&
1636 condition_info::completion_value_used_as_condition($course, $mod)) {
1637 $extraclass = ' preventjs';
1638 } else {
1639 $extraclass = '';
1641 echo "
1642 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1643 <input type='hidden' name='id' value='{$mod->id}' />
1644 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1645 <input type='hidden' name='sesskey' value='".sesskey()."' />
1646 <input type='hidden' name='completionstate' value='$newstate' />
1647 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1648 </div></form>";
1649 } else {
1650 // In auto mode, or when editing, the icon is just an image
1651 echo "<span class='autocompletion'>";
1652 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1657 // If there is content AND a link, then display the content here
1658 // (AFTER any icons). Otherwise it was displayed before
1659 if (!empty($url)) {
1660 echo $contentpart;
1663 // Show availability information (for someone who isn't allowed to
1664 // see the activity itself, or for staff)
1665 if (!$mod->uservisible) {
1666 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1667 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1668 $visibilityclass = '';
1669 if (!$mod->visible) {
1670 $visibilityclass = 'accesshide';
1672 $ci = new condition_info($mod);
1673 $fullinfo = $ci->get_full_information();
1674 if($fullinfo) {
1675 echo '<div class="availabilityinfo '.$visibilityclass.'">'.get_string($mod->showavailability
1676 ? 'userrestriction_visible'
1677 : 'userrestriction_hidden','condition',
1678 $fullinfo).'</div>';
1682 echo html_writer::end_tag('div');
1683 echo html_writer::end_tag('li')."\n";
1686 } elseif ($ismoving) {
1687 echo "<ul class=\"section\">\n";
1690 if ($ismoving) {
1691 echo '<li><a title="'.$strmovefull.'"'.
1692 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1693 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1694 ' alt="'.$strmovehere.'" /></a></li>
1697 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1698 echo "</ul><!--class='section'-->\n\n";
1703 * Prints the menus to add activities and resources.
1705 * @param stdClass $course The course
1706 * @param int $section relative section number (field course_sections.section)
1707 * @param null|array $modnames An array containing the list of modules and their names
1708 * if omitted will be taken from get_module_types_names()
1709 * @param bool $vertical Vertical orientation
1710 * @param bool $return Return the menus or send them to output
1711 * @param int $sectionreturn The section to link back to
1712 * @return void|string depending on $return
1714 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1715 global $CFG, $OUTPUT;
1717 if ($modnames === null) {
1718 $modnames = get_module_types_names();
1721 // check to see if user can add menus and there are modules to add
1722 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1723 || empty($modnames)) {
1724 if ($return) {
1725 return '';
1726 } else {
1727 return false;
1731 // Retrieve all modules with associated metadata
1732 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1734 // We'll sort resources and activities into two lists
1735 $resources = array();
1736 $activities = array();
1738 // We need to add the section section to the link for each module
1739 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1741 foreach ($modules as $module) {
1742 if (isset($module->types)) {
1743 // This module has a subtype
1744 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1745 $subtypes = array();
1746 foreach ($module->types as $subtype) {
1747 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1750 // Sort module subtypes into the list
1751 if (!empty($module->title)) {
1752 // This grouping has a name
1753 if ($module->archetype == MOD_CLASS_RESOURCE) {
1754 $resources[] = array($module->title=>$subtypes);
1755 } else {
1756 $activities[] = array($module->title=>$subtypes);
1758 } else {
1759 // This grouping does not have a name
1760 if ($module->archetype == MOD_CLASS_RESOURCE) {
1761 $resources = array_merge($resources, $subtypes);
1762 } else {
1763 $activities = array_merge($activities, $subtypes);
1766 } else {
1767 // This module has no subtypes
1768 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1769 $resources[$module->link . $sectionlink] = $module->title;
1770 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1771 // System modules cannot be added by user, do not add to dropdown
1772 } else {
1773 $activities[$module->link . $sectionlink] = $module->title;
1778 $straddactivity = get_string('addactivity');
1779 $straddresource = get_string('addresource');
1780 $sectionname = get_section_name($course, $section);
1781 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1782 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1784 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1786 if (!$vertical) {
1787 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1790 if (!empty($resources)) {
1791 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1792 $select->set_help_icon('resources');
1793 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1794 $output .= $OUTPUT->render($select);
1797 if (!empty($activities)) {
1798 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1799 $select->set_help_icon('activities');
1800 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1801 $output .= $OUTPUT->render($select);
1804 if (!$vertical) {
1805 $output .= html_writer::end_tag('div');
1808 $output .= html_writer::end_tag('div');
1810 if (course_ajax_enabled($course)) {
1811 $straddeither = get_string('addresourceoractivity');
1812 // The module chooser link
1813 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1814 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1815 $icon = $OUTPUT->pix_icon('t/add', $straddeither);
1816 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1817 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1818 $modchooser.= html_writer::end_tag('div');
1819 $modchooser.= html_writer::end_tag('div');
1821 // Wrap the normal output in a noscript div
1822 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1823 if ($usemodchooser) {
1824 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1825 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1826 } else {
1827 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1828 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1829 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1831 $output = $modchooser . $output;
1834 if ($return) {
1835 return $output;
1836 } else {
1837 echo $output;
1842 * Retrieve all metadata for the requested modules
1844 * @param object $course The Course
1845 * @param array $modnames An array containing the list of modules and their
1846 * names
1847 * @param int $sectionreturn The section to return to
1848 * @return array A list of stdClass objects containing metadata about each
1849 * module
1851 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1852 global $CFG, $OUTPUT;
1854 // get_module_metadata will be called once per section on the page and courses may show
1855 // different modules to one another
1856 static $modlist = array();
1857 if (!isset($modlist[$course->id])) {
1858 $modlist[$course->id] = array();
1861 $return = array();
1862 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1863 foreach($modnames as $modname => $modnamestr) {
1864 if (!course_allowed_module($course, $modname)) {
1865 continue;
1867 if (isset($modlist[$modname])) {
1868 // This module is already cached
1869 $return[$modname] = $modlist[$course->id][$modname];
1870 continue;
1873 // Include the module lib
1874 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1875 if (!file_exists($libfile)) {
1876 continue;
1878 include_once($libfile);
1880 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1881 $gettypesfunc = $modname.'_get_types';
1882 if (function_exists($gettypesfunc)) {
1883 if ($types = $gettypesfunc()) {
1884 $group = new stdClass();
1885 $group->name = $modname;
1886 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1887 foreach($types as $type) {
1888 if ($type->typestr === '--') {
1889 continue;
1891 if (strpos($type->typestr, '--') === 0) {
1892 $group->title = str_replace('--', '', $type->typestr);
1893 continue;
1895 // Set the Sub Type metadata
1896 $subtype = new stdClass();
1897 $subtype->title = $type->typestr;
1898 $subtype->type = str_replace('&amp;', '&', $type->type);
1899 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1900 $subtype->archetype = $type->modclass;
1902 // The group archetype should match the subtype archetypes and all subtypes
1903 // should have the same archetype
1904 $group->archetype = $subtype->archetype;
1906 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1907 $subtype->help = get_string('help' . $subtype->name, $modname);
1909 $subtype->link = $urlbase . $subtype->type;
1910 $group->types[] = $subtype;
1912 $modlist[$course->id][$modname] = $group;
1914 } else {
1915 $module = new stdClass();
1916 $module->title = get_string('modulename', $modname);
1917 $module->name = $modname;
1918 $module->link = $urlbase . $modname;
1919 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1920 $sm = get_string_manager();
1921 if ($sm->string_exists('modulename_help', $modname)) {
1922 $module->help = get_string('modulename_help', $modname);
1923 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1924 $link = get_string('modulename_link', $modname);
1925 $linktext = get_string('morehelp');
1926 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1929 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1930 $modlist[$course->id][$modname] = $module;
1932 $return[$modname] = $modlist[$course->id][$modname];
1935 return $return;
1939 * Return the course category context for the category with id $categoryid, except
1940 * that if $categoryid is 0, return the system context.
1942 * @param integer $categoryid a category id or 0.
1943 * @return object the corresponding context
1945 function get_category_or_system_context($categoryid) {
1946 if ($categoryid) {
1947 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1948 } else {
1949 return context_system::instance();
1954 * Gets the child categories of a given courses category. Uses a static cache
1955 * to make repeat calls efficient.
1957 * @param int $parentid the id of a course category.
1958 * @return array all the child course categories.
1960 function get_child_categories($parentid) {
1961 static $allcategories = null;
1963 // only fill in this variable the first time
1964 if (null == $allcategories) {
1965 $allcategories = array();
1967 $categories = get_categories();
1968 foreach ($categories as $category) {
1969 if (empty($allcategories[$category->parent])) {
1970 $allcategories[$category->parent] = array();
1972 $allcategories[$category->parent][] = $category;
1976 if (empty($allcategories[$parentid])) {
1977 return array();
1978 } else {
1979 return $allcategories[$parentid];
1984 * This function recursively travels the categories, building up a nice list
1985 * for display. It also makes an array that list all the parents for each
1986 * category.
1988 * For example, if you have a tree of categories like:
1989 * Miscellaneous (id = 1)
1990 * Subcategory (id = 2)
1991 * Sub-subcategory (id = 4)
1992 * Other category (id = 3)
1993 * Then after calling this function you will have
1994 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1995 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1996 * 3 => 'Other category');
1997 * $parents = array(2 => array(1), 4 => array(1, 2));
1999 * If you specify $requiredcapability, then only categories where the current
2000 * user has that capability will be added to $list, although all categories
2001 * will still be added to $parents, and if you only have $requiredcapability
2002 * in a child category, not the parent, then the child catgegory will still be
2003 * included.
2005 * If you specify the option $excluded, then that category, and all its children,
2006 * are omitted from the tree. This is useful when you are doing something like
2007 * moving categories, where you do not want to allow people to move a category
2008 * to be the child of itself.
2010 * @param array $list For output, accumulates an array categoryid => full category path name
2011 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2012 * @param string/array $requiredcapability if given, only categories where the current
2013 * user has this capability will be added to $list. Can also be an array of capabilities,
2014 * in which case they are all required.
2015 * @param integer $excludeid Omit this category and its children from the lists built.
2016 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2017 * @param string $path For internal use, as part of recursive calls.
2019 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2020 $excludeid = 0, $category = NULL, $path = "") {
2022 // initialize the arrays if needed
2023 if (!is_array($list)) {
2024 $list = array();
2026 if (!is_array($parents)) {
2027 $parents = array();
2030 if (empty($category)) {
2031 // Start at the top level.
2032 $category = new stdClass;
2033 $category->id = 0;
2034 } else {
2035 // This is the excluded category, don't include it.
2036 if ($excludeid > 0 && $excludeid == $category->id) {
2037 return;
2040 $context = context_coursecat::instance($category->id);
2041 $categoryname = format_string($category->name, true, array('context' => $context));
2043 // Update $path.
2044 if ($path) {
2045 $path = $path.' / '.$categoryname;
2046 } else {
2047 $path = $categoryname;
2050 // Add this category to $list, if the permissions check out.
2051 if (empty($requiredcapability)) {
2052 $list[$category->id] = $path;
2054 } else {
2055 $requiredcapability = (array)$requiredcapability;
2056 if (has_all_capabilities($requiredcapability, $context)) {
2057 $list[$category->id] = $path;
2062 // Add all the children recursively, while updating the parents array.
2063 if ($categories = get_child_categories($category->id)) {
2064 foreach ($categories as $cat) {
2065 if (!empty($category->id)) {
2066 if (isset($parents[$category->id])) {
2067 $parents[$cat->id] = $parents[$category->id];
2069 $parents[$cat->id][] = $category->id;
2071 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2077 * This function generates a structured array of courses and categories.
2079 * The depth of categories is limited by $CFG->maxcategorydepth however there
2080 * is no limit on the number of courses!
2082 * Suitable for use with the course renderers course_category_tree method:
2083 * $renderer = $PAGE->get_renderer('core','course');
2084 * echo $renderer->course_category_tree(get_course_category_tree());
2086 * @global moodle_database $DB
2087 * @param int $id
2088 * @param int $depth
2090 function get_course_category_tree($id = 0, $depth = 0) {
2091 global $DB, $CFG;
2092 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2093 $categories = get_child_categories($id);
2094 $categoryids = array();
2095 foreach ($categories as $key => &$category) {
2096 if (!$category->visible && !$viewhiddencats) {
2097 unset($categories[$key]);
2098 continue;
2100 $categoryids[$category->id] = $category;
2101 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2102 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2103 foreach ($subcategories as $subid=>$subcat) {
2104 $categoryids[$subid] = $subcat;
2106 $category->courses = array();
2110 if ($depth > 0) {
2111 // This is a recursive call so return the required array
2112 return array($categories, $categoryids);
2115 if (empty($categoryids)) {
2116 // No categories available (probably all hidden).
2117 return array();
2120 // The depth is 0 this function has just been called so we can finish it off
2122 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2123 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2124 $sql = "SELECT
2125 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2126 $ccselect
2127 FROM {course} c
2128 $ccjoin
2129 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2130 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2131 // loop throught them
2132 foreach ($courses as $course) {
2133 if ($course->id == SITEID) {
2134 continue;
2136 context_instance_preload($course);
2137 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2138 $categoryids[$course->category]->courses[$course->id] = $course;
2142 return $categories;
2146 * Recursive function to print out all the categories in a nice format
2147 * with or without courses included
2149 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2150 global $CFG;
2152 // maxcategorydepth == 0 meant no limit
2153 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2154 return;
2157 if (!$displaylist) {
2158 make_categories_list($displaylist, $parentslist);
2161 if ($category) {
2162 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2163 print_category_info($category, $depth, $showcourses);
2164 } else {
2165 return; // Don't bother printing children of invisible categories
2168 } else {
2169 $category = new stdClass();
2170 $category->id = "0";
2173 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2174 $countcats = count($categories);
2175 $count = 0;
2176 $first = true;
2177 $last = false;
2178 foreach ($categories as $cat) {
2179 $count++;
2180 if ($count == $countcats) {
2181 $last = true;
2183 $up = $first ? false : true;
2184 $down = $last ? false : true;
2185 $first = false;
2187 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2193 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2195 function make_categories_options() {
2196 make_categories_list($cats,$parents);
2197 foreach ($cats as $key => $value) {
2198 if (array_key_exists($key,$parents)) {
2199 if ($indent = count($parents[$key])) {
2200 for ($i = 0; $i < $indent; $i++) {
2201 $cats[$key] = '&nbsp;'.$cats[$key];
2206 return $cats;
2210 * Prints the category info in indented fashion
2211 * This function is only used by print_whole_category_list() above
2213 function print_category_info($category, $depth=0, $showcourses = false) {
2214 global $CFG, $DB, $OUTPUT;
2216 $strsummary = get_string('summary');
2218 $catlinkcss = null;
2219 if (!$category->visible) {
2220 $catlinkcss = array('class'=>'dimmed');
2222 static $coursecount = null;
2223 if (null === $coursecount) {
2224 // only need to check this once
2225 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2228 if ($showcourses and $coursecount) {
2229 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2230 } else {
2231 $catimage = "&nbsp;";
2234 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2235 $context = context_coursecat::instance($category->id);
2236 $fullname = format_string($category->name, true, array('context' => $context));
2238 if ($showcourses and $coursecount) {
2239 echo '<div class="categorylist clearfix">';
2240 $cat = '';
2241 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2242 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2243 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2245 $html = '';
2246 if ($depth > 0) {
2247 for ($i=0; $i< $depth; $i++) {
2248 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2249 $cat = '';
2251 } else {
2252 $html = $cat;
2254 echo html_writer::tag('div', $html, array('class'=>'category'));
2255 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2257 // does the depth exceed maxcategorydepth
2258 // maxcategorydepth == 0 or unset meant no limit
2259 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2260 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2261 foreach ($courses as $course) {
2262 $linkcss = null;
2263 if (!$course->visible) {
2264 $linkcss = array('class'=>'dimmed');
2267 $coursename = get_course_display_name_for_list($course);
2268 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2270 // print enrol info
2271 $courseicon = '';
2272 if ($icons = enrol_get_course_info_icons($course)) {
2273 foreach ($icons as $pix_icon) {
2274 $courseicon = $OUTPUT->render($pix_icon).' ';
2278 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2280 if ($course->summary) {
2281 $link = new moodle_url('/course/info.php?id='.$course->id);
2282 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2283 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2284 array('title'=>$strsummary));
2286 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2289 $html = '';
2290 for ($i=0; $i <= $depth; $i++) {
2291 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2292 $coursecontent = '';
2294 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2297 echo '</div>';
2298 } else {
2299 echo '<div class="categorylist">';
2300 $html = '';
2301 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2302 if (count($courses) > 0) {
2303 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2306 if ($depth > 0) {
2307 for ($i=0; $i< $depth; $i++) {
2308 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2309 $cat = '';
2311 } else {
2312 $html = $cat;
2315 echo html_writer::tag('div', $html, array('class'=>'category'));
2316 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2317 echo '</div>';
2322 * Print the buttons relating to course requests.
2324 * @param object $systemcontext the system context.
2326 function print_course_request_buttons($systemcontext) {
2327 global $CFG, $DB, $OUTPUT;
2328 if (empty($CFG->enablecourserequests)) {
2329 return;
2331 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2332 /// Print a button to request a new course
2333 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2335 /// Print a button to manage pending requests
2336 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2337 $disabled = !$DB->record_exists('course_request', array());
2338 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2343 * Does the user have permission to edit things in this category?
2345 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2346 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2348 function can_edit_in_category($categoryid = 0) {
2349 $context = get_category_or_system_context($categoryid);
2350 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2354 * Prints the turn editing on/off button on course/index.php or course/category.php.
2356 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2357 * @return string HTML of the editing button, or empty string, if this user is not allowed
2358 * to see it.
2360 function update_category_button($categoryid = 0) {
2361 global $CFG, $PAGE, $OUTPUT;
2363 // Check permissions.
2364 if (!can_edit_in_category($categoryid)) {
2365 return '';
2368 // Work out the appropriate action.
2369 if ($PAGE->user_is_editing()) {
2370 $label = get_string('turneditingoff');
2371 $edit = 'off';
2372 } else {
2373 $label = get_string('turneditingon');
2374 $edit = 'on';
2377 // Generate the button HTML.
2378 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2379 if ($categoryid) {
2380 $options['id'] = $categoryid;
2381 $page = 'category.php';
2382 } else {
2383 $page = 'index.php';
2385 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2389 * Category is 0 (for all courses) or an object
2391 function print_courses($category) {
2392 global $CFG, $OUTPUT;
2394 if (!is_object($category) && $category==0) {
2395 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2396 if (is_array($categories) && count($categories) == 1) {
2397 $category = array_shift($categories);
2398 $courses = get_courses_wmanagers($category->id,
2399 'c.sortorder ASC',
2400 array('summary','summaryformat'));
2401 } else {
2402 $courses = get_courses_wmanagers('all',
2403 'c.sortorder ASC',
2404 array('summary','summaryformat'));
2406 unset($categories);
2407 } else {
2408 $courses = get_courses_wmanagers($category->id,
2409 'c.sortorder ASC',
2410 array('summary','summaryformat'));
2413 if ($courses) {
2414 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2415 foreach ($courses as $course) {
2416 $coursecontext = context_course::instance($course->id);
2417 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2418 echo html_writer::start_tag('li');
2419 print_course($course);
2420 echo html_writer::end_tag('li');
2423 echo html_writer::end_tag('ul');
2424 } else {
2425 echo $OUTPUT->heading(get_string("nocoursesyet"));
2426 $context = context_system::instance();
2427 if (has_capability('moodle/course:create', $context)) {
2428 $options = array();
2429 if (!empty($category->id)) {
2430 $options['category'] = $category->id;
2431 } else {
2432 $options['category'] = $CFG->defaultrequestcategory;
2434 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2435 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2436 echo html_writer::end_tag('div');
2442 * Print a description of a course, suitable for browsing in a list.
2444 * @param object $course the course object.
2445 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2447 function print_course($course, $highlightterms = '') {
2448 global $CFG, $USER, $DB, $OUTPUT;
2450 $context = context_course::instance($course->id);
2452 // Rewrite file URLs so that they are correct
2453 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2455 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2456 echo html_writer::start_tag('div', array('class'=>'info'));
2457 echo html_writer::start_tag('h3', array('class'=>'name'));
2459 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2461 $coursename = get_course_display_name_for_list($course);
2462 $linktext = highlight($highlightterms, format_string($coursename));
2463 $linkparams = array('title'=>get_string('entercourse'));
2464 if (empty($course->visible)) {
2465 $linkparams['class'] = 'dimmed';
2467 echo html_writer::link($linkhref, $linktext, $linkparams);
2468 echo html_writer::end_tag('h3');
2470 /// first find all roles that are supposed to be displayed
2471 if (!empty($CFG->coursecontact)) {
2472 $managerroles = explode(',', $CFG->coursecontact);
2473 $rusers = array();
2475 if (!isset($course->managers)) {
2476 list($sort, $sortparams) = users_order_by_sql('u');
2477 $rusers = get_role_users($managerroles, $context, true,
2478 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2479 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2480 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2481 } else {
2482 // use the managers array if we have it for perf reasosn
2483 // populate the datastructure like output of get_role_users();
2484 foreach ($course->managers as $manager) {
2485 $user = clone($manager->user);
2486 $user->roleid = $manager->roleid;
2487 $user->rolename = $manager->rolename;
2488 $user->roleshortname = $manager->roleshortname;
2489 $user->rolecoursealias = $manager->rolecoursealias;
2490 $rusers[$user->id] = $user;
2494 $namesarray = array();
2495 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2496 foreach ($rusers as $ra) {
2497 if (isset($namesarray[$ra->id])) {
2498 // only display a user once with the higest sortorder role
2499 continue;
2502 $role = new stdClass();
2503 $role->id = $ra->roleid;
2504 $role->name = $ra->rolename;
2505 $role->shortname = $ra->roleshortname;
2506 $role->coursealias = $ra->rolecoursealias;
2507 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2509 $fullname = fullname($ra, $canviewfullnames);
2510 $namesarray[$ra->id] = $rolename.': '.
2511 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2514 if (!empty($namesarray)) {
2515 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2516 foreach ($namesarray as $name) {
2517 echo html_writer::tag('li', $name);
2519 echo html_writer::end_tag('ul');
2522 echo html_writer::end_tag('div'); // End of info div
2524 echo html_writer::start_tag('div', array('class'=>'summary'));
2525 $options = new stdClass();
2526 $options->noclean = true;
2527 $options->para = false;
2528 $options->overflowdiv = true;
2529 if (!isset($course->summaryformat)) {
2530 $course->summaryformat = FORMAT_MOODLE;
2532 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2533 if ($icons = enrol_get_course_info_icons($course)) {
2534 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2535 foreach ($icons as $icon) {
2536 echo $OUTPUT->render($icon);
2538 echo html_writer::end_tag('div'); // End of enrolmenticons div
2540 echo html_writer::end_tag('div'); // End of summary div
2541 echo html_writer::end_tag('div'); // End of coursebox div
2545 * Prints custom user information on the home page.
2546 * Over time this can include all sorts of information
2548 function print_my_moodle() {
2549 global $USER, $CFG, $DB, $OUTPUT;
2551 if (!isloggedin() or isguestuser()) {
2552 print_error('nopermissions', '', '', 'See My Moodle');
2555 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2556 $rhosts = array();
2557 $rcourses = array();
2558 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2559 $rcourses = get_my_remotecourses($USER->id);
2560 $rhosts = get_my_remotehosts();
2563 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2565 if (!empty($courses)) {
2566 echo '<ul class="unlist">';
2567 foreach ($courses as $course) {
2568 if ($course->id == SITEID) {
2569 continue;
2571 echo '<li>';
2572 print_course($course);
2573 echo "</li>\n";
2575 echo "</ul>\n";
2578 // MNET
2579 if (!empty($rcourses)) {
2580 // at the IDP, we know of all the remote courses
2581 foreach ($rcourses as $course) {
2582 print_remote_course($course, "100%");
2584 } elseif (!empty($rhosts)) {
2585 // non-IDP, we know of all the remote servers, but not courses
2586 foreach ($rhosts as $host) {
2587 print_remote_host($host, "100%");
2590 unset($course);
2591 unset($host);
2593 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2594 echo "<table width=\"100%\"><tr><td align=\"center\">";
2595 print_course_search("", false, "short");
2596 echo "</td><td align=\"center\">";
2597 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2598 echo "</td></tr></table>\n";
2601 } else {
2602 if ($DB->count_records("course_categories") > 1) {
2603 echo $OUTPUT->box_start("categorybox");
2604 print_whole_category_list();
2605 echo $OUTPUT->box_end();
2606 } else {
2607 print_courses(0);
2613 function print_course_search($value="", $return=false, $format="plain") {
2614 global $CFG;
2615 static $count = 0;
2617 $count++;
2619 $id = 'coursesearch';
2621 if ($count > 1) {
2622 $id .= $count;
2625 $strsearchcourses= get_string("searchcourses");
2627 if ($format == 'plain') {
2628 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2629 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2630 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2631 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2632 $output .= '<input type="submit" value="'.get_string('go').'" />';
2633 $output .= '</fieldset></form>';
2634 } else if ($format == 'short') {
2635 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2636 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2637 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2638 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2639 $output .= '<input type="submit" value="'.get_string('go').'" />';
2640 $output .= '</fieldset></form>';
2641 } else if ($format == 'navbar') {
2642 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2643 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2644 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2645 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2646 $output .= '<input type="submit" value="'.get_string('go').'" />';
2647 $output .= '</fieldset></form>';
2650 if ($return) {
2651 return $output;
2653 echo $output;
2656 function print_remote_course($course, $width="100%") {
2657 global $CFG, $USER;
2659 $linkcss = '';
2661 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2663 echo '<div class="coursebox remotecoursebox clearfix">';
2664 echo '<div class="info">';
2665 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2666 $linkcss.' href="'.$url.'">'
2667 . format_string($course->fullname) .'</a><br />'
2668 . format_string($course->hostname) . ' : '
2669 . format_string($course->cat_name) . ' : '
2670 . format_string($course->shortname). '</div>';
2671 echo '</div><div class="summary">';
2672 $options = new stdClass();
2673 $options->noclean = true;
2674 $options->para = false;
2675 $options->overflowdiv = true;
2676 echo format_text($course->summary, $course->summaryformat, $options);
2677 echo '</div>';
2678 echo '</div>';
2681 function print_remote_host($host, $width="100%") {
2682 global $OUTPUT;
2684 $linkcss = '';
2686 echo '<div class="coursebox clearfix">';
2687 echo '<div class="info">';
2688 echo '<div class="name">';
2689 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2690 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2691 . s($host['name']).'</a> - ';
2692 echo $host['count'] . ' ' . get_string('courses');
2693 echo '</div>';
2694 echo '</div>';
2695 echo '</div>';
2699 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2701 function add_course_module($mod) {
2702 global $DB;
2704 $mod->added = time();
2705 unset($mod->id);
2707 $cmid = $DB->insert_record("course_modules", $mod);
2708 rebuild_course_cache($mod->course, true);
2709 return $cmid;
2713 * Creates missing course section(s) and rebuilds course cache
2715 * @param int|stdClass $courseorid course id or course object
2716 * @param int|array $sections list of relative section numbers to create
2717 * @return bool if there were any sections created
2719 function course_create_sections_if_missing($courseorid, $sections) {
2720 global $DB;
2721 if (!is_array($sections)) {
2722 $sections = array($sections);
2724 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2725 if (is_object($courseorid)) {
2726 $courseorid = $courseorid->id;
2728 $coursechanged = false;
2729 foreach ($sections as $sectionnum) {
2730 if (!in_array($sectionnum, $existing)) {
2731 $cw = new stdClass();
2732 $cw->course = $courseorid;
2733 $cw->section = $sectionnum;
2734 $cw->summary = '';
2735 $cw->summaryformat = FORMAT_HTML;
2736 $cw->sequence = '';
2737 $id = $DB->insert_record("course_sections", $cw);
2738 $coursechanged = true;
2741 if ($coursechanged) {
2742 rebuild_course_cache($courseorid, true);
2744 return $coursechanged;
2748 * Adds an existing module to the section
2750 * Updates both tables {course_sections} and {course_modules}
2752 * @param int|stdClass $courseorid course id or course object
2753 * @param int $modid id of the module already existing in course_modules table
2754 * @param int $sectionnum relative number of the section (field course_sections.section)
2755 * If section does not exist it will be created
2756 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2757 * before which the module needs to be included. Null for inserting in the
2758 * end of the section
2759 * @return int The course_sections ID where the module is inserted
2761 function course_add_cm_to_section($courseorid, $modid, $sectionnum, $beforemod = null) {
2762 global $DB, $COURSE;
2763 if (is_object($beforemod)) {
2764 $beforemod = $beforemod->id;
2766 course_create_sections_if_missing($courseorid, $sectionnum);
2767 $section = get_fast_modinfo($courseorid)->get_section_info($sectionnum);
2768 $modarray = explode(",", trim($section->sequence));
2769 if (empty($section->sequence)) {
2770 $newsequence = "$modid";
2771 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2772 $insertarray = array($modid, $beforemod);
2773 array_splice($modarray, $key[0], 1, $insertarray);
2774 $newsequence = implode(",", $modarray);
2775 } else {
2776 $newsequence = "$section->sequence,$modid";
2778 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2779 $DB->set_field('course_modules', 'section', $section->id, array('id' => $modid));
2780 if (is_object($courseorid)) {
2781 rebuild_course_cache($courseorid->id, true);
2782 } else {
2783 rebuild_course_cache($courseorid, true);
2785 return $section->id; // Return course_sections ID that was used.
2788 function set_coursemodule_groupmode($id, $groupmode) {
2789 global $DB;
2790 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2791 if ($cm->groupmode != $groupmode) {
2792 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2793 rebuild_course_cache($cm->course, true);
2795 return ($cm->groupmode != $groupmode);
2798 function set_coursemodule_idnumber($id, $idnumber) {
2799 global $DB;
2800 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2801 if ($cm->idnumber != $idnumber) {
2802 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2803 rebuild_course_cache($cm->course, true);
2805 return ($cm->idnumber != $idnumber);
2809 * $prevstateoverrides = true will set the visibility of the course module
2810 * to what is defined in visibleold. This enables us to remember the current
2811 * visibility when making a whole section hidden, so that when we toggle
2812 * that section back to visible, we are able to return the visibility of
2813 * the course module back to what it was originally.
2815 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2816 global $DB, $CFG;
2817 require_once($CFG->libdir.'/gradelib.php');
2819 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2820 return false;
2822 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2823 return false;
2825 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2826 foreach($events as $event) {
2827 if ($visible) {
2828 show_event($event);
2829 } else {
2830 hide_event($event);
2835 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2836 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2837 if ($grade_items) {
2838 foreach ($grade_items as $grade_item) {
2839 $grade_item->set_hidden(!$visible);
2843 if ($prevstateoverrides) {
2844 if ($visible == '0') {
2845 // Remember the current visible state so we can toggle this back.
2846 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2847 } else {
2848 // Get the previous saved visible states.
2849 $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2851 } else {
2852 $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2854 rebuild_course_cache($cm->course, true);
2855 return true;
2859 * Delete a course module and any associated data at the course level (events)
2860 * Until 1.5 this function simply marked a deleted flag ... now it
2861 * deletes it completely.
2864 function delete_course_module($id) {
2865 global $CFG, $DB;
2866 require_once($CFG->libdir.'/gradelib.php');
2867 require_once($CFG->dirroot.'/blog/lib.php');
2869 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2870 return true;
2872 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2873 //delete events from calendar
2874 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2875 foreach($events as $event) {
2876 delete_event($event->id);
2879 //delete grade items, outcome items and grades attached to modules
2880 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2881 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2882 foreach ($grade_items as $grade_item) {
2883 $grade_item->delete('moddelete');
2886 // Delete completion and availability data; it is better to do this even if the
2887 // features are not turned on, in case they were turned on previously (these will be
2888 // very quick on an empty table)
2889 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2890 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2891 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2892 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2893 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2895 delete_context(CONTEXT_MODULE, $cm->id);
2896 $DB->delete_records('course_modules', array('id'=>$cm->id));
2897 rebuild_course_cache($cm->course, true);
2898 return true;
2901 function delete_mod_from_section($modid, $sectionid) {
2902 global $DB;
2904 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2906 $modarray = explode(",", $section->sequence);
2908 if ($key = array_keys ($modarray, $modid)) {
2909 array_splice($modarray, $key[0], 1);
2910 $newsequence = implode(",", $modarray);
2911 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2912 rebuild_course_cache($section->course, true);
2913 return true;
2914 } else {
2915 return false;
2919 return false;
2923 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2925 * @param object $course course object
2926 * @param int $section Section number (not id!!!)
2927 * @param int $move (-1 or 1)
2928 * @return boolean true if section moved successfully
2929 * @todo MDL-33379 remove this function in 2.5
2931 function move_section($course, $section, $move) {
2932 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2934 /// Moves a whole course section up and down within the course
2935 global $USER;
2937 if (!$move) {
2938 return true;
2941 $sectiondest = $section + $move;
2943 // compartibility with course formats using field 'numsections'
2944 $courseformatoptions = course_get_format($course)->get_format_options();
2945 if (array_key_exists('numsections', $courseformatoptions) &&
2946 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2947 return false;
2950 $retval = move_section_to($course, $section, $sectiondest);
2951 return $retval;
2955 * Moves a section within a course, from a position to another.
2956 * Be very careful: $section and $destination refer to section number,
2957 * not id!.
2959 * @param object $course
2960 * @param int $section Section number (not id!!!)
2961 * @param int $destination
2962 * @return boolean Result
2964 function move_section_to($course, $section, $destination) {
2965 /// Moves a whole course section up and down within the course
2966 global $USER, $DB;
2968 if (!$destination && $destination != 0) {
2969 return true;
2972 // compartibility with course formats using field 'numsections'
2973 $courseformatoptions = course_get_format($course)->get_format_options();
2974 if ((array_key_exists('numsections', $courseformatoptions) &&
2975 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
2976 return false;
2979 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2980 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2981 'section ASC, id ASC', 'id, section')) {
2982 return false;
2985 $movedsections = reorder_sections($sections, $section, $destination);
2987 // Update all sections. Do this in 2 steps to avoid breaking database
2988 // uniqueness constraint
2989 $transaction = $DB->start_delegated_transaction();
2990 foreach ($movedsections as $id => $position) {
2991 if ($sections[$id] !== $position) {
2992 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2995 foreach ($movedsections as $id => $position) {
2996 if ($sections[$id] !== $position) {
2997 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3001 // If we move the highlighted section itself, then just highlight the destination.
3002 // Adjust the higlighted section location if we move something over it either direction.
3003 if ($section == $course->marker) {
3004 course_set_marker($course->id, $destination);
3005 } elseif ($section > $course->marker && $course->marker >= $destination) {
3006 course_set_marker($course->id, $course->marker+1);
3007 } elseif ($section < $course->marker && $course->marker <= $destination) {
3008 course_set_marker($course->id, $course->marker-1);
3011 $transaction->allow_commit();
3012 rebuild_course_cache($course->id, true);
3013 return true;
3017 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3018 * an original position number and a target position number, rebuilds the array so that the
3019 * move is made without any duplication of section positions.
3020 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3021 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3023 * @param array $sections
3024 * @param int $origin_position
3025 * @param int $target_position
3026 * @return array
3028 function reorder_sections($sections, $origin_position, $target_position) {
3029 if (!is_array($sections)) {
3030 return false;
3033 // We can't move section position 0
3034 if ($origin_position < 1) {
3035 echo "We can't move section position 0";
3036 return false;
3039 // Locate origin section in sections array
3040 if (!$origin_key = array_search($origin_position, $sections)) {
3041 echo "searched position not in sections array";
3042 return false; // searched position not in sections array
3045 // Extract origin section
3046 $origin_section = $sections[$origin_key];
3047 unset($sections[$origin_key]);
3049 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3050 $found = false;
3051 $append_array = array();
3052 foreach ($sections as $id => $position) {
3053 if ($found) {
3054 $append_array[$id] = $position;
3055 unset($sections[$id]);
3057 if ($position == $target_position) {
3058 if ($target_position < $origin_position) {
3059 $append_array[$id] = $position;
3060 unset($sections[$id]);
3062 $found = true;
3066 // Append moved section
3067 $sections[$origin_key] = $origin_section;
3069 // Append rest of array (if applicable)
3070 if (!empty($append_array)) {
3071 foreach ($append_array as $id => $position) {
3072 $sections[$id] = $position;
3076 // Renumber positions
3077 $position = 0;
3078 foreach ($sections as $id => $p) {
3079 $sections[$id] = $position;
3080 $position++;
3083 return $sections;
3088 * Move the module object $mod to the specified $section
3089 * If $beforemod exists then that is the module
3090 * before which $modid should be inserted
3091 * All parameters are objects
3093 function moveto_module($mod, $section, $beforemod=NULL) {
3094 global $OUTPUT;
3096 /// Remove original module from original section
3097 if (! delete_mod_from_section($mod->id, $mod->section)) {
3098 echo $OUTPUT->notification("Could not delete module from existing section");
3101 // if moving to a hidden section then hide module
3102 if (!$section->visible && $mod->visible) {
3103 set_coursemodule_visible($mod->id, 0);
3106 /// Add the module into the new section
3107 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3108 return true;
3112 * Produces the editing buttons for a module
3114 * @global core_renderer $OUTPUT
3115 * @staticvar type $str
3116 * @param stdClass $mod The module to produce editing buttons for
3117 * @param bool $absolute_ignored ignored - all links are absolute
3118 * @param bool $moveselect If true a move seleciton process is used (default true)
3119 * @param int $indent The current indenting
3120 * @param int $section The section to link back to
3121 * @return string XHTML for the editing buttons
3123 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3124 global $CFG, $OUTPUT, $COURSE;
3126 static $str;
3128 $coursecontext = context_course::instance($mod->course);
3129 $modcontext = context_module::instance($mod->id);
3131 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3132 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3134 // no permission to edit anything
3135 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3136 return false;
3139 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3141 if (!isset($str)) {
3142 $str = new stdClass;
3143 $str->assign = get_string("assignroles", 'role');
3144 $str->delete = get_string("delete");
3145 $str->move = get_string("move");
3146 $str->moveup = get_string("moveup");
3147 $str->movedown = get_string("movedown");
3148 $str->moveright = get_string("moveright");
3149 $str->moveleft = get_string("moveleft");
3150 $str->update = get_string("update");
3151 $str->duplicate = get_string("duplicate");
3152 $str->hide = get_string("hide");
3153 $str->show = get_string("show");
3154 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3155 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3156 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3157 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3158 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3159 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3160 $str->edittitle = get_string('edittitle', 'moodle');
3163 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3165 if ($section !== null) {
3166 $baseurl->param('sr', $section);
3168 $actions = array();
3170 // AJAX edit title
3171 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3172 $actions[] = new action_link(
3173 new moodle_url($baseurl, array('update' => $mod->id)),
3174 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3175 null,
3176 array('class' => 'editing_title', 'title' => $str->edittitle)
3180 // leftright
3181 if ($hasmanageactivities) {
3182 if (right_to_left()) { // Exchange arrows on RTL
3183 $rightarrow = 't/left';
3184 $leftarrow = 't/right';
3185 } else {
3186 $rightarrow = 't/right';
3187 $leftarrow = 't/left';
3190 if ($indent > 0) {
3191 $actions[] = new action_link(
3192 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3193 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3194 null,
3195 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3198 if ($indent >= 0) {
3199 $actions[] = new action_link(
3200 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3201 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3202 null,
3203 array('class' => 'editing_moveright', 'title' => $str->moveright)
3208 // move
3209 if ($hasmanageactivities) {
3210 if ($moveselect) {
3211 $actions[] = new action_link(
3212 new moodle_url($baseurl, array('copy' => $mod->id)),
3213 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3214 null,
3215 array('class' => 'editing_move', 'title' => $str->move)
3217 } else {
3218 $actions[] = new action_link(
3219 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3220 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3221 null,
3222 array('class' => 'editing_moveup', 'title' => $str->moveup)
3224 $actions[] = new action_link(
3225 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3226 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3227 null,
3228 array('class' => 'editing_movedown', 'title' => $str->movedown)
3233 // Update
3234 if ($hasmanageactivities) {
3235 $actions[] = new action_link(
3236 new moodle_url($baseurl, array('update' => $mod->id)),
3237 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3238 null,
3239 array('class' => 'editing_update', 'title' => $str->update)
3243 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3244 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3245 $actions[] = new action_link(
3246 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3247 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3248 null,
3249 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3253 // Delete
3254 if ($hasmanageactivities) {
3255 $actions[] = new action_link(
3256 new moodle_url($baseurl, array('delete' => $mod->id)),
3257 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3258 null,
3259 array('class' => 'editing_delete', 'title' => $str->delete)
3263 // hideshow
3264 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3265 if ($mod->visible) {
3266 $actions[] = new action_link(
3267 new moodle_url($baseurl, array('hide' => $mod->id)),
3268 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3269 null,
3270 array('class' => 'editing_hide', 'title' => $str->hide)
3272 } else {
3273 $actions[] = new action_link(
3274 new moodle_url($baseurl, array('show' => $mod->id)),
3275 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3276 null,
3277 array('class' => 'editing_show', 'title' => $str->show)
3282 // groupmode
3283 if ($hasmanageactivities and $mod->groupmode !== false) {
3284 if ($mod->groupmode == SEPARATEGROUPS) {
3285 $groupmode = 0;
3286 $grouptitle = $str->groupsseparate;
3287 $forcedgrouptitle = $str->forcedgroupsseparate;
3288 $groupclass = 'editing_groupsseparate';
3289 $groupimage = 't/groups';
3290 } else if ($mod->groupmode == VISIBLEGROUPS) {
3291 $groupmode = 1;
3292 $grouptitle = $str->groupsvisible;
3293 $forcedgrouptitle = $str->forcedgroupsvisible;
3294 $groupclass = 'editing_groupsvisible';
3295 $groupimage = 't/groupv';
3296 } else {
3297 $groupmode = 2;
3298 $grouptitle = $str->groupsnone;
3299 $forcedgrouptitle = $str->forcedgroupsnone;
3300 $groupclass = 'editing_groupsnone';
3301 $groupimage = 't/groupn';
3303 if ($mod->groupmodelink) {
3304 $actions[] = new action_link(
3305 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3306 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3307 null,
3308 array('class' => $groupclass, 'title' => $grouptitle)
3310 } else {
3311 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3315 // Assign
3316 if (has_capability('moodle/role:assign', $modcontext)){
3317 $actions[] = new action_link(
3318 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3319 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3320 null,
3321 array('class' => 'editing_assign', 'title' => $str->assign)
3325 $output = html_writer::start_tag('span', array('class' => 'commands'));
3326 foreach ($actions as $action) {
3327 if ($action instanceof renderable) {
3328 $output .= $OUTPUT->render($action);
3329 } else {
3330 $output .= $action;
3333 $output .= html_writer::end_tag('span');
3334 return $output;
3338 * given a course object with shortname & fullname, this function will
3339 * truncate the the number of chars allowed and add ... if it was too long
3341 function course_format_name ($course,$max=100) {
3343 $context = context_course::instance($course->id);
3344 $shortname = format_string($course->shortname, true, array('context' => $context));
3345 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3346 $str = $shortname.': '. $fullname;
3347 if (textlib::strlen($str) <= $max) {
3348 return $str;
3350 else {
3351 return textlib::substr($str,0,$max-3).'...';
3356 * Is the user allowed to add this type of module to this course?
3357 * @param object $course the course settings. Only $course->id is used.
3358 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3359 * @return bool whether the current user is allowed to add this type of module to this course.
3361 function course_allowed_module($course, $modname) {
3362 if (is_numeric($modname)) {
3363 throw new coding_exception('Function course_allowed_module no longer
3364 supports numeric module ids. Please update your code to pass the module name.');
3367 $capability = 'mod/' . $modname . ':addinstance';
3368 if (!get_capability_info($capability)) {
3369 // Debug warning that the capability does not exist, but no more than once per page.
3370 static $warned = array();
3371 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3372 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3373 debugging('The module ' . $modname . ' does not define the standard capability ' .
3374 $capability , DEBUG_DEVELOPER);
3375 $warned[$modname] = 1;
3378 // If the capability does not exist, the module can always be added.
3379 return true;
3382 $coursecontext = context_course::instance($course->id);
3383 return has_capability($capability, $coursecontext);
3387 * Recursively delete category including all subcategories and courses.
3388 * @param stdClass $category
3389 * @param boolean $showfeedback display some notices
3390 * @return array return deleted courses
3392 function category_delete_full($category, $showfeedback=true) {
3393 global $CFG, $DB;
3394 require_once($CFG->libdir.'/gradelib.php');
3395 require_once($CFG->libdir.'/questionlib.php');
3396 require_once($CFG->dirroot.'/cohort/lib.php');
3398 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3399 foreach ($children as $childcat) {
3400 category_delete_full($childcat, $showfeedback);
3404 $deletedcourses = array();
3405 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3406 foreach ($courses as $course) {
3407 if (!delete_course($course, false)) {
3408 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3410 $deletedcourses[] = $course;
3414 // move or delete cohorts in this context
3415 cohort_delete_category($category);
3417 // now delete anything that may depend on course category context
3418 grade_course_category_delete($category->id, 0, $showfeedback);
3419 if (!question_delete_course_category($category, 0, $showfeedback)) {
3420 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3423 // finally delete the category and it's context
3424 $DB->delete_records('course_categories', array('id'=>$category->id));
3425 delete_context(CONTEXT_COURSECAT, $category->id);
3427 events_trigger('course_category_deleted', $category);
3429 return $deletedcourses;
3433 * Delete category, but move contents to another category.
3434 * @param object $ccategory
3435 * @param int $newparentid category id
3436 * @return bool status
3438 function category_delete_move($category, $newparentid, $showfeedback=true) {
3439 global $CFG, $DB, $OUTPUT;
3440 require_once($CFG->libdir.'/gradelib.php');
3441 require_once($CFG->libdir.'/questionlib.php');
3442 require_once($CFG->dirroot.'/cohort/lib.php');
3444 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3445 return false;
3448 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3449 foreach ($children as $childcat) {
3450 move_category($childcat, $newparentcat);
3454 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3455 if (!move_courses(array_keys($courses), $newparentid)) {
3456 if ($showfeedback) {
3457 echo $OUTPUT->notification("Error moving courses");
3459 return false;
3461 if ($showfeedback) {
3462 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3466 // move or delete cohorts in this context
3467 cohort_delete_category($category);
3469 // now delete anything that may depend on course category context
3470 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3471 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3472 if ($showfeedback) {
3473 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3475 return false;
3478 // finally delete the category and it's context
3479 $DB->delete_records('course_categories', array('id'=>$category->id));
3480 delete_context(CONTEXT_COURSECAT, $category->id);
3482 events_trigger('course_category_deleted', $category);
3484 if ($showfeedback) {
3485 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3487 return true;
3491 * Efficiently moves many courses around while maintaining
3492 * sortorder in order.
3494 * @param array $courseids is an array of course ids
3495 * @param int $categoryid
3496 * @return bool success
3498 function move_courses($courseids, $categoryid) {
3499 global $CFG, $DB, $OUTPUT;
3501 if (empty($courseids)) {
3502 // nothing to do
3503 return;
3506 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3507 return false;
3510 $courseids = array_reverse($courseids);
3511 $newparent = context_coursecat::instance($category->id);
3512 $i = 1;
3514 foreach ($courseids as $courseid) {
3515 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3516 $course = new stdClass();
3517 $course->id = $courseid;
3518 $course->category = $category->id;
3519 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3520 if ($category->visible == 0) {
3521 // hide the course when moving into hidden category,
3522 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3523 $course->visible = 0;
3526 $DB->update_record('course', $course);
3528 $context = context_course::instance($course->id);
3529 context_moved($context, $newparent);
3532 fix_course_sortorder();
3534 return true;
3538 * Hide course category and child course and subcategories
3539 * @param stdClass $category
3540 * @return void
3542 function course_category_hide($category) {
3543 global $DB;
3545 $category->visible = 0;
3546 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3547 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3548 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id)); // store visible flag so that we can return to it if we immediately unhide
3549 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3550 // get all child categories and hide too
3551 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3552 foreach ($subcats as $cat) {
3553 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3554 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3555 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3556 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3562 * Show course category and child course and subcategories
3563 * @param stdClass $category
3564 * @return void
3566 function course_category_show($category) {
3567 global $DB;
3569 $category->visible = 1;
3570 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3571 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3572 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3573 // get all child categories and unhide too
3574 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3575 foreach ($subcats as $cat) {
3576 if ($cat->visibleold) {
3577 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3579 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3585 * Efficiently moves a category - NOTE that this can have
3586 * a huge impact access-control-wise...
3588 function move_category($category, $newparentcat) {
3589 global $CFG, $DB;
3591 $context = context_coursecat::instance($category->id);
3593 $hidecat = false;
3594 if (empty($newparentcat->id)) {
3595 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3597 $newparent = context_system::instance();
3599 } else {
3600 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3601 $newparent = context_coursecat::instance($newparentcat->id);
3603 if (!$newparentcat->visible and $category->visible) {
3604 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3605 $hidecat = true;
3609 context_moved($context, $newparent);
3611 // now make it last in new category
3612 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3614 // and fix the sortorders
3615 fix_course_sortorder();
3617 if ($hidecat) {
3618 course_category_hide($category);
3623 * Returns the display name of the given section that the course prefers
3625 * Implementation of this function is provided by course format
3626 * @see format_base::get_section_name()
3628 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
3629 * @param int|stdClass $section Section object from database or just field course_sections.section
3630 * @return string Display name that the course format prefers, e.g. "Week 2"
3632 function get_section_name($courseorid, $section) {
3633 return course_get_format($courseorid)->get_section_name($section);
3637 * Tells if current course format uses sections
3639 * @param string $format Course format ID e.g. 'weeks' $course->format
3640 * @return bool
3642 function course_format_uses_sections($format) {
3643 $course = new stdClass();
3644 $course->format = $format;
3645 return course_get_format($course)->uses_sections();
3649 * Returns the information about the ajax support in the given source format
3651 * The returned object's property (boolean)capable indicates that
3652 * the course format supports Moodle course ajax features.
3653 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3655 * @param string $format
3656 * @return stdClass
3658 function course_format_ajax_support($format) {
3659 $course = new stdClass();
3660 $course->format = $format;
3661 return course_get_format($course)->supports_ajax();
3665 * Can the current user delete this course?
3666 * Course creators have exception,
3667 * 1 day after the creation they can sill delete the course.
3668 * @param int $courseid
3669 * @return boolean
3671 function can_delete_course($courseid) {
3672 global $USER, $DB;
3674 $context = context_course::instance($courseid);
3676 if (has_capability('moodle/course:delete', $context)) {
3677 return true;
3680 // hack: now try to find out if creator created this course recently (1 day)
3681 if (!has_capability('moodle/course:create', $context)) {
3682 return false;
3685 $since = time() - 60*60*24;
3687 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3688 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3690 return $DB->record_exists_select('log', $select, $params);
3694 * Save the Your name for 'Some role' strings.
3696 * @param integer $courseid the id of this course.
3697 * @param array $data the data that came from the course settings form.
3699 function save_local_role_names($courseid, $data) {
3700 global $DB;
3701 $context = context_course::instance($courseid);
3703 foreach ($data as $fieldname => $value) {
3704 if (strpos($fieldname, 'role_') !== 0) {
3705 continue;
3707 list($ignored, $roleid) = explode('_', $fieldname);
3709 // make up our mind whether we want to delete, update or insert
3710 if (!$value) {
3711 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3713 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3714 $rolename->name = $value;
3715 $DB->update_record('role_names', $rolename);
3717 } else {
3718 $rolename = new stdClass;
3719 $rolename->contextid = $context->id;
3720 $rolename->roleid = $roleid;
3721 $rolename->name = $value;
3722 $DB->insert_record('role_names', $rolename);
3728 * Create a course and either return a $course object
3730 * Please note this functions does not verify any access control,
3731 * the calling code is responsible for all validation (usually it is the form definition).
3733 * @param array $editoroptions course description editor options
3734 * @param object $data - all the data needed for an entry in the 'course' table
3735 * @return object new course instance
3737 function create_course($data, $editoroptions = NULL) {
3738 global $CFG, $DB;
3740 //check the categoryid - must be given for all new courses
3741 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3743 //check if the shortname already exist
3744 if (!empty($data->shortname)) {
3745 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3746 throw new moodle_exception('shortnametaken');
3750 //check if the id number already exist
3751 if (!empty($data->idnumber)) {
3752 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3753 throw new moodle_exception('idnumbertaken');
3757 $data->timecreated = time();
3758 $data->timemodified = $data->timecreated;
3760 // place at beginning of any category
3761 $data->sortorder = 0;
3763 if ($editoroptions) {
3764 // summary text is updated later, we need context to store the files first
3765 $data->summary = '';
3766 $data->summary_format = FORMAT_HTML;
3769 if (!isset($data->visible)) {
3770 // data not from form, add missing visibility info
3771 $data->visible = $category->visible;
3773 $data->visibleold = $data->visible;
3775 $newcourseid = $DB->insert_record('course', $data);
3776 $context = context_course::instance($newcourseid, MUST_EXIST);
3778 if ($editoroptions) {
3779 // Save the files used in the summary editor and store
3780 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3781 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3782 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3785 // update course format options
3786 course_get_format($newcourseid)->update_course_format_options($data);
3788 $course = course_get_format($newcourseid)->get_course();
3790 // Setup the blocks
3791 blocks_add_default_course_blocks($course);
3793 // Create a default section.
3794 course_create_sections_if_missing($course, 0);
3796 fix_course_sortorder();
3798 // new context created - better mark it as dirty
3799 mark_context_dirty($context->path);
3801 // Save any custom role names.
3802 save_local_role_names($course->id, (array)$data);
3804 // set up enrolments
3805 enrol_course_updated(true, $course, $data);
3807 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3809 // Trigger events
3810 events_trigger('course_created', $course);
3812 return $course;
3816 * Create a new course category and marks the context as dirty
3818 * This function does not set the sortorder for the new category and
3819 * @see{fix_course_sortorder} should be called after creating a new course
3820 * category
3822 * Please note that this function does not verify access control.
3824 * @param object $category All of the data required for an entry in the course_categories table
3825 * @return object new course category
3827 function create_course_category($category) {
3828 global $DB;
3830 $category->timemodified = time();
3831 $category->id = $DB->insert_record('course_categories', $category);
3832 $category = $DB->get_record('course_categories', array('id' => $category->id));
3834 // We should mark the context as dirty
3835 $category->context = context_coursecat::instance($category->id);
3836 $category->context->mark_dirty();
3838 return $category;
3842 * Update a course.
3844 * Please note this functions does not verify any access control,
3845 * the calling code is responsible for all validation (usually it is the form definition).
3847 * @param object $data - all the data needed for an entry in the 'course' table
3848 * @param array $editoroptions course description editor options
3849 * @return void
3851 function update_course($data, $editoroptions = NULL) {
3852 global $CFG, $DB;
3854 $data->timemodified = time();
3856 $oldcourse = course_get_format($data->id)->get_course();
3857 $context = context_course::instance($oldcourse->id);
3859 if ($editoroptions) {
3860 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3863 if (!isset($data->category) or empty($data->category)) {
3864 // prevent nulls and 0 in category field
3865 unset($data->category);
3867 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3869 if (!isset($data->visible)) {
3870 // data not from form, add missing visibility info
3871 $data->visible = $oldcourse->visible;
3874 if ($data->visible != $oldcourse->visible) {
3875 // reset the visibleold flag when manually hiding/unhiding course
3876 $data->visibleold = $data->visible;
3877 } else {
3878 if ($movecat) {
3879 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3880 if (empty($newcategory->visible)) {
3881 // make sure when moving into hidden category the course is hidden automatically
3882 $data->visible = 0;
3887 // Update with the new data
3888 $DB->update_record('course', $data);
3889 // make sure the modinfo cache is reset
3890 rebuild_course_cache($data->id);
3892 // update course format options with full course data
3893 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
3895 $course = $DB->get_record('course', array('id'=>$data->id));
3897 if ($movecat) {
3898 $newparent = context_coursecat::instance($course->category);
3899 context_moved($context, $newparent);
3902 fix_course_sortorder();
3904 // Test for and remove blocks which aren't appropriate anymore
3905 blocks_remove_inappropriate($course);
3907 // Save any custom role names.
3908 save_local_role_names($course->id, $data);
3910 // update enrol settings
3911 enrol_course_updated(false, $course, $data);
3913 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3915 // Trigger events
3916 events_trigger('course_updated', $course);
3918 if ($oldcourse->format !== $course->format) {
3919 // Remove all options stored for the previous format
3920 // We assume that new course format migrated everything it needed watching trigger
3921 // 'course_updated' and in method format_XXX::update_course_format_options()
3922 $DB->delete_records('course_format_options',
3923 array('courseid' => $course->id, 'format' => $oldcourse->format));
3928 * Average number of participants
3929 * @return integer
3931 function average_number_of_participants() {
3932 global $DB, $SITE;
3934 //count total of enrolments for visible course (except front page)
3935 $sql = 'SELECT COUNT(*) FROM (
3936 SELECT DISTINCT ue.userid, e.courseid
3937 FROM {user_enrolments} ue, {enrol} e, {course} c
3938 WHERE ue.enrolid = e.id
3939 AND e.courseid <> :siteid
3940 AND c.id = e.courseid
3941 AND c.visible = 1) total';
3942 $params = array('siteid' => $SITE->id);
3943 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3946 //count total of visible courses (minus front page)
3947 $coursetotal = $DB->count_records('course', array('visible' => 1));
3948 $coursetotal = $coursetotal - 1 ;
3950 //average of enrolment
3951 if (empty($coursetotal)) {
3952 $participantaverage = 0;
3953 } else {
3954 $participantaverage = $enrolmenttotal / $coursetotal;
3957 return $participantaverage;
3961 * Average number of course modules
3962 * @return integer
3964 function average_number_of_courses_modules() {
3965 global $DB, $SITE;
3967 //count total of visible course module (except front page)
3968 $sql = 'SELECT COUNT(*) FROM (
3969 SELECT cm.course, cm.module
3970 FROM {course} c, {course_modules} cm
3971 WHERE c.id = cm.course
3972 AND c.id <> :siteid
3973 AND cm.visible = 1
3974 AND c.visible = 1) total';
3975 $params = array('siteid' => $SITE->id);
3976 $moduletotal = $DB->count_records_sql($sql, $params);
3979 //count total of visible courses (minus front page)
3980 $coursetotal = $DB->count_records('course', array('visible' => 1));
3981 $coursetotal = $coursetotal - 1 ;
3983 //average of course module
3984 if (empty($coursetotal)) {
3985 $coursemoduleaverage = 0;
3986 } else {
3987 $coursemoduleaverage = $moduletotal / $coursetotal;
3990 return $coursemoduleaverage;
3994 * This class pertains to course requests and contains methods associated with
3995 * create, approving, and removing course requests.
3997 * Please note we do not allow embedded images here because there is no context
3998 * to store them with proper access control.
4000 * @copyright 2009 Sam Hemelryk
4001 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4002 * @since Moodle 2.0
4004 * @property-read int $id
4005 * @property-read string $fullname
4006 * @property-read string $shortname
4007 * @property-read string $summary
4008 * @property-read int $summaryformat
4009 * @property-read int $summarytrust
4010 * @property-read string $reason
4011 * @property-read int $requester
4013 class course_request {
4016 * This is the stdClass that stores the properties for the course request
4017 * and is externally accessed through the __get magic method
4018 * @var stdClass
4020 protected $properties;
4023 * An array of options for the summary editor used by course request forms.
4024 * This is initially set by {@link summary_editor_options()}
4025 * @var array
4026 * @static
4028 protected static $summaryeditoroptions;
4031 * Static function to prepare the summary editor for working with a course
4032 * request.
4034 * @static
4035 * @param null|stdClass $data Optional, an object containing the default values
4036 * for the form, these may be modified when preparing the
4037 * editor so this should be called before creating the form
4038 * @return stdClass An object that can be used to set the default values for
4039 * an mforms form
4041 public static function prepare($data=null) {
4042 if ($data === null) {
4043 $data = new stdClass;
4045 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4046 return $data;
4050 * Static function to create a new course request when passed an array of properties
4051 * for it.
4053 * This function also handles saving any files that may have been used in the editor
4055 * @static
4056 * @param stdClass $data
4057 * @return course_request The newly created course request
4059 public static function create($data) {
4060 global $USER, $DB, $CFG;
4061 $data->requester = $USER->id;
4063 // Setting the default category if none set.
4064 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
4065 $data->category = $CFG->defaultrequestcategory;
4068 // Summary is a required field so copy the text over
4069 $data->summary = $data->summary_editor['text'];
4070 $data->summaryformat = $data->summary_editor['format'];
4072 $data->id = $DB->insert_record('course_request', $data);
4074 // Create a new course_request object and return it
4075 $request = new course_request($data);
4077 // Notify the admin if required.
4078 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4080 $a = new stdClass;
4081 $a->link = "$CFG->wwwroot/course/pending.php";
4082 $a->user = fullname($USER);
4083 $subject = get_string('courserequest');
4084 $message = get_string('courserequestnotifyemail', 'admin', $a);
4085 foreach ($users as $user) {
4086 $request->notify($user, $USER, 'courserequested', $subject, $message);
4090 return $request;
4094 * Returns an array of options to use with a summary editor
4096 * @uses course_request::$summaryeditoroptions
4097 * @return array An array of options to use with the editor
4099 public static function summary_editor_options() {
4100 global $CFG;
4101 if (self::$summaryeditoroptions === null) {
4102 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4104 return self::$summaryeditoroptions;
4108 * Loads the properties for this course request object. Id is required and if
4109 * only id is provided then we load the rest of the properties from the database
4111 * @param stdClass|int $properties Either an object containing properties
4112 * or the course_request id to load
4114 public function __construct($properties) {
4115 global $DB;
4116 if (empty($properties->id)) {
4117 if (empty($properties)) {
4118 throw new coding_exception('You must provide a course request id when creating a course_request object');
4120 $id = $properties;
4121 $properties = new stdClass;
4122 $properties->id = (int)$id;
4123 unset($id);
4125 if (empty($properties->requester)) {
4126 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4127 print_error('unknowncourserequest');
4129 } else {
4130 $this->properties = $properties;
4132 $this->properties->collision = null;
4136 * Returns the requested property
4138 * @param string $key
4139 * @return mixed
4141 public function __get($key) {
4142 return $this->properties->$key;
4146 * Override this to ensure empty($request->blah) calls return a reliable answer...
4148 * This is required because we define the __get method
4150 * @param mixed $key
4151 * @return bool True is it not empty, false otherwise
4153 public function __isset($key) {
4154 return (!empty($this->properties->$key));
4158 * Returns the user who requested this course
4160 * Uses a static var to cache the results and cut down the number of db queries
4162 * @staticvar array $requesters An array of cached users
4163 * @return stdClass The user who requested the course
4165 public function get_requester() {
4166 global $DB;
4167 static $requesters= array();
4168 if (!array_key_exists($this->properties->requester, $requesters)) {
4169 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4171 return $requesters[$this->properties->requester];
4175 * Checks that the shortname used by the course does not conflict with any other
4176 * courses that exist
4178 * @param string|null $shortnamemark The string to append to the requests shortname
4179 * should a conflict be found
4180 * @return bool true is there is a conflict, false otherwise
4182 public function check_shortname_collision($shortnamemark = '[*]') {
4183 global $DB;
4185 if ($this->properties->collision !== null) {
4186 return $this->properties->collision;
4189 if (empty($this->properties->shortname)) {
4190 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4191 $this->properties->collision = false;
4192 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4193 if (!empty($shortnamemark)) {
4194 $this->properties->shortname .= ' '.$shortnamemark;
4196 $this->properties->collision = true;
4197 } else {
4198 $this->properties->collision = false;
4200 return $this->properties->collision;
4204 * This function approves the request turning it into a course
4206 * This function converts the course request into a course, at the same time
4207 * transferring any files used in the summary to the new course and then removing
4208 * the course request and the files associated with it.
4210 * @return int The id of the course that was created from this request
4212 public function approve() {
4213 global $CFG, $DB, $USER;
4215 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4217 $courseconfig = get_config('moodlecourse');
4219 // Transfer appropriate settings
4220 $data = clone($this->properties);
4221 unset($data->id);
4222 unset($data->reason);
4223 unset($data->requester);
4225 // If the category is not set, if the current user does not have the rights to change the category, or if the
4226 // category does not exist, we set the default category to the course to be approved.
4227 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
4228 if (empty($data->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
4229 (!$category = get_course_category($data->category))) {
4230 $category = get_course_category($CFG->defaultrequestcategory);
4233 // Set category
4234 $data->category = $category->id;
4235 $data->sortorder = $category->sortorder; // place as the first in category
4237 // Set misc settings
4238 $data->requested = 1;
4240 // Apply course default settings
4241 $data->format = $courseconfig->format;
4242 $data->newsitems = $courseconfig->newsitems;
4243 $data->showgrades = $courseconfig->showgrades;
4244 $data->showreports = $courseconfig->showreports;
4245 $data->maxbytes = $courseconfig->maxbytes;
4246 $data->groupmode = $courseconfig->groupmode;
4247 $data->groupmodeforce = $courseconfig->groupmodeforce;
4248 $data->visible = $courseconfig->visible;
4249 $data->visibleold = $data->visible;
4250 $data->lang = $courseconfig->lang;
4252 $course = create_course($data);
4253 $context = context_course::instance($course->id, MUST_EXIST);
4255 // add enrol instances
4256 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4257 if ($manual = enrol_get_plugin('manual')) {
4258 $manual->add_default_instance($course);
4262 // enrol the requester as teacher if necessary
4263 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4264 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4267 $this->delete();
4269 $a = new stdClass();
4270 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
4271 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4272 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4274 return $course->id;
4278 * Reject a course request
4280 * This function rejects a course request, emailing the requesting user the
4281 * provided notice and then removing the request from the database
4283 * @param string $notice The message to display to the user
4285 public function reject($notice) {
4286 global $USER, $DB;
4287 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4288 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4289 $this->delete();
4293 * Deletes the course request and any associated files
4295 public function delete() {
4296 global $DB;
4297 $DB->delete_records('course_request', array('id' => $this->properties->id));
4301 * Send a message from one user to another using events_trigger
4303 * @param object $touser
4304 * @param object $fromuser
4305 * @param string $name
4306 * @param string $subject
4307 * @param string $message
4309 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4310 $eventdata = new stdClass();
4311 $eventdata->component = 'moodle';
4312 $eventdata->name = $name;
4313 $eventdata->userfrom = $fromuser;
4314 $eventdata->userto = $touser;
4315 $eventdata->subject = $subject;
4316 $eventdata->fullmessage = $message;
4317 $eventdata->fullmessageformat = FORMAT_PLAIN;
4318 $eventdata->fullmessagehtml = '';
4319 $eventdata->smallmessage = '';
4320 $eventdata->notification = 1;
4321 message_send($eventdata);
4326 * Return a list of page types
4327 * @param string $pagetype current page type
4328 * @param stdClass $parentcontext Block's parent context
4329 * @param stdClass $currentcontext Current context of block
4331 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4332 // if above course context ,display all course fomats
4333 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4334 if ($course->id == SITEID) {
4335 return array('*'=>get_string('page-x', 'pagetype'));
4336 } else {
4337 return array('*'=>get_string('page-x', 'pagetype'),
4338 'course-*'=>get_string('page-course-x', 'pagetype'),
4339 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4345 * Determine whether course ajax should be enabled for the specified course
4347 * @param stdClass $course The course to test against
4348 * @return boolean Whether course ajax is enabled or note
4350 function course_ajax_enabled($course) {
4351 global $CFG, $PAGE, $SITE;
4353 // Ajax must be enabled globally
4354 if (!$CFG->enableajax) {
4355 return false;
4358 // The user must be editing for AJAX to be included
4359 if (!$PAGE->user_is_editing()) {
4360 return false;
4363 // Check that the theme suports
4364 if (!$PAGE->theme->enablecourseajax) {
4365 return false;
4368 // Check that the course format supports ajax functionality
4369 // The site 'format' doesn't have information on course format support
4370 if ($SITE->id !== $course->id) {
4371 $courseformatajaxsupport = course_format_ajax_support($course->format);
4372 if (!$courseformatajaxsupport->capable) {
4373 return false;
4377 // All conditions have been met so course ajax should be enabled
4378 return true;
4382 * Include the relevant javascript and language strings for the resource
4383 * toolbox YUI module
4385 * @param integer $id The ID of the course being applied to
4386 * @param array $usedmodules An array containing the names of the modules in use on the page
4387 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4388 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4389 * * resourceurl The URL to post changes to for resource changes
4390 * * sectionurl The URL to post changes to for section changes
4391 * * pageparams Additional parameters to pass through in the post
4392 * @return bool
4394 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4395 global $PAGE, $SITE;
4397 // Ensure that ajax should be included
4398 if (!course_ajax_enabled($course)) {
4399 return false;
4402 if (!$config) {
4403 $config = new stdClass();
4406 // The URL to use for resource changes
4407 if (!isset($config->resourceurl)) {
4408 $config->resourceurl = '/course/rest.php';
4411 // The URL to use for section changes
4412 if (!isset($config->sectionurl)) {
4413 $config->sectionurl = '/course/rest.php';
4416 // Any additional parameters which need to be included on page submission
4417 if (!isset($config->pageparams)) {
4418 $config->pageparams = array();
4421 // Include toolboxes
4422 $PAGE->requires->yui_module('moodle-course-toolboxes',
4423 'M.course.init_resource_toolbox',
4424 array(array(
4425 'courseid' => $course->id,
4426 'ajaxurl' => $config->resourceurl,
4427 'config' => $config,
4430 $PAGE->requires->yui_module('moodle-course-toolboxes',
4431 'M.course.init_section_toolbox',
4432 array(array(
4433 'courseid' => $course->id,
4434 'format' => $course->format,
4435 'ajaxurl' => $config->sectionurl,
4436 'config' => $config,
4440 // Include course dragdrop
4441 if ($course->id != $SITE->id) {
4442 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4443 array(array(
4444 'courseid' => $course->id,
4445 'ajaxurl' => $config->sectionurl,
4446 'config' => $config,
4447 )), null, true);
4449 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4450 array(array(
4451 'courseid' => $course->id,
4452 'ajaxurl' => $config->resourceurl,
4453 'config' => $config,
4454 )), null, true);
4457 // Include blocks dragdrop
4458 $params = array(
4459 'courseid' => $course->id,
4460 'pagetype' => $PAGE->pagetype,
4461 'pagelayout' => $PAGE->pagelayout,
4462 'regions' => $PAGE->blocks->get_regions(),
4464 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4466 // Require various strings for the command toolbox
4467 $PAGE->requires->strings_for_js(array(
4468 'moveleft',
4469 'deletechecktype',
4470 'deletechecktypename',
4471 'edittitle',
4472 'edittitleinstructions',
4473 'show',
4474 'hide',
4475 'groupsnone',
4476 'groupsvisible',
4477 'groupsseparate',
4478 'clicktochangeinbrackets',
4479 'markthistopic',
4480 'markedthistopic',
4481 'move',
4482 'movesection',
4483 ), 'moodle');
4485 // Include format-specific strings
4486 if ($course->id != $SITE->id) {
4487 $PAGE->requires->strings_for_js(array(
4488 'showfromothers',
4489 'hidefromothers',
4490 ), 'format_' . $course->format);
4493 // For confirming resource deletion we need the name of the module in question
4494 foreach ($usedmodules as $module => $modname) {
4495 $PAGE->requires->string_for_js('pluginname', $module);
4498 // Load drag and drop upload AJAX.
4499 dndupload_add_to_course($course, $enabledmodules);
4501 // Add the module chooser
4502 $PAGE->requires->yui_module('moodle-course-modchooser',
4503 'M.course.init_chooser',
4504 array(array('courseid' => $course->id))
4506 $PAGE->requires->strings_for_js(array(
4507 'addresourceoractivity',
4508 'modchooserenable',
4509 'modchooserdisable',
4510 ), 'moodle');
4512 return true;
4516 * The URL to use for the specified course (with section)
4518 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
4519 * @param int|stdClass $section Section object from database or just field course_sections.section
4520 * if omitted the course view page is returned
4521 * @param array $options options for view URL. At the moment core uses:
4522 * 'navigation' (bool) if true and section has no separate page, the function returns null
4523 * 'sr' (int) used by multipage formats to specify to which section to return
4524 * @return moodle_url The url of course
4526 function course_get_url($courseorid, $section = null, $options = array()) {
4527 return course_get_format($courseorid)->get_view_url($section, $options);