MDL-34082 course restrict modules: typo in MDL-19125 upgrade code.
[moodle.git] / course / lib.php
blobcf8f3723c714f82e8fb8fa1805286589dcc95213
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');
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
35 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
36 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
37 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
38 define('FRONTPAGENEWS', '0');
39 define('FRONTPAGECOURSELIST', '1');
40 define('FRONTPAGECATEGORYNAMES', '2');
41 define('FRONTPAGETOPICONLY', '3');
42 define('FRONTPAGECATEGORYCOMBO', '4');
43 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
44 define('EXCELROWS', 65535);
45 define('FIRSTUSEDEXCELROW', 3);
47 define('MOD_CLASS_ACTIVITY', 0);
48 define('MOD_CLASS_RESOURCE', 1);
50 function make_log_url($module, $url) {
51 switch ($module) {
52 case 'course':
53 if (strpos($url, 'report/') === 0) {
54 // there is only one report type, course reports are deprecated
55 $url = "/$url";
56 break;
58 case 'file':
59 case 'login':
60 case 'lib':
61 case 'admin':
62 case 'calendar':
63 case 'mnet course':
64 if (strpos($url, '../') === 0) {
65 $url = ltrim($url, '.');
66 } else {
67 $url = "/course/$url";
69 break;
70 case 'user':
71 case 'blog':
72 $url = "/$module/$url";
73 break;
74 case 'upload':
75 $url = $url;
76 break;
77 case 'coursetags':
78 $url = '/'.$url;
79 break;
80 case 'library':
81 case '':
82 $url = '/';
83 break;
84 case 'message':
85 $url = "/message/$url";
86 break;
87 case 'notes':
88 $url = "/notes/$url";
89 break;
90 case 'tag':
91 $url = "/tag/$url";
92 break;
93 case 'role':
94 $url = '/'.$url;
95 break;
96 default:
97 $url = "/mod/$module/$url";
98 break;
101 //now let's sanitise urls - there might be some ugly nasties:-(
102 $parts = explode('?', $url);
103 $script = array_shift($parts);
104 if (strpos($script, 'http') === 0) {
105 $script = clean_param($script, PARAM_URL);
106 } else {
107 $script = clean_param($script, PARAM_PATH);
110 $query = '';
111 if ($parts) {
112 $query = implode('', $parts);
113 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
114 $parts = explode('&', $query);
115 $eq = urlencode('=');
116 foreach ($parts as $key=>$part) {
117 $part = urlencode(urldecode($part));
118 $part = str_replace($eq, '=', $part);
119 $parts[$key] = $part;
121 $query = '?'.implode('&amp;', $parts);
124 return $script.$query;
128 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
129 $modname="", $modid=0, $modaction="", $groupid=0) {
130 global $CFG, $DB;
132 // It is assumed that $date is the GMT time of midnight for that day,
133 // and so the next 86400 seconds worth of logs are printed.
135 /// Setup for group handling.
137 // TODO: I don't understand group/context/etc. enough to be able to do
138 // something interesting with it here
139 // What is the context of a remote course?
141 /// If the group mode is separate, and this user does not have editing privileges,
142 /// then only the user's group can be viewed.
143 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
144 // $groupid = get_current_group($course->id);
146 /// If this course doesn't have groups, no groupid can be specified.
147 //else if (!$course->groupmode) {
148 // $groupid = 0;
151 $groupid = 0;
153 $joins = array();
154 $where = '';
156 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
157 FROM {mnet_log} l
158 LEFT JOIN {user} u ON l.userid = u.id
159 WHERE ";
160 $params = array();
162 $where .= "l.hostid = :hostid";
163 $params['hostid'] = $hostid;
165 // TODO: Is 1 really a magic number referring to the sitename?
166 if ($course != SITEID || $modid != 0) {
167 $where .= " AND l.course=:courseid";
168 $params['courseid'] = $course;
171 if ($modname) {
172 $where .= " AND l.module = :modname";
173 $params['modname'] = $modname;
176 if ('site_errors' === $modid) {
177 $where .= " AND ( l.action='error' OR l.action='infected' )";
178 } else if ($modid) {
179 //TODO: This assumes that modids are the same across sites... probably
180 //not true
181 $where .= " AND l.cmid = :modid";
182 $params['modid'] = $modid;
185 if ($modaction) {
186 $firstletter = substr($modaction, 0, 1);
187 if ($firstletter == '-') {
188 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
189 $params['modaction'] = '%'.substr($modaction, 1).'%';
190 } else {
191 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
192 $params['modaction'] = '%'.$modaction.'%';
196 if ($user) {
197 $where .= " AND l.userid = :user";
198 $params['user'] = $user;
201 if ($date) {
202 $enddate = $date + 86400;
203 $where .= " AND l.time > :date AND l.time < :enddate";
204 $params['date'] = $date;
205 $params['enddate'] = $enddate;
208 $result = array();
209 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
210 if(!empty($result['totalcount'])) {
211 $where .= " ORDER BY $order";
212 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
213 } else {
214 $result['logs'] = array();
216 return $result;
219 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
220 $modname="", $modid=0, $modaction="", $groupid=0) {
221 global $DB, $SESSION, $USER;
222 // It is assumed that $date is the GMT time of midnight for that day,
223 // and so the next 86400 seconds worth of logs are printed.
225 /// Setup for group handling.
227 /// If the group mode is separate, and this user does not have editing privileges,
228 /// then only the user's group can be viewed.
229 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
230 if (isset($SESSION->currentgroup[$course->id])) {
231 $groupid = $SESSION->currentgroup[$course->id];
232 } else {
233 $groupid = groups_get_all_groups($course->id, $USER->id);
234 if (is_array($groupid)) {
235 $groupid = array_shift(array_keys($groupid));
236 $SESSION->currentgroup[$course->id] = $groupid;
237 } else {
238 $groupid = 0;
242 /// If this course doesn't have groups, no groupid can be specified.
243 else if (!$course->groupmode) {
244 $groupid = 0;
247 $joins = array();
248 $params = array();
250 if ($course->id != SITEID || $modid != 0) {
251 $joins[] = "l.course = :courseid";
252 $params['courseid'] = $course->id;
255 if ($modname) {
256 $joins[] = "l.module = :modname";
257 $params['modname'] = $modname;
260 if ('site_errors' === $modid) {
261 $joins[] = "( l.action='error' OR l.action='infected' )";
262 } else if ($modid) {
263 $joins[] = "l.cmid = :modid";
264 $params['modid'] = $modid;
267 if ($modaction) {
268 $firstletter = substr($modaction, 0, 1);
269 if ($firstletter == '-') {
270 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
271 $params['modaction'] = '%'.substr($modaction, 1).'%';
272 } else {
273 $joins[] = $DB->sql_like('l.action', ':modaction', false);
274 $params['modaction'] = '%'.$modaction.'%';
279 /// Getting all members of a group.
280 if ($groupid and !$user) {
281 if ($gusers = groups_get_members($groupid)) {
282 $gusers = array_keys($gusers);
283 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
284 } else {
285 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
288 else if ($user) {
289 $joins[] = "l.userid = :userid";
290 $params['userid'] = $user;
293 if ($date) {
294 $enddate = $date + 86400;
295 $joins[] = "l.time > :date AND l.time < :enddate";
296 $params['date'] = $date;
297 $params['enddate'] = $enddate;
300 $selector = implode(' AND ', $joins);
302 $totalcount = 0; // Initialise
303 $result = array();
304 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
305 $result['totalcount'] = $totalcount;
306 return $result;
310 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
311 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
313 global $CFG, $DB, $OUTPUT;
315 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
316 $modname, $modid, $modaction, $groupid)) {
317 echo $OUTPUT->notification("No logs found!");
318 echo $OUTPUT->footer();
319 exit;
322 $courses = array();
324 if ($course->id == SITEID) {
325 $courses[0] = '';
326 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
327 foreach ($ccc as $cc) {
328 $courses[$cc->id] = $cc->shortname;
331 } else {
332 $courses[$course->id] = $course->shortname;
335 $totalcount = $logs['totalcount'];
336 $count=0;
337 $ldcache = array();
338 $tt = getdate(time());
339 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
341 $strftimedatetime = get_string("strftimedatetime");
343 echo "<div class=\"info\">\n";
344 print_string("displayingrecords", "", $totalcount);
345 echo "</div>\n";
347 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
349 $table = new html_table();
350 $table->classes = array('logtable','generalbox');
351 $table->align = array('right', 'left', 'left');
352 $table->head = array(
353 get_string('time'),
354 get_string('ip_address'),
355 get_string('fullnameuser'),
356 get_string('action'),
357 get_string('info')
359 $table->data = array();
361 if ($course->id == SITEID) {
362 array_unshift($table->align, 'left');
363 array_unshift($table->head, get_string('course'));
366 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
367 if (empty($logs['logs'])) {
368 $logs['logs'] = array();
371 foreach ($logs['logs'] as $log) {
373 if (isset($ldcache[$log->module][$log->action])) {
374 $ld = $ldcache[$log->module][$log->action];
375 } else {
376 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
377 $ldcache[$log->module][$log->action] = $ld;
379 if ($ld && is_numeric($log->info)) {
380 // ugly hack to make sure fullname is shown correctly
381 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
382 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
383 } else {
384 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
388 //Filter log->info
389 $log->info = format_string($log->info);
391 // If $log->url has been trimmed short by the db size restriction
392 // code in add_to_log, keep a note so we don't add a link to a broken url
393 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
395 $row = array();
396 if ($course->id == SITEID) {
397 if (empty($log->course)) {
398 $row[] = get_string('site');
399 } else {
400 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
404 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
406 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
407 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
409 $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))));
411 $displayaction="$log->module $log->action";
412 if ($brokenurl) {
413 $row[] = $displayaction;
414 } else {
415 $link = make_log_url($log->module,$log->url);
416 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
418 $row[] = $log->info;
419 $table->data[] = $row;
422 echo html_writer::table($table);
423 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
427 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
428 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
430 global $CFG, $DB, $OUTPUT;
432 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
433 $modname, $modid, $modaction, $groupid)) {
434 echo $OUTPUT->notification("No logs found!");
435 echo $OUTPUT->footer();
436 exit;
439 if ($course->id == SITEID) {
440 $courses[0] = '';
441 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
442 foreach ($ccc as $cc) {
443 $courses[$cc->id] = $cc->shortname;
448 $totalcount = $logs['totalcount'];
449 $count=0;
450 $ldcache = array();
451 $tt = getdate(time());
452 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
454 $strftimedatetime = get_string("strftimedatetime");
456 echo "<div class=\"info\">\n";
457 print_string("displayingrecords", "", $totalcount);
458 echo "</div>\n";
460 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
462 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
463 echo "<tr>";
464 if ($course->id == SITEID) {
465 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
467 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
468 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
469 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
470 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
471 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
472 echo "</tr>\n";
474 if (empty($logs['logs'])) {
475 echo "</table>\n";
476 return;
479 $row = 1;
480 foreach ($logs['logs'] as $log) {
482 $log->info = $log->coursename;
483 $row = ($row + 1) % 2;
485 if (isset($ldcache[$log->module][$log->action])) {
486 $ld = $ldcache[$log->module][$log->action];
487 } else {
488 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
489 $ldcache[$log->module][$log->action] = $ld;
491 if (0 && $ld && !empty($log->info)) {
492 // ugly hack to make sure fullname is shown correctly
493 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
494 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
495 } else {
496 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
500 //Filter log->info
501 $log->info = format_string($log->info);
503 echo '<tr class="r'.$row.'">';
504 if ($course->id == SITEID) {
505 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
506 echo "<td class=\"r$row c0\" >\n";
507 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
508 echo "</td>\n";
510 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
511 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
512 echo "<td class=\"r$row c2\" >\n";
513 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
514 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
515 echo "</td>\n";
516 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
517 echo "<td class=\"r$row c3\" >\n";
518 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
519 echo "</td>\n";
520 echo "<td class=\"r$row c4\">\n";
521 echo $log->action .': '.$log->module;
522 echo "</td>\n";;
523 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
524 echo "</tr>\n";
526 echo "</table>\n";
528 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
532 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
533 $modid, $modaction, $groupid) {
534 global $DB, $CFG;
536 require_once($CFG->libdir . '/csvlib.class.php');
538 $csvexporter = new csv_export_writer('tab');
540 $header = array();
541 $header[] = get_string('course');
542 $header[] = get_string('time');
543 $header[] = get_string('ip_address');
544 $header[] = get_string('fullnameuser');
545 $header[] = get_string('action');
546 $header[] = get_string('info');
548 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
549 $modname, $modid, $modaction, $groupid)) {
550 return false;
553 $courses = array();
555 if ($course->id == SITEID) {
556 $courses[0] = '';
557 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
558 foreach ($ccc as $cc) {
559 $courses[$cc->id] = $cc->shortname;
562 } else {
563 $courses[$course->id] = $course->shortname;
566 $count=0;
567 $ldcache = array();
568 $tt = getdate(time());
569 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
571 $strftimedatetime = get_string("strftimedatetime");
573 $csvexporter->set_filename('logs', '.txt');
574 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
575 $csvexporter->add_data($title);
576 $csvexporter->add_data($header);
578 if (empty($logs['logs'])) {
579 return true;
582 foreach ($logs['logs'] as $log) {
583 if (isset($ldcache[$log->module][$log->action])) {
584 $ld = $ldcache[$log->module][$log->action];
585 } else {
586 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
587 $ldcache[$log->module][$log->action] = $ld;
589 if ($ld && !empty($log->info)) {
590 // ugly hack to make sure fullname is shown correctly
591 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
592 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
593 } else {
594 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
598 //Filter log->info
599 $log->info = format_string($log->info);
600 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
602 $coursecontext = context_course::instance($course->id);
603 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
604 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
605 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
606 $csvexporter->add_data($row);
608 $csvexporter->download_file();
609 return true;
613 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
614 $modid, $modaction, $groupid) {
616 global $CFG, $DB;
618 require_once("$CFG->libdir/excellib.class.php");
620 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
621 $modname, $modid, $modaction, $groupid)) {
622 return false;
625 $courses = array();
627 if ($course->id == SITEID) {
628 $courses[0] = '';
629 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
630 foreach ($ccc as $cc) {
631 $courses[$cc->id] = $cc->shortname;
634 } else {
635 $courses[$course->id] = $course->shortname;
638 $count=0;
639 $ldcache = array();
640 $tt = getdate(time());
641 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
643 $strftimedatetime = get_string("strftimedatetime");
645 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
646 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
647 $filename .= '.xls';
649 $workbook = new MoodleExcelWorkbook('-');
650 $workbook->send($filename);
652 $worksheet = array();
653 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
654 get_string('fullnameuser'), get_string('action'), get_string('info'));
656 // Creating worksheets
657 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
658 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
659 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
660 $worksheet[$wsnumber]->set_column(1, 1, 30);
661 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
662 userdate(time(), $strftimedatetime));
663 $col = 0;
664 foreach ($headers as $item) {
665 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
666 $col++;
670 if (empty($logs['logs'])) {
671 $workbook->close();
672 return true;
675 $formatDate =& $workbook->add_format();
676 $formatDate->set_num_format(get_string('log_excel_date_format'));
678 $row = FIRSTUSEDEXCELROW;
679 $wsnumber = 1;
680 $myxls =& $worksheet[$wsnumber];
681 foreach ($logs['logs'] as $log) {
682 if (isset($ldcache[$log->module][$log->action])) {
683 $ld = $ldcache[$log->module][$log->action];
684 } else {
685 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
686 $ldcache[$log->module][$log->action] = $ld;
688 if ($ld && !empty($log->info)) {
689 // ugly hack to make sure fullname is shown correctly
690 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
691 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
692 } else {
693 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
697 // Filter log->info
698 $log->info = format_string($log->info);
699 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
701 if ($nroPages>1) {
702 if ($row > EXCELROWS) {
703 $wsnumber++;
704 $myxls =& $worksheet[$wsnumber];
705 $row = FIRSTUSEDEXCELROW;
709 $coursecontext = context_course::instance($course->id);
711 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
712 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
713 $myxls->write($row, 2, $log->ip, '');
714 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
715 $myxls->write($row, 3, $fullname, '');
716 $myxls->write($row, 4, $log->module.' '.$log->action, '');
717 $myxls->write($row, 5, $log->info, '');
719 $row++;
722 $workbook->close();
723 return true;
726 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
727 $modid, $modaction, $groupid) {
729 global $CFG, $DB;
731 require_once("$CFG->libdir/odslib.class.php");
733 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
734 $modname, $modid, $modaction, $groupid)) {
735 return false;
738 $courses = array();
740 if ($course->id == SITEID) {
741 $courses[0] = '';
742 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
743 foreach ($ccc as $cc) {
744 $courses[$cc->id] = $cc->shortname;
747 } else {
748 $courses[$course->id] = $course->shortname;
751 $count=0;
752 $ldcache = array();
753 $tt = getdate(time());
754 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
756 $strftimedatetime = get_string("strftimedatetime");
758 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
759 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
760 $filename .= '.ods';
762 $workbook = new MoodleODSWorkbook('-');
763 $workbook->send($filename);
765 $worksheet = array();
766 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
767 get_string('fullnameuser'), get_string('action'), get_string('info'));
769 // Creating worksheets
770 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
771 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
772 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
773 $worksheet[$wsnumber]->set_column(1, 1, 30);
774 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
775 userdate(time(), $strftimedatetime));
776 $col = 0;
777 foreach ($headers as $item) {
778 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
779 $col++;
783 if (empty($logs['logs'])) {
784 $workbook->close();
785 return true;
788 $formatDate =& $workbook->add_format();
789 $formatDate->set_num_format(get_string('log_excel_date_format'));
791 $row = FIRSTUSEDEXCELROW;
792 $wsnumber = 1;
793 $myxls =& $worksheet[$wsnumber];
794 foreach ($logs['logs'] as $log) {
795 if (isset($ldcache[$log->module][$log->action])) {
796 $ld = $ldcache[$log->module][$log->action];
797 } else {
798 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
799 $ldcache[$log->module][$log->action] = $ld;
801 if ($ld && !empty($log->info)) {
802 // ugly hack to make sure fullname is shown correctly
803 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
804 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
805 } else {
806 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
810 // Filter log->info
811 $log->info = format_string($log->info);
812 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
814 if ($nroPages>1) {
815 if ($row > EXCELROWS) {
816 $wsnumber++;
817 $myxls =& $worksheet[$wsnumber];
818 $row = FIRSTUSEDEXCELROW;
822 $coursecontext = context_course::instance($course->id);
824 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
825 $myxls->write_date($row, 1, $log->time);
826 $myxls->write_string($row, 2, $log->ip);
827 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
828 $myxls->write_string($row, 3, $fullname);
829 $myxls->write_string($row, 4, $log->module.' '.$log->action);
830 $myxls->write_string($row, 5, $log->info);
832 $row++;
835 $workbook->close();
836 return true;
840 function print_overview($courses, array $remote_courses=array()) {
841 global $CFG, $USER, $DB, $OUTPUT;
843 $htmlarray = array();
844 if ($modules = $DB->get_records('modules')) {
845 foreach ($modules as $mod) {
846 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
847 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
848 $fname = $mod->name.'_print_overview';
849 if (function_exists($fname)) {
850 $fname($courses,$htmlarray);
855 foreach ($courses as $course) {
856 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
857 echo $OUTPUT->box_start('coursebox');
858 $attributes = array('title' => s($fullname));
859 if (empty($course->visible)) {
860 $attributes['class'] = 'dimmed';
862 echo $OUTPUT->heading(html_writer::link(
863 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
864 if (array_key_exists($course->id,$htmlarray)) {
865 foreach ($htmlarray[$course->id] as $modname => $html) {
866 echo $html;
869 echo $OUTPUT->box_end();
872 if (!empty($remote_courses)) {
873 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
875 foreach ($remote_courses as $course) {
876 echo $OUTPUT->box_start('coursebox');
877 $attributes = array('title' => s($course->fullname));
878 echo $OUTPUT->heading(html_writer::link(
879 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
880 format_string($course->shortname),
881 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
882 echo $OUTPUT->box_end();
888 * This function trawls through the logs looking for
889 * anything new since the user's last login
891 function print_recent_activity($course) {
892 // $course is an object
893 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
895 $context = context_course::instance($course->id);
897 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
899 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
901 if (!isguestuser()) {
902 if (!empty($USER->lastcourseaccess[$course->id])) {
903 if ($USER->lastcourseaccess[$course->id] > $timestart) {
904 $timestart = $USER->lastcourseaccess[$course->id];
909 echo '<div class="activitydate">';
910 echo get_string('activitysince', '', userdate($timestart));
911 echo '</div>';
912 echo '<div class="activityhead">';
914 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
916 echo "</div>\n";
918 $content = false;
920 /// Firstly, have there been any new enrolments?
922 $users = get_recent_enrolments($course->id, $timestart);
924 //Accessibility: new users now appear in an <OL> list.
925 if ($users) {
926 echo '<div class="newusers">';
927 echo $OUTPUT->heading(get_string("newusers").':', 3);
928 $content = true;
929 echo "<ol class=\"list\">\n";
930 foreach ($users as $user) {
931 $fullname = fullname($user, $viewfullnames);
932 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
934 echo "</ol>\n</div>\n";
937 /// Next, have there been any modifications to the course structure?
939 $modinfo = get_fast_modinfo($course);
941 $changelist = array();
943 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
944 module = 'course' AND
945 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
946 array($timestart, $course->id), "id ASC");
948 if ($logs) {
949 $actions = array('add mod', 'update mod', 'delete mod');
950 $newgones = array(); // added and later deleted items
951 foreach ($logs as $key => $log) {
952 if (!in_array($log->action, $actions)) {
953 continue;
955 $info = explode(' ', $log->info);
957 // note: in most cases I replaced hardcoding of label with use of
958 // $cm->has_view() but it was not possible to do this here because
959 // we don't necessarily have the $cm for it
960 if ($info[0] == 'label') { // Labels are ignored in recent activity
961 continue;
964 if (count($info) != 2) {
965 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
966 continue;
969 $modname = $info[0];
970 $instanceid = $info[1];
972 if ($log->action == 'delete mod') {
973 // unfortunately we do not know if the mod was visible
974 if (!array_key_exists($log->info, $newgones)) {
975 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
976 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
978 } else {
979 if (!isset($modinfo->instances[$modname][$instanceid])) {
980 if ($log->action == 'add mod') {
981 // do not display added and later deleted activities
982 $newgones[$log->info] = true;
984 continue;
986 $cm = $modinfo->instances[$modname][$instanceid];
987 if (!$cm->uservisible) {
988 continue;
991 if ($log->action == 'add mod') {
992 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
993 $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>");
995 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
996 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
997 $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>");
1003 if (!empty($changelist)) {
1004 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1005 $content = true;
1006 foreach ($changelist as $changeinfo => $change) {
1007 echo '<p class="activity">'.$change['text'].'</p>';
1011 /// Now display new things from each module
1013 $usedmodules = array();
1014 foreach($modinfo->cms as $cm) {
1015 if (isset($usedmodules[$cm->modname])) {
1016 continue;
1018 if (!$cm->uservisible) {
1019 continue;
1021 $usedmodules[$cm->modname] = $cm->modname;
1024 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1025 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1026 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1027 $print_recent_activity = $modname.'_print_recent_activity';
1028 if (function_exists($print_recent_activity)) {
1029 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1030 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1032 } else {
1033 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1037 if (! $content) {
1038 echo '<p class="message">'.get_string('nothingnew').'</p>';
1043 * For a given course, returns an array of course activity objects
1044 * Each item in the array contains he following properties:
1046 function get_array_of_activities($courseid) {
1047 // cm - course module id
1048 // mod - name of the module (eg forum)
1049 // section - the number of the section (eg week or topic)
1050 // name - the name of the instance
1051 // visible - is the instance visible or not
1052 // groupingid - grouping id
1053 // groupmembersonly - is this instance visible to group members only
1054 // extra - contains extra string to include in any link
1055 global $CFG, $DB;
1056 if(!empty($CFG->enableavailability)) {
1057 require_once($CFG->libdir.'/conditionlib.php');
1060 $course = $DB->get_record('course', array('id'=>$courseid));
1062 if (empty($course)) {
1063 throw new moodle_exception('courseidnotfound');
1066 $mod = array();
1068 $rawmods = get_course_mods($courseid);
1069 if (empty($rawmods)) {
1070 return $mod; // always return array
1073 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1074 foreach ($sections as $section) {
1075 if (!empty($section->sequence)) {
1076 $sequence = explode(",", $section->sequence);
1077 foreach ($sequence as $seq) {
1078 if (empty($rawmods[$seq])) {
1079 continue;
1081 $mod[$seq] = new stdClass();
1082 $mod[$seq]->id = $rawmods[$seq]->instance;
1083 $mod[$seq]->cm = $rawmods[$seq]->id;
1084 $mod[$seq]->mod = $rawmods[$seq]->modname;
1086 // Oh dear. Inconsistent names left here for backward compatibility.
1087 $mod[$seq]->section = $section->section;
1088 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1090 $mod[$seq]->module = $rawmods[$seq]->module;
1091 $mod[$seq]->added = $rawmods[$seq]->added;
1092 $mod[$seq]->score = $rawmods[$seq]->score;
1093 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1094 $mod[$seq]->visible = $rawmods[$seq]->visible;
1095 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1096 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1097 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1098 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1099 $mod[$seq]->indent = $rawmods[$seq]->indent;
1100 $mod[$seq]->completion = $rawmods[$seq]->completion;
1101 $mod[$seq]->extra = "";
1102 $mod[$seq]->completiongradeitemnumber =
1103 $rawmods[$seq]->completiongradeitemnumber;
1104 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1105 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1106 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1107 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1108 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1109 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1110 if (!empty($CFG->enableavailability)) {
1111 condition_info::fill_availability_conditions($rawmods[$seq]);
1112 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1113 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1114 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1117 $modname = $mod[$seq]->mod;
1118 $functionname = $modname."_get_coursemodule_info";
1120 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1121 continue;
1124 include_once("$CFG->dirroot/mod/$modname/lib.php");
1126 if ($hasfunction = function_exists($functionname)) {
1127 if ($info = $functionname($rawmods[$seq])) {
1128 if (!empty($info->icon)) {
1129 $mod[$seq]->icon = $info->icon;
1131 if (!empty($info->iconcomponent)) {
1132 $mod[$seq]->iconcomponent = $info->iconcomponent;
1134 if (!empty($info->name)) {
1135 $mod[$seq]->name = $info->name;
1137 if ($info instanceof cached_cm_info) {
1138 // When using cached_cm_info you can include three new fields
1139 // that aren't available for legacy code
1140 if (!empty($info->content)) {
1141 $mod[$seq]->content = $info->content;
1143 if (!empty($info->extraclasses)) {
1144 $mod[$seq]->extraclasses = $info->extraclasses;
1146 if (!empty($info->iconurl)) {
1147 $mod[$seq]->iconurl = $info->iconurl;
1149 if (!empty($info->onclick)) {
1150 $mod[$seq]->onclick = $info->onclick;
1152 if (!empty($info->customdata)) {
1153 $mod[$seq]->customdata = $info->customdata;
1155 } else {
1156 // When using a stdclass, the (horrible) deprecated ->extra field
1157 // is available for BC
1158 if (!empty($info->extra)) {
1159 $mod[$seq]->extra = $info->extra;
1164 // When there is no modname_get_coursemodule_info function,
1165 // but showdescriptions is enabled, then we use the 'intro'
1166 // and 'introformat' fields in the module table
1167 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1168 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1169 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1170 // Set content from intro and introformat. Filters are disabled
1171 // because we filter it with format_text at display time
1172 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1173 $modvalues, $rawmods[$seq]->id, false);
1175 // To save making another query just below, put name in here
1176 $mod[$seq]->name = $modvalues->name;
1179 if (!isset($mod[$seq]->name)) {
1180 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1183 // Minimise the database size by unsetting default options when they are
1184 // 'empty'. This list corresponds to code in the cm_info constructor.
1185 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1186 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1187 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1188 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1189 'completionview', 'completionexpected', 'score', 'showdescription')
1190 as $property) {
1191 if (property_exists($mod[$seq], $property) &&
1192 empty($mod[$seq]->{$property})) {
1193 unset($mod[$seq]->{$property});
1196 // Special case: this value is usually set to null, but may be 0
1197 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1198 is_null($mod[$seq]->completiongradeitemnumber)) {
1199 unset($mod[$seq]->completiongradeitemnumber);
1205 return $mod;
1210 * Returns a number of useful structures for course displays
1212 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1213 global $CFG, $DB, $COURSE;
1215 $mods = array(); // course modules indexed by id
1216 $modnames = array(); // all course module names (except resource!)
1217 $modnamesplural= array(); // all course module names (plural form)
1218 $modnamesused = array(); // course module names used
1220 if ($allmods = $DB->get_records("modules")) {
1221 foreach ($allmods as $mod) {
1222 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1223 continue;
1225 if ($mod->visible) {
1226 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1227 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1230 collatorlib::asort($modnames);
1231 } else {
1232 print_error("nomodules", 'debug');
1235 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1236 $modinfo = get_fast_modinfo($course);
1238 if ($rawmods=$modinfo->cms) {
1239 foreach($rawmods as $mod) { // Index the mods
1240 if (empty($modnames[$mod->modname])) {
1241 continue;
1243 $mods[$mod->id] = $mod;
1244 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1245 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', context_course::instance($courseid))) {
1246 continue;
1248 // Check groupings
1249 if (!groups_course_module_visible($mod)) {
1250 continue;
1252 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1254 if ($modnamesused) {
1255 collatorlib::asort($modnamesused);
1261 * Returns an array of sections for the requested course id
1263 * This function stores the sections against the course id within a staticvar encase
1264 * of subsequent requests. This is used all over + in some standard libs and course
1265 * format callbacks so subsequent requests are a reality.
1267 * Note: Since Moodle 2.3, it is more efficient to get this data by calling
1268 * get_fast_modinfo, then using $modinfo->get_section_info or get_section_info_all.
1270 * @staticvar array $coursesections
1271 * @param int $courseid
1272 * @return array Array of sections
1274 function get_all_sections($courseid) {
1275 global $DB;
1276 static $coursesections = array();
1277 if (!array_key_exists($courseid, $coursesections)) {
1278 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1279 'section, id, course, name, summary, summaryformat, sequence, visible, ' .
1280 'availablefrom, availableuntil, showavailability, groupingid');
1282 return $coursesections[$courseid];
1286 * Set highlighted section. Only one section can be highlighted at the time.
1288 * @param int $courseid course id
1289 * @param int $marker highlight section with this number, 0 means remove higlightin
1290 * @return void
1292 function course_set_marker($courseid, $marker) {
1293 global $DB;
1294 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1298 * For a given course section, marks it visible or hidden,
1299 * and does the same for every activity in that section
1301 * @param int $courseid course id
1302 * @param int $sectionnumber The section number to adjust
1303 * @param int $visibility The new visibility
1304 * @return array A list of resources which were hidden in the section
1306 function set_section_visible($courseid, $sectionnumber, $visibility) {
1307 global $DB;
1309 $resourcestotoggle = array();
1310 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1311 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1312 if (!empty($section->sequence)) {
1313 $modules = explode(",", $section->sequence);
1314 foreach ($modules as $moduleid) {
1315 set_coursemodule_visible($moduleid, $visibility, true);
1318 rebuild_course_cache($courseid);
1320 // Determine which modules are visible for AJAX update
1321 if (!empty($modules)) {
1322 list($insql, $params) = $DB->get_in_or_equal($modules);
1323 $select = 'id ' . $insql . ' AND visible = ?';
1324 array_push($params, $visibility);
1325 if (!$visibility) {
1326 $select .= ' AND visibleold = 1';
1328 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1331 return $resourcestotoggle;
1335 * Obtains shared data that is used in print_section when displaying a
1336 * course-module entry.
1338 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1340 * This data is also used in other areas of the code.
1341 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1342 * @param object $course Moodle course object
1343 * @return array An array with the following values in this order:
1344 * $content (optional extra content for after link),
1345 * $instancename (text of link)
1347 function get_print_section_cm_text(cm_info $cm, $course) {
1348 global $OUTPUT;
1350 // Get content from modinfo if specified. Content displays either
1351 // in addition to the standard link (below), or replaces it if
1352 // the link is turned off by setting ->url to null.
1353 if (($content = $cm->get_content()) !== '') {
1354 // Improve filter performance by preloading filter setttings for all
1355 // activities on the course (this does nothing if called multiple
1356 // times)
1357 filter_preload_activities($cm->get_modinfo());
1359 // Get module context
1360 $modulecontext = context_module::instance($cm->id);
1361 $labelformatoptions = new stdClass();
1362 $labelformatoptions->noclean = true;
1363 $labelformatoptions->overflowdiv = true;
1364 $labelformatoptions->context = $modulecontext;
1365 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1366 } else {
1367 $content = '';
1370 // Get course context
1371 $coursecontext = context_course::instance($course->id);
1372 $stringoptions = new stdClass;
1373 $stringoptions->context = $coursecontext;
1374 $instancename = format_string($cm->name, true, $stringoptions);
1375 return array($content, $instancename);
1379 * Prints a section full of activity modules
1381 * @param stdClass $course The course
1382 * @param stdClass $section The section
1383 * @param array $mods The modules in the section
1384 * @param array $modnamesused An array containing the list of modules and their names
1385 * @param bool $absolute All links are absolute
1386 * @param string $width Width of the container
1387 * @param bool $hidecompletion Hide completion status
1388 * @param int $sectionreturn The section to return to
1389 * @return void
1391 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=0) {
1392 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1394 static $initialised;
1396 static $groupbuttons;
1397 static $groupbuttonslink;
1398 static $isediting;
1399 static $ismoving;
1400 static $strmovehere;
1401 static $strmovefull;
1402 static $strunreadpostsone;
1403 static $modulenames;
1405 if (!isset($initialised)) {
1406 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1407 $groupbuttonslink = (!$course->groupmodeforce);
1408 $isediting = $PAGE->user_is_editing();
1409 $ismoving = $isediting && ismoving($course->id);
1410 if ($ismoving) {
1411 $strmovehere = get_string("movehere");
1412 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1414 $modulenames = array();
1415 $initialised = true;
1418 $modinfo = get_fast_modinfo($course);
1419 $completioninfo = new completion_info($course);
1421 //Accessibility: replace table with list <ul>, but don't output empty list.
1422 if (!empty($section->sequence)) {
1424 // Fix bug #5027, don't want style=\"width:$width\".
1425 echo "<ul class=\"section img-text\">\n";
1426 $sectionmods = explode(",", $section->sequence);
1428 foreach ($sectionmods as $modnumber) {
1429 if (empty($mods[$modnumber])) {
1430 continue;
1434 * @var cm_info
1436 $mod = $mods[$modnumber];
1438 if ($ismoving and $mod->id == $USER->activitycopy) {
1439 // do not display moving mod
1440 continue;
1443 if (isset($modinfo->cms[$modnumber])) {
1444 // We can continue (because it will not be displayed at all)
1445 // if:
1446 // 1) The activity is not visible to users
1447 // and
1448 // 2a) The 'showavailability' option is not set (if that is set,
1449 // we need to display the activity so we can show
1450 // availability info)
1451 // or
1452 // 2b) The 'availableinfo' is empty, i.e. the activity was
1453 // hidden in a way that leaves no info, such as using the
1454 // eye icon.
1455 if (!$modinfo->cms[$modnumber]->uservisible &&
1456 (empty($modinfo->cms[$modnumber]->showavailability) ||
1457 empty($modinfo->cms[$modnumber]->availableinfo))) {
1458 // visibility shortcut
1459 continue;
1461 } else {
1462 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1463 // module not installed
1464 continue;
1466 if (!coursemodule_visible_for_user($mod) &&
1467 empty($mod->showavailability)) {
1468 // full visibility check
1469 continue;
1473 if (!isset($modulenames[$mod->modname])) {
1474 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1476 $modulename = $modulenames[$mod->modname];
1478 // In some cases the activity is visible to user, but it is
1479 // dimmed. This is done if viewhiddenactivities is true and if:
1480 // 1. the activity is not visible, or
1481 // 2. the activity has dates set which do not include current, or
1482 // 3. the activity has any other conditions set (regardless of whether
1483 // current user meets them)
1484 $modcontext = context_module::instance($mod->id);
1485 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1486 $accessiblebutdim = false;
1487 if ($canviewhidden) {
1488 $accessiblebutdim = !$mod->visible;
1489 if (!empty($CFG->enableavailability)) {
1490 $accessiblebutdim = $accessiblebutdim ||
1491 $mod->availablefrom > time() ||
1492 ($mod->availableuntil && $mod->availableuntil < time()) ||
1493 count($mod->conditionsgrade) > 0 ||
1494 count($mod->conditionscompletion) > 0;
1498 $liclasses = array();
1499 $liclasses[] = 'activity';
1500 $liclasses[] = $mod->modname;
1501 $liclasses[] = 'modtype_'.$mod->modname;
1502 $extraclasses = $mod->get_extra_classes();
1503 if ($extraclasses) {
1504 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1506 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1507 if ($ismoving) {
1508 echo '<a title="'.$strmovefull.'"'.
1509 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1510 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1511 ' alt="'.$strmovehere.'" /></a><br />
1515 $classes = array('mod-indent');
1516 if (!empty($mod->indent)) {
1517 $classes[] = 'mod-indent-'.$mod->indent;
1518 if ($mod->indent > 15) {
1519 $classes[] = 'mod-indent-huge';
1522 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1524 // Get data about this course-module
1525 list($content, $instancename) =
1526 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1528 //Accessibility: for files get description via icon, this is very ugly hack!
1529 $altname = '';
1530 $altname = $mod->modfullname;
1531 // Avoid unnecessary duplication: if e.g. a forum name already
1532 // includes the word forum (or Forum, etc) then it is unhelpful
1533 // to include that in the accessible description that is added.
1534 if (false !== strpos(textlib::strtolower($instancename),
1535 textlib::strtolower($altname))) {
1536 $altname = '';
1538 // File type after name, for alphabetic lists (screen reader).
1539 if ($altname) {
1540 $altname = get_accesshide(' '.$altname);
1543 // We may be displaying this just in order to show information
1544 // about visibility, without the actual link
1545 $contentpart = '';
1546 if ($mod->uservisible) {
1547 // Nope - in this case the link is fully working for user
1548 $linkclasses = '';
1549 $textclasses = '';
1550 if ($accessiblebutdim) {
1551 $linkclasses .= ' dimmed';
1552 $textclasses .= ' dimmed_text';
1553 $accesstext = '<span class="accesshide">'.
1554 get_string('hiddenfromstudents').': </span>';
1555 } else {
1556 $accesstext = '';
1558 if ($linkclasses) {
1559 $linkcss = 'class="' . trim($linkclasses) . '" ';
1560 } else {
1561 $linkcss = '';
1563 if ($textclasses) {
1564 $textcss = 'class="' . trim($textclasses) . '" ';
1565 } else {
1566 $textcss = '';
1569 // Get on-click attribute value if specified
1570 $onclick = $mod->get_on_click();
1571 if ($onclick) {
1572 $onclick = ' onclick="' . $onclick . '"';
1575 if ($url = $mod->get_url()) {
1576 // Display link itself
1577 echo '<a ' . $linkcss . $mod->extra . $onclick .
1578 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1579 '" class="activityicon" alt="' .
1580 $modulename . '" /> ' .
1581 $accesstext . '<span class="instancename">' .
1582 $instancename . $altname . '</span></a>';
1584 // If specified, display extra content after link
1585 if ($content) {
1586 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1587 '">' . $content . '</div>';
1589 } else {
1590 // No link, so display only content
1591 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1592 $accesstext . $content . '</div>';
1595 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1596 $groupings = groups_get_all_groupings($course->id);
1597 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1599 } else {
1600 $textclasses = $extraclasses;
1601 $textclasses .= ' dimmed_text';
1602 if ($textclasses) {
1603 $textcss = 'class="' . trim($textclasses) . '" ';
1604 } else {
1605 $textcss = '';
1607 $accesstext = '<span class="accesshide">' .
1608 get_string('notavailableyet', 'condition') .
1609 ': </span>';
1611 if ($url = $mod->get_url()) {
1612 // Display greyed-out text of link
1613 echo '<div ' . $textcss . $mod->extra .
1614 ' >' . '<img src="' . $mod->get_icon_url() .
1615 '" class="activityicon" alt="' .
1616 $modulename .
1617 '" /> <span>'. $instancename . $altname .
1618 '</span></div>';
1620 // Do not display content after link when it is greyed out like this.
1621 } else {
1622 // No link, so display only content (also greyed)
1623 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1624 $accesstext . $content . '</div>';
1628 // Module can put text after the link (e.g. forum unread)
1629 echo $mod->get_after_link();
1631 // If there is content but NO link (eg label), then display the
1632 // content here (BEFORE any icons). In this case cons must be
1633 // displayed after the content so that it makes more sense visually
1634 // and for accessibility reasons, e.g. if you have a one-line label
1635 // it should work similarly (at least in terms of ordering) to an
1636 // activity.
1637 if (empty($url)) {
1638 echo $contentpart;
1641 if ($isediting) {
1642 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1643 if (! $mod->groupmodelink = $groupbuttonslink) {
1644 $mod->groupmode = $course->groupmode;
1647 } else {
1648 $mod->groupmode = false;
1650 echo '&nbsp;&nbsp;';
1651 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1652 echo $mod->get_after_edit_icons();
1655 // Completion
1656 $completion = $hidecompletion
1657 ? COMPLETION_TRACKING_NONE
1658 : $completioninfo->is_enabled($mod);
1659 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1660 !isguestuser() && $mod->uservisible) {
1661 $completiondata = $completioninfo->get_data($mod,true);
1662 $completionicon = '';
1663 if ($isediting) {
1664 switch ($completion) {
1665 case COMPLETION_TRACKING_MANUAL :
1666 $completionicon = 'manual-enabled'; break;
1667 case COMPLETION_TRACKING_AUTOMATIC :
1668 $completionicon = 'auto-enabled'; break;
1669 default: // wtf
1671 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1672 switch($completiondata->completionstate) {
1673 case COMPLETION_INCOMPLETE:
1674 $completionicon = 'manual-n'; break;
1675 case COMPLETION_COMPLETE:
1676 $completionicon = 'manual-y'; break;
1678 } else { // Automatic
1679 switch($completiondata->completionstate) {
1680 case COMPLETION_INCOMPLETE:
1681 $completionicon = 'auto-n'; break;
1682 case COMPLETION_COMPLETE:
1683 $completionicon = 'auto-y'; break;
1684 case COMPLETION_COMPLETE_PASS:
1685 $completionicon = 'auto-pass'; break;
1686 case COMPLETION_COMPLETE_FAIL:
1687 $completionicon = 'auto-fail'; break;
1690 if ($completionicon) {
1691 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1692 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1693 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1694 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1695 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1696 $newstate =
1697 $completiondata->completionstate==COMPLETION_COMPLETE
1698 ? COMPLETION_INCOMPLETE
1699 : COMPLETION_COMPLETE;
1700 // In manual mode the icon is a toggle form...
1702 // If this completion state is used by the
1703 // conditional activities system, we need to turn
1704 // off the JS.
1705 if (!empty($CFG->enableavailability) &&
1706 condition_info::completion_value_used_as_condition($course, $mod)) {
1707 $extraclass = ' preventjs';
1708 } else {
1709 $extraclass = '';
1711 echo "
1712 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1713 <input type='hidden' name='id' value='{$mod->id}' />
1714 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1715 <input type='hidden' name='sesskey' value='".sesskey()."' />
1716 <input type='hidden' name='completionstate' value='$newstate' />
1717 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1718 </div></form>";
1719 } else {
1720 // In auto mode, or when editing, the icon is just an image
1721 echo "<span class='autocompletion'>";
1722 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1727 // If there is content AND a link, then display the content here
1728 // (AFTER any icons). Otherwise it was displayed before
1729 if (!empty($url)) {
1730 echo $contentpart;
1733 // Show availability information (for someone who isn't allowed to
1734 // see the activity itself, or for staff)
1735 if (!$mod->uservisible) {
1736 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1737 } else if ($canviewhidden && !empty($CFG->enableavailability) && $mod->visible) {
1738 $ci = new condition_info($mod);
1739 $fullinfo = $ci->get_full_information();
1740 if($fullinfo) {
1741 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1742 ? 'userrestriction_visible'
1743 : 'userrestriction_hidden','condition',
1744 $fullinfo).'</div>';
1748 echo html_writer::end_tag('div');
1749 echo html_writer::end_tag('li')."\n";
1752 } elseif ($ismoving) {
1753 echo "<ul class=\"section\">\n";
1756 if ($ismoving) {
1757 echo '<li><a title="'.$strmovefull.'"'.
1758 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1759 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1760 ' alt="'.$strmovehere.'" /></a></li>
1763 if (!empty($section->sequence) || $ismoving) {
1764 echo "</ul><!--class='section'-->\n\n";
1769 * Prints the menus to add activities and resources.
1771 * @param stdClass $course The course
1772 * @param stdClass $section The section
1773 * @param array $modnames An array containing the list of modules and their names
1774 * @param bool $vertical Vertical orientation
1775 * @param bool $return Return the menus or send them to output
1776 * @param int $sectionreturn The section to link back to
1777 * @return void|string depending on $return
1779 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false, $sectionreturn=0) {
1780 global $CFG, $OUTPUT;
1782 // check to see if user can add menus
1783 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))) {
1784 return false;
1787 // Retrieve all modules with associated metadata
1788 $modules = get_module_metadata($course, $modnames);
1790 // We'll sort resources and activities into two lists
1791 $resources = array();
1792 $activities = array();
1794 // We need to add the section section to the link for each module
1795 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1797 foreach ($modules as $module) {
1798 if (isset($module->types)) {
1799 // This module has a subtype
1800 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1801 $subtypes = array();
1802 foreach ($module->types as $subtype) {
1803 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1806 // Sort module subtypes into the list
1807 if (!empty($module->title)) {
1808 // This grouping has a name
1809 if ($module->archetype == MOD_CLASS_RESOURCE) {
1810 $resources[] = array($module->title=>$subtypes);
1811 } else {
1812 $activities[] = array($module->title=>$subtypes);
1814 } else {
1815 // This grouping does not have a name
1816 if ($module->archetype == MOD_CLASS_RESOURCE) {
1817 $resources = array_merge($resources, $subtypes);
1818 } else {
1819 $activities = array_merge($activities, $subtypes);
1822 } else {
1823 // This module has no subtypes
1824 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1825 $resources[$module->link . $sectionlink] = $module->title;
1826 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1827 // System modules cannot be added by user, do not add to dropdown
1828 } else {
1829 $activities[$module->link . $sectionlink] = $module->title;
1834 $straddactivity = get_string('addactivity');
1835 $straddresource = get_string('addresource');
1837 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1839 if (!$vertical) {
1840 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1843 if (!empty($resources)) {
1844 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1845 $select->set_help_icon('resources');
1846 $output .= $OUTPUT->render($select);
1849 if (!empty($activities)) {
1850 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1851 $select->set_help_icon('activities');
1852 $output .= $OUTPUT->render($select);
1855 if (!$vertical) {
1856 $output .= html_writer::end_tag('div');
1859 $output .= html_writer::end_tag('div');
1861 if (course_ajax_enabled($course)) {
1862 $straddeither = get_string('addresourceoractivity');
1863 // The module chooser link
1864 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1865 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1866 $icon = $OUTPUT->pix_icon('t/add', $straddeither);
1867 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1868 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1869 $modchooser.= html_writer::end_tag('div');
1870 $modchooser.= html_writer::end_tag('div');
1872 // Wrap the normal output in a noscript div
1873 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1874 if ($usemodchooser) {
1875 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1876 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1877 } else {
1878 $output = html_writer::tag('div', $output, array('class' => 'visibleifjs addresourcedropdown'));
1879 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hiddenifjs addresourcemodchooser'));
1881 $output = $modchooser . $output;
1884 if ($return) {
1885 return $output;
1886 } else {
1887 echo $output;
1892 * Retrieve all metadata for the requested modules
1894 * @param object $course The Course
1895 * @param array $modnames An array containing the list of modules and their
1896 * names
1897 * @param int $sectionreturn The section to return to
1898 * @return array A list of stdClass objects containing metadata about each
1899 * module
1901 function get_module_metadata($course, $modnames, $sectionreturn = 0) {
1902 global $CFG, $OUTPUT;
1904 // get_module_metadata will be called once per section on the page and courses may show
1905 // different modules to one another
1906 static $modlist = array();
1907 if (!isset($modlist[$course->id])) {
1908 $modlist[$course->id] = array();
1911 $return = array();
1912 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1913 foreach($modnames as $modname => $modnamestr) {
1914 if (!course_allowed_module($course, $modname)) {
1915 continue;
1917 if (isset($modlist[$modname])) {
1918 // This module is already cached
1919 $return[$modname] = $modlist[$course->id][$modname];
1920 continue;
1923 // Include the module lib
1924 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1925 if (!file_exists($libfile)) {
1926 continue;
1928 include_once($libfile);
1930 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1931 $gettypesfunc = $modname.'_get_types';
1932 if (function_exists($gettypesfunc)) {
1933 if ($types = $gettypesfunc()) {
1934 $group = new stdClass();
1935 $group->name = $modname;
1936 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1937 foreach($types as $type) {
1938 if ($type->typestr === '--') {
1939 continue;
1941 if (strpos($type->typestr, '--') === 0) {
1942 $group->title = str_replace('--', '', $type->typestr);
1943 continue;
1945 // Set the Sub Type metadata
1946 $subtype = new stdClass();
1947 $subtype->title = $type->typestr;
1948 $subtype->type = str_replace('&amp;', '&', $type->type);
1949 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1950 $subtype->archetype = $type->modclass;
1952 // The group archetype should match the subtype archetypes and all subtypes
1953 // should have the same archetype
1954 $group->archetype = $subtype->archetype;
1956 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1957 $subtype->help = get_string('help' . $subtype->name, $modname);
1959 $subtype->link = $urlbase . $subtype->type;
1960 $group->types[] = $subtype;
1962 $modlist[$course->id][$modname] = $group;
1964 } else {
1965 $module = new stdClass();
1966 $module->title = get_string('modulename', $modname);
1967 $module->name = $modname;
1968 $module->link = $urlbase . $modname;
1969 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1970 $sm = get_string_manager();
1971 if ($sm->string_exists('modulename_help', $modname)) {
1972 $module->help = get_string('modulename_help', $modname);
1973 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1974 $link = get_string('modulename_link', $modname);
1975 $linktext = get_string('morehelp');
1976 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext), array('class' => 'helpdoclink'));
1979 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1980 $modlist[$course->id][$modname] = $module;
1982 $return[$modname] = $modlist[$course->id][$modname];
1985 return $return;
1989 * Return the course category context for the category with id $categoryid, except
1990 * that if $categoryid is 0, return the system context.
1992 * @param integer $categoryid a category id or 0.
1993 * @return object the corresponding context
1995 function get_category_or_system_context($categoryid) {
1996 if ($categoryid) {
1997 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1998 } else {
1999 return context_system::instance();
2004 * Gets the child categories of a given courses category. Uses a static cache
2005 * to make repeat calls efficient.
2007 * @param int $parentid the id of a course category.
2008 * @return array all the child course categories.
2010 function get_child_categories($parentid) {
2011 static $allcategories = null;
2013 // only fill in this variable the first time
2014 if (null == $allcategories) {
2015 $allcategories = array();
2017 $categories = get_categories();
2018 foreach ($categories as $category) {
2019 if (empty($allcategories[$category->parent])) {
2020 $allcategories[$category->parent] = array();
2022 $allcategories[$category->parent][] = $category;
2026 if (empty($allcategories[$parentid])) {
2027 return array();
2028 } else {
2029 return $allcategories[$parentid];
2034 * This function recursively travels the categories, building up a nice list
2035 * for display. It also makes an array that list all the parents for each
2036 * category.
2038 * For example, if you have a tree of categories like:
2039 * Miscellaneous (id = 1)
2040 * Subcategory (id = 2)
2041 * Sub-subcategory (id = 4)
2042 * Other category (id = 3)
2043 * Then after calling this function you will have
2044 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2045 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2046 * 3 => 'Other category');
2047 * $parents = array(2 => array(1), 4 => array(1, 2));
2049 * If you specify $requiredcapability, then only categories where the current
2050 * user has that capability will be added to $list, although all categories
2051 * will still be added to $parents, and if you only have $requiredcapability
2052 * in a child category, not the parent, then the child catgegory will still be
2053 * included.
2055 * If you specify the option $excluded, then that category, and all its children,
2056 * are omitted from the tree. This is useful when you are doing something like
2057 * moving categories, where you do not want to allow people to move a category
2058 * to be the child of itself.
2060 * @param array $list For output, accumulates an array categoryid => full category path name
2061 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2062 * @param string/array $requiredcapability if given, only categories where the current
2063 * user has this capability will be added to $list. Can also be an array of capabilities,
2064 * in which case they are all required.
2065 * @param integer $excludeid Omit this category and its children from the lists built.
2066 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2067 * @param string $path For internal use, as part of recursive calls.
2069 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2070 $excludeid = 0, $category = NULL, $path = "") {
2072 // initialize the arrays if needed
2073 if (!is_array($list)) {
2074 $list = array();
2076 if (!is_array($parents)) {
2077 $parents = array();
2080 if (empty($category)) {
2081 // Start at the top level.
2082 $category = new stdClass;
2083 $category->id = 0;
2084 } else {
2085 // This is the excluded category, don't include it.
2086 if ($excludeid > 0 && $excludeid == $category->id) {
2087 return;
2090 $context = context_coursecat::instance($category->id);
2091 $categoryname = format_string($category->name, true, array('context' => $context));
2093 // Update $path.
2094 if ($path) {
2095 $path = $path.' / '.$categoryname;
2096 } else {
2097 $path = $categoryname;
2100 // Add this category to $list, if the permissions check out.
2101 if (empty($requiredcapability)) {
2102 $list[$category->id] = $path;
2104 } else {
2105 $requiredcapability = (array)$requiredcapability;
2106 if (has_all_capabilities($requiredcapability, $context)) {
2107 $list[$category->id] = $path;
2112 // Add all the children recursively, while updating the parents array.
2113 if ($categories = get_child_categories($category->id)) {
2114 foreach ($categories as $cat) {
2115 if (!empty($category->id)) {
2116 if (isset($parents[$category->id])) {
2117 $parents[$cat->id] = $parents[$category->id];
2119 $parents[$cat->id][] = $category->id;
2121 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2127 * This function generates a structured array of courses and categories.
2129 * The depth of categories is limited by $CFG->maxcategorydepth however there
2130 * is no limit on the number of courses!
2132 * Suitable for use with the course renderers course_category_tree method:
2133 * $renderer = $PAGE->get_renderer('core','course');
2134 * echo $renderer->course_category_tree(get_course_category_tree());
2136 * @global moodle_database $DB
2137 * @param int $id
2138 * @param int $depth
2140 function get_course_category_tree($id = 0, $depth = 0) {
2141 global $DB, $CFG;
2142 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2143 $categories = get_child_categories($id);
2144 $categoryids = array();
2145 foreach ($categories as $key => &$category) {
2146 if (!$category->visible && !$viewhiddencats) {
2147 unset($categories[$key]);
2148 continue;
2150 $categoryids[$category->id] = $category;
2151 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2152 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2153 foreach ($subcategories as $subid=>$subcat) {
2154 $categoryids[$subid] = $subcat;
2156 $category->courses = array();
2160 if ($depth > 0) {
2161 // This is a recursive call so return the required array
2162 return array($categories, $categoryids);
2165 if (empty($categoryids)) {
2166 // No categories available (probably all hidden).
2167 return array();
2170 // The depth is 0 this function has just been called so we can finish it off
2172 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2173 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2174 $sql = "SELECT
2175 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2176 $ccselect
2177 FROM {course} c
2178 $ccjoin
2179 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2180 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2181 // loop throught them
2182 foreach ($courses as $course) {
2183 if ($course->id == SITEID) {
2184 continue;
2186 context_instance_preload($course);
2187 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2188 $categoryids[$course->category]->courses[$course->id] = $course;
2192 return $categories;
2196 * Recursive function to print out all the categories in a nice format
2197 * with or without courses included
2199 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2200 global $CFG;
2202 // maxcategorydepth == 0 meant no limit
2203 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2204 return;
2207 if (!$displaylist) {
2208 make_categories_list($displaylist, $parentslist);
2211 if ($category) {
2212 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2213 print_category_info($category, $depth, $showcourses);
2214 } else {
2215 return; // Don't bother printing children of invisible categories
2218 } else {
2219 $category = new stdClass();
2220 $category->id = "0";
2223 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2224 $countcats = count($categories);
2225 $count = 0;
2226 $first = true;
2227 $last = false;
2228 foreach ($categories as $cat) {
2229 $count++;
2230 if ($count == $countcats) {
2231 $last = true;
2233 $up = $first ? false : true;
2234 $down = $last ? false : true;
2235 $first = false;
2237 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2243 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2245 function make_categories_options() {
2246 make_categories_list($cats,$parents);
2247 foreach ($cats as $key => $value) {
2248 if (array_key_exists($key,$parents)) {
2249 if ($indent = count($parents[$key])) {
2250 for ($i = 0; $i < $indent; $i++) {
2251 $cats[$key] = '&nbsp;'.$cats[$key];
2256 return $cats;
2260 * Prints the category info in indented fashion
2261 * This function is only used by print_whole_category_list() above
2263 function print_category_info($category, $depth=0, $showcourses = false) {
2264 global $CFG, $DB, $OUTPUT;
2266 $strsummary = get_string('summary');
2268 $catlinkcss = null;
2269 if (!$category->visible) {
2270 $catlinkcss = array('class'=>'dimmed');
2272 static $coursecount = null;
2273 if (null === $coursecount) {
2274 // only need to check this once
2275 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2278 if ($showcourses and $coursecount) {
2279 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2280 } else {
2281 $catimage = "&nbsp;";
2284 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2285 $context = context_coursecat::instance($category->id);
2286 $fullname = format_string($category->name, true, array('context' => $context));
2288 if ($showcourses and $coursecount) {
2289 echo '<div class="categorylist clearfix">';
2290 $cat = '';
2291 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2292 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2293 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2295 $html = '';
2296 if ($depth > 0) {
2297 for ($i=0; $i< $depth; $i++) {
2298 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2299 $cat = '';
2301 } else {
2302 $html = $cat;
2304 echo html_writer::tag('div', $html, array('class'=>'category'));
2305 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2307 // does the depth exceed maxcategorydepth
2308 // maxcategorydepth == 0 or unset meant no limit
2309 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2310 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2311 foreach ($courses as $course) {
2312 $linkcss = null;
2313 if (!$course->visible) {
2314 $linkcss = array('class'=>'dimmed');
2317 $coursename = get_course_display_name_for_list($course);
2318 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2320 // print enrol info
2321 $courseicon = '';
2322 if ($icons = enrol_get_course_info_icons($course)) {
2323 foreach ($icons as $pix_icon) {
2324 $courseicon = $OUTPUT->render($pix_icon).' ';
2328 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2330 if ($course->summary) {
2331 $link = new moodle_url('/course/info.php?id='.$course->id);
2332 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2333 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2334 array('title'=>$strsummary));
2336 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2339 $html = '';
2340 for ($i=0; $i <= $depth; $i++) {
2341 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2342 $coursecontent = '';
2344 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2347 echo '</div>';
2348 } else {
2349 echo '<div class="categorylist">';
2350 $html = '';
2351 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2352 if (count($courses) > 0) {
2353 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2356 if ($depth > 0) {
2357 for ($i=0; $i< $depth; $i++) {
2358 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2359 $cat = '';
2361 } else {
2362 $html = $cat;
2365 echo html_writer::tag('div', $html, array('class'=>'category'));
2366 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2367 echo '</div>';
2372 * Print the buttons relating to course requests.
2374 * @param object $systemcontext the system context.
2376 function print_course_request_buttons($systemcontext) {
2377 global $CFG, $DB, $OUTPUT;
2378 if (empty($CFG->enablecourserequests)) {
2379 return;
2381 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2382 /// Print a button to request a new course
2383 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2385 /// Print a button to manage pending requests
2386 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2387 $disabled = !$DB->record_exists('course_request', array());
2388 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2393 * Does the user have permission to edit things in this category?
2395 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2396 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2398 function can_edit_in_category($categoryid = 0) {
2399 $context = get_category_or_system_context($categoryid);
2400 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2404 * Prints the turn editing on/off button on course/index.php or course/category.php.
2406 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2407 * @return string HTML of the editing button, or empty string, if this user is not allowed
2408 * to see it.
2410 function update_category_button($categoryid = 0) {
2411 global $CFG, $PAGE, $OUTPUT;
2413 // Check permissions.
2414 if (!can_edit_in_category($categoryid)) {
2415 return '';
2418 // Work out the appropriate action.
2419 if ($PAGE->user_is_editing()) {
2420 $label = get_string('turneditingoff');
2421 $edit = 'off';
2422 } else {
2423 $label = get_string('turneditingon');
2424 $edit = 'on';
2427 // Generate the button HTML.
2428 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2429 if ($categoryid) {
2430 $options['id'] = $categoryid;
2431 $page = 'category.php';
2432 } else {
2433 $page = 'index.php';
2435 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2439 * Category is 0 (for all courses) or an object
2441 function print_courses($category) {
2442 global $CFG, $OUTPUT;
2444 if (!is_object($category) && $category==0) {
2445 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2446 if (is_array($categories) && count($categories) == 1) {
2447 $category = array_shift($categories);
2448 $courses = get_courses_wmanagers($category->id,
2449 'c.sortorder ASC',
2450 array('summary','summaryformat'));
2451 } else {
2452 $courses = get_courses_wmanagers('all',
2453 'c.sortorder ASC',
2454 array('summary','summaryformat'));
2456 unset($categories);
2457 } else {
2458 $courses = get_courses_wmanagers($category->id,
2459 'c.sortorder ASC',
2460 array('summary','summaryformat'));
2463 if ($courses) {
2464 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2465 foreach ($courses as $course) {
2466 $coursecontext = context_course::instance($course->id);
2467 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2468 echo html_writer::start_tag('li');
2469 print_course($course);
2470 echo html_writer::end_tag('li');
2473 echo html_writer::end_tag('ul');
2474 } else {
2475 echo $OUTPUT->heading(get_string("nocoursesyet"));
2476 $context = context_system::instance();
2477 if (has_capability('moodle/course:create', $context)) {
2478 $options = array();
2479 if (!empty($category->id)) {
2480 $options['category'] = $category->id;
2481 } else {
2482 $options['category'] = $CFG->defaultrequestcategory;
2484 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2485 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2486 echo html_writer::end_tag('div');
2492 * Print a description of a course, suitable for browsing in a list.
2494 * @param object $course the course object.
2495 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2497 function print_course($course, $highlightterms = '') {
2498 global $CFG, $USER, $DB, $OUTPUT;
2500 $context = context_course::instance($course->id);
2502 // Rewrite file URLs so that they are correct
2503 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2505 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2506 echo html_writer::start_tag('div', array('class'=>'info'));
2507 echo html_writer::start_tag('h3', array('class'=>'name'));
2509 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2511 $coursename = get_course_display_name_for_list($course);
2512 $linktext = highlight($highlightterms, format_string($coursename));
2513 $linkparams = array('title'=>get_string('entercourse'));
2514 if (empty($course->visible)) {
2515 $linkparams['class'] = 'dimmed';
2517 echo html_writer::link($linkhref, $linktext, $linkparams);
2518 echo html_writer::end_tag('h3');
2520 /// first find all roles that are supposed to be displayed
2521 if (!empty($CFG->coursecontact)) {
2522 $managerroles = explode(',', $CFG->coursecontact);
2523 $rusers = array();
2525 if (!isset($course->managers)) {
2526 $rusers = get_role_users($managerroles, $context, true,
2527 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2528 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2529 'r.sortorder ASC, u.lastname ASC');
2530 } else {
2531 // use the managers array if we have it for perf reasosn
2532 // populate the datastructure like output of get_role_users();
2533 foreach ($course->managers as $manager) {
2534 $user = clone($manager->user);
2535 $user->roleid = $manager->roleid;
2536 $user->rolename = $manager->rolename;
2537 $user->roleshortname = $manager->roleshortname;
2538 $user->rolecoursealias = $manager->rolecoursealias;
2539 $rusers[$user->id] = $user;
2543 $namesarray = array();
2544 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2545 foreach ($rusers as $ra) {
2546 if (isset($namesarray[$ra->id])) {
2547 // only display a user once with the higest sortorder role
2548 continue;
2551 $role = new stdClass();
2552 $role->id = $ra->roleid;
2553 $role->name = $ra->rolename;
2554 $role->shortname = $ra->roleshortname;
2555 $role->coursealias = $ra->rolecoursealias;
2556 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2558 $fullname = fullname($ra, $canviewfullnames);
2559 $namesarray[$ra->id] = $rolename.': '.
2560 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2563 if (!empty($namesarray)) {
2564 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2565 foreach ($namesarray as $name) {
2566 echo html_writer::tag('li', $name);
2568 echo html_writer::end_tag('ul');
2571 echo html_writer::end_tag('div'); // End of info div
2573 echo html_writer::start_tag('div', array('class'=>'summary'));
2574 $options = new stdClass();
2575 $options->noclean = true;
2576 $options->para = false;
2577 $options->overflowdiv = true;
2578 if (!isset($course->summaryformat)) {
2579 $course->summaryformat = FORMAT_MOODLE;
2581 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2582 if ($icons = enrol_get_course_info_icons($course)) {
2583 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2584 foreach ($icons as $icon) {
2585 echo $OUTPUT->render($icon);
2587 echo html_writer::end_tag('div'); // End of enrolmenticons div
2589 echo html_writer::end_tag('div'); // End of summary div
2590 echo html_writer::end_tag('div'); // End of coursebox div
2594 * Prints custom user information on the home page.
2595 * Over time this can include all sorts of information
2597 function print_my_moodle() {
2598 global $USER, $CFG, $DB, $OUTPUT;
2600 if (!isloggedin() or isguestuser()) {
2601 print_error('nopermissions', '', '', 'See My Moodle');
2604 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2605 $rhosts = array();
2606 $rcourses = array();
2607 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2608 $rcourses = get_my_remotecourses($USER->id);
2609 $rhosts = get_my_remotehosts();
2612 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2614 if (!empty($courses)) {
2615 echo '<ul class="unlist">';
2616 foreach ($courses as $course) {
2617 if ($course->id == SITEID) {
2618 continue;
2620 echo '<li>';
2621 print_course($course);
2622 echo "</li>\n";
2624 echo "</ul>\n";
2627 // MNET
2628 if (!empty($rcourses)) {
2629 // at the IDP, we know of all the remote courses
2630 foreach ($rcourses as $course) {
2631 print_remote_course($course, "100%");
2633 } elseif (!empty($rhosts)) {
2634 // non-IDP, we know of all the remote servers, but not courses
2635 foreach ($rhosts as $host) {
2636 print_remote_host($host, "100%");
2639 unset($course);
2640 unset($host);
2642 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2643 echo "<table width=\"100%\"><tr><td align=\"center\">";
2644 print_course_search("", false, "short");
2645 echo "</td><td align=\"center\">";
2646 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2647 echo "</td></tr></table>\n";
2650 } else {
2651 if ($DB->count_records("course_categories") > 1) {
2652 echo $OUTPUT->box_start("categorybox");
2653 print_whole_category_list();
2654 echo $OUTPUT->box_end();
2655 } else {
2656 print_courses(0);
2662 function print_course_search($value="", $return=false, $format="plain") {
2663 global $CFG;
2664 static $count = 0;
2666 $count++;
2668 $id = 'coursesearch';
2670 if ($count > 1) {
2671 $id .= $count;
2674 $strsearchcourses= get_string("searchcourses");
2676 if ($format == 'plain') {
2677 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2678 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2679 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2680 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2681 $output .= '<input type="submit" value="'.get_string('go').'" />';
2682 $output .= '</fieldset></form>';
2683 } else if ($format == 'short') {
2684 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2685 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2686 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2687 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2688 $output .= '<input type="submit" value="'.get_string('go').'" />';
2689 $output .= '</fieldset></form>';
2690 } else if ($format == 'navbar') {
2691 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2692 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2693 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2694 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2695 $output .= '<input type="submit" value="'.get_string('go').'" />';
2696 $output .= '</fieldset></form>';
2699 if ($return) {
2700 return $output;
2702 echo $output;
2705 function print_remote_course($course, $width="100%") {
2706 global $CFG, $USER;
2708 $linkcss = '';
2710 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2712 echo '<div class="coursebox remotecoursebox clearfix">';
2713 echo '<div class="info">';
2714 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2715 $linkcss.' href="'.$url.'">'
2716 . format_string($course->fullname) .'</a><br />'
2717 . format_string($course->hostname) . ' : '
2718 . format_string($course->cat_name) . ' : '
2719 . format_string($course->shortname). '</div>';
2720 echo '</div><div class="summary">';
2721 $options = new stdClass();
2722 $options->noclean = true;
2723 $options->para = false;
2724 $options->overflowdiv = true;
2725 echo format_text($course->summary, $course->summaryformat, $options);
2726 echo '</div>';
2727 echo '</div>';
2730 function print_remote_host($host, $width="100%") {
2731 global $OUTPUT;
2733 $linkcss = '';
2735 echo '<div class="coursebox clearfix">';
2736 echo '<div class="info">';
2737 echo '<div class="name">';
2738 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2739 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2740 . s($host['name']).'</a> - ';
2741 echo $host['count'] . ' ' . get_string('courses');
2742 echo '</div>';
2743 echo '</div>';
2744 echo '</div>';
2748 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2750 function add_course_module($mod) {
2751 global $DB;
2753 $mod->added = time();
2754 unset($mod->id);
2756 return $DB->insert_record("course_modules", $mod);
2760 * Returns course section - creates new if does not exist yet.
2761 * @param int $relative section number
2762 * @param int $courseid
2763 * @return object $course_section object
2765 function get_course_section($section, $courseid) {
2766 global $DB;
2768 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2769 return $cw;
2771 $cw = new stdClass();
2772 $cw->course = $courseid;
2773 $cw->section = $section;
2774 $cw->summary = "";
2775 $cw->summaryformat = FORMAT_HTML;
2776 $cw->sequence = "";
2777 $id = $DB->insert_record("course_sections", $cw);
2778 rebuild_course_cache($courseid, true);
2779 return $DB->get_record("course_sections", array("id"=>$id));
2783 * Given a full mod object with section and course already defined, adds this module to that section.
2785 * @param object $mod
2786 * @param int $beforemod An existing ID which we will insert the new module before
2787 * @return int The course_sections ID where the mod is inserted
2789 function add_mod_to_section($mod, $beforemod=NULL) {
2790 global $DB;
2792 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2794 $section->sequence = trim($section->sequence);
2796 if (empty($section->sequence)) {
2797 $newsequence = "$mod->coursemodule";
2799 } else if ($beforemod) {
2800 $modarray = explode(",", $section->sequence);
2802 if ($key = array_keys($modarray, $beforemod->id)) {
2803 $insertarray = array($mod->id, $beforemod->id);
2804 array_splice($modarray, $key[0], 1, $insertarray);
2805 $newsequence = implode(",", $modarray);
2807 } else { // Just tack it on the end anyway
2808 $newsequence = "$section->sequence,$mod->coursemodule";
2811 } else {
2812 $newsequence = "$section->sequence,$mod->coursemodule";
2815 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2816 return $section->id; // Return course_sections ID that was used.
2818 } else { // Insert a new record
2819 $section = new stdClass();
2820 $section->course = $mod->course;
2821 $section->section = $mod->section;
2822 $section->summary = "";
2823 $section->summaryformat = FORMAT_HTML;
2824 $section->sequence = $mod->coursemodule;
2825 return $DB->insert_record("course_sections", $section);
2829 function set_coursemodule_groupmode($id, $groupmode) {
2830 global $DB;
2831 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2834 function set_coursemodule_idnumber($id, $idnumber) {
2835 global $DB;
2836 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2840 * $prevstateoverrides = true will set the visibility of the course module
2841 * to what is defined in visibleold. This enables us to remember the current
2842 * visibility when making a whole section hidden, so that when we toggle
2843 * that section back to visible, we are able to return the visibility of
2844 * the course module back to what it was originally.
2846 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2847 global $DB, $CFG;
2848 require_once($CFG->libdir.'/gradelib.php');
2850 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2851 return false;
2853 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2854 return false;
2856 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2857 foreach($events as $event) {
2858 if ($visible) {
2859 show_event($event);
2860 } else {
2861 hide_event($event);
2866 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2867 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2868 if ($grade_items) {
2869 foreach ($grade_items as $grade_item) {
2870 $grade_item->set_hidden(!$visible);
2874 if ($prevstateoverrides) {
2875 if ($visible == '0') {
2876 // Remember the current visible state so we can toggle this back.
2877 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2878 } else {
2879 // Get the previous saved visible states.
2880 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2883 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2887 * Delete a course module and any associated data at the course level (events)
2888 * Until 1.5 this function simply marked a deleted flag ... now it
2889 * deletes it completely.
2892 function delete_course_module($id) {
2893 global $CFG, $DB;
2894 require_once($CFG->libdir.'/gradelib.php');
2895 require_once($CFG->dirroot.'/blog/lib.php');
2897 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2898 return true;
2900 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2901 //delete events from calendar
2902 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2903 foreach($events as $event) {
2904 delete_event($event->id);
2907 //delete grade items, outcome items and grades attached to modules
2908 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2909 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2910 foreach ($grade_items as $grade_item) {
2911 $grade_item->delete('moddelete');
2914 // Delete completion and availability data; it is better to do this even if the
2915 // features are not turned on, in case they were turned on previously (these will be
2916 // very quick on an empty table)
2917 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2918 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2919 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2920 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2921 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2923 delete_context(CONTEXT_MODULE, $cm->id);
2924 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2927 function delete_mod_from_section($mod, $section) {
2928 global $DB;
2930 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2932 $modarray = explode(",", $section->sequence);
2934 if ($key = array_keys ($modarray, $mod)) {
2935 array_splice($modarray, $key[0], 1);
2936 $newsequence = implode(",", $modarray);
2937 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2938 } else {
2939 return false;
2943 return false;
2947 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2949 * @param object $course course object
2950 * @param int $section Section number (not id!!!)
2951 * @param int $move (-1 or 1)
2952 * @return boolean true if section moved successfully
2953 * @todo MDL-33379 remove this function in 2.5
2955 function move_section($course, $section, $move) {
2956 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2958 /// Moves a whole course section up and down within the course
2959 global $USER, $DB;
2961 if (!$move) {
2962 return true;
2965 $sectiondest = $section + $move;
2967 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2968 return false;
2971 $retval = move_section_to($course, $section, $sectiondest);
2972 // If section moved, then rebuild course cache.
2973 if ($retval) {
2974 rebuild_course_cache($course->id, true);
2976 return $retval;
2980 * Moves a section within a course, from a position to another.
2981 * Be very careful: $section and $destination refer to section number,
2982 * not id!.
2984 * @param object $course
2985 * @param int $section Section number (not id!!!)
2986 * @param int $destination
2987 * @return boolean Result
2989 function move_section_to($course, $section, $destination) {
2990 /// Moves a whole course section up and down within the course
2991 global $USER, $DB;
2993 if (!$destination && $destination != 0) {
2994 return true;
2997 if (($destination > $course->numsections) || ($destination < 1)) {
2998 return false;
3001 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3002 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3003 'section ASC, id ASC', 'id, section')) {
3004 return false;
3007 $movedsections = reorder_sections($sections, $section, $destination);
3009 // Update all sections. Do this in 2 steps to avoid breaking database
3010 // uniqueness constraint
3011 $transaction = $DB->start_delegated_transaction();
3012 foreach ($movedsections as $id => $position) {
3013 if ($sections[$id] !== $position) {
3014 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3017 foreach ($movedsections as $id => $position) {
3018 if ($sections[$id] !== $position) {
3019 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3023 // If we move the highlighted section itself, then just highlight the destination.
3024 // Adjust the higlighted section location if we move something over it either direction.
3025 if ($section == $course->marker) {
3026 course_set_marker($course->id, $destination);
3027 } elseif ($section > $course->marker && $course->marker >= $destination) {
3028 course_set_marker($course->id, $course->marker+1);
3029 } elseif ($section < $course->marker && $course->marker <= $destination) {
3030 course_set_marker($course->id, $course->marker-1);
3033 $transaction->allow_commit();
3034 return true;
3038 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3039 * an original position number and a target position number, rebuilds the array so that the
3040 * move is made without any duplication of section positions.
3041 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3042 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3044 * @param array $sections
3045 * @param int $origin_position
3046 * @param int $target_position
3047 * @return array
3049 function reorder_sections($sections, $origin_position, $target_position) {
3050 if (!is_array($sections)) {
3051 return false;
3054 // We can't move section position 0
3055 if ($origin_position < 1) {
3056 echo "We can't move section position 0";
3057 return false;
3060 // Locate origin section in sections array
3061 if (!$origin_key = array_search($origin_position, $sections)) {
3062 echo "searched position not in sections array";
3063 return false; // searched position not in sections array
3066 // Extract origin section
3067 $origin_section = $sections[$origin_key];
3068 unset($sections[$origin_key]);
3070 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3071 $found = false;
3072 $append_array = array();
3073 foreach ($sections as $id => $position) {
3074 if ($found) {
3075 $append_array[$id] = $position;
3076 unset($sections[$id]);
3078 if ($position == $target_position) {
3079 if ($target_position < $origin_position) {
3080 $append_array[$id] = $position;
3081 unset($sections[$id]);
3083 $found = true;
3087 // Append moved section
3088 $sections[$origin_key] = $origin_section;
3090 // Append rest of array (if applicable)
3091 if (!empty($append_array)) {
3092 foreach ($append_array as $id => $position) {
3093 $sections[$id] = $position;
3097 // Renumber positions
3098 $position = 0;
3099 foreach ($sections as $id => $p) {
3100 $sections[$id] = $position;
3101 $position++;
3104 return $sections;
3109 * Move the module object $mod to the specified $section
3110 * If $beforemod exists then that is the module
3111 * before which $modid should be inserted
3112 * All parameters are objects
3114 function moveto_module($mod, $section, $beforemod=NULL) {
3115 global $DB, $OUTPUT;
3117 /// Remove original module from original section
3118 if (! delete_mod_from_section($mod->id, $mod->section)) {
3119 echo $OUTPUT->notification("Could not delete module from existing section");
3122 /// Update module itself if necessary
3124 if ($mod->section != $section->id) {
3125 $mod->section = $section->id;
3126 $DB->update_record("course_modules", $mod);
3127 // if moving to a hidden section then hide module
3128 if (!$section->visible) {
3129 set_coursemodule_visible($mod->id, 0);
3133 /// Add the module into the new section
3135 $mod->course = $section->course;
3136 $mod->section = $section->section; // need relative reference
3137 $mod->coursemodule = $mod->id;
3139 if (! add_mod_to_section($mod, $beforemod)) {
3140 return false;
3143 return true;
3147 * Produces the editing buttons for a module
3149 * @global core_renderer $OUTPUT
3150 * @staticvar type $str
3151 * @param stdClass $mod The module to produce editing buttons for
3152 * @param bool $absolute_ignored ignored - all links are absolute
3153 * @param bool $moveselect If true a move seleciton process is used (default true)
3154 * @param int $indent The current indenting
3155 * @param int $section The section to link back to
3156 * @return string XHTML for the editing buttons
3158 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3159 global $CFG, $OUTPUT, $COURSE;
3161 static $str;
3163 $coursecontext = context_course::instance($mod->course);
3164 $modcontext = context_module::instance($mod->id);
3166 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3167 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3169 // no permission to edit anything
3170 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3171 return false;
3174 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3176 if (!isset($str)) {
3177 $str = new stdClass;
3178 $str->assign = get_string("assignroles", 'role');
3179 $str->delete = get_string("delete");
3180 $str->move = get_string("move");
3181 $str->moveup = get_string("moveup");
3182 $str->movedown = get_string("movedown");
3183 $str->moveright = get_string("moveright");
3184 $str->moveleft = get_string("moveleft");
3185 $str->update = get_string("update");
3186 $str->duplicate = get_string("duplicate");
3187 $str->hide = get_string("hide");
3188 $str->show = get_string("show");
3189 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3190 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3191 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3192 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3193 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3194 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3195 $str->edittitle = get_string('edittitle', 'moodle');
3198 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3200 if ($section >= 0) {
3201 $baseurl->param('sr', $section);
3203 $actions = array();
3205 // AJAX edit title
3206 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3207 $actions[] = new action_link(
3208 new moodle_url($baseurl, array('update' => $mod->id)),
3209 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs')),
3210 null,
3211 array('class' => 'editing_title', 'title' => $str->edittitle)
3215 // leftright
3216 if ($hasmanageactivities) {
3217 if (right_to_left()) { // Exchange arrows on RTL
3218 $rightarrow = 't/left';
3219 $leftarrow = 't/right';
3220 } else {
3221 $rightarrow = 't/right';
3222 $leftarrow = 't/left';
3225 if ($indent > 0) {
3226 $actions[] = new action_link(
3227 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3228 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3229 null,
3230 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3233 if ($indent >= 0) {
3234 $actions[] = new action_link(
3235 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3236 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3237 null,
3238 array('class' => 'editing_moveright', 'title' => $str->moveright)
3243 // move
3244 if ($hasmanageactivities) {
3245 if ($moveselect) {
3246 $actions[] = new action_link(
3247 new moodle_url($baseurl, array('copy' => $mod->id)),
3248 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3249 null,
3250 array('class' => 'editing_move', 'title' => $str->move)
3252 } else {
3253 $actions[] = new action_link(
3254 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3255 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3256 null,
3257 array('class' => 'editing_moveup', 'title' => $str->moveup)
3259 $actions[] = new action_link(
3260 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3261 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3262 null,
3263 array('class' => 'editing_movedown', 'title' => $str->movedown)
3268 // Update
3269 if ($hasmanageactivities) {
3270 $actions[] = new action_link(
3271 new moodle_url($baseurl, array('update' => $mod->id)),
3272 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3273 null,
3274 array('class' => 'editing_update', 'title' => $str->update)
3278 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3279 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3280 $actions[] = new action_link(
3281 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3282 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3283 null,
3284 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3288 // Delete
3289 if ($hasmanageactivities) {
3290 $actions[] = new action_link(
3291 new moodle_url($baseurl, array('delete' => $mod->id)),
3292 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3293 null,
3294 array('class' => 'editing_delete', 'title' => $str->delete)
3298 // hideshow
3299 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3300 if ($mod->visible) {
3301 $actions[] = new action_link(
3302 new moodle_url($baseurl, array('hide' => $mod->id)),
3303 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3304 null,
3305 array('class' => 'editing_hide', 'title' => $str->hide)
3307 } else {
3308 $actions[] = new action_link(
3309 new moodle_url($baseurl, array('show' => $mod->id)),
3310 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3311 null,
3312 array('class' => 'editing_show', 'title' => $str->show)
3317 // groupmode
3318 if ($hasmanageactivities and $mod->groupmode !== false) {
3319 if ($mod->groupmode == SEPARATEGROUPS) {
3320 $groupmode = 0;
3321 $grouptitle = $str->groupsseparate;
3322 $forcedgrouptitle = $str->forcedgroupsseparate;
3323 $groupclass = 'editing_groupsseparate';
3324 $groupimage = 't/groups';
3325 } else if ($mod->groupmode == VISIBLEGROUPS) {
3326 $groupmode = 1;
3327 $grouptitle = $str->groupsvisible;
3328 $forcedgrouptitle = $str->forcedgroupsvisible;
3329 $groupclass = 'editing_groupsvisible';
3330 $groupimage = 't/groupv';
3331 } else {
3332 $groupmode = 2;
3333 $grouptitle = $str->groupsnone;
3334 $forcedgrouptitle = $str->forcedgroupsnone;
3335 $groupclass = 'editing_groupsnone';
3336 $groupimage = 't/groupn';
3338 if ($mod->groupmodelink) {
3339 $actions[] = new action_link(
3340 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3341 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3342 null,
3343 array('class' => $groupclass, 'title' => $grouptitle)
3345 } else {
3346 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3350 // Assign
3351 if (has_capability('moodle/role:assign', $modcontext)){
3352 $actions[] = new action_link(
3353 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3354 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3355 null,
3356 array('class' => 'editing_assign', 'title' => $str->assign)
3360 $output = html_writer::start_tag('span', array('class' => 'commands'));
3361 foreach ($actions as $action) {
3362 if ($action instanceof renderable) {
3363 $output .= $OUTPUT->render($action);
3364 } else {
3365 $output .= $action;
3368 $output .= html_writer::end_tag('span');
3369 return $output;
3373 * given a course object with shortname & fullname, this function will
3374 * truncate the the number of chars allowed and add ... if it was too long
3376 function course_format_name ($course,$max=100) {
3378 $context = context_course::instance($course->id);
3379 $shortname = format_string($course->shortname, true, array('context' => $context));
3380 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3381 $str = $shortname.': '. $fullname;
3382 if (textlib::strlen($str) <= $max) {
3383 return $str;
3385 else {
3386 return textlib::substr($str,0,$max-3).'...';
3391 * Is the user allowed to add this type of module to this course?
3392 * @param object $course the course settings. Only $course->id is used.
3393 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3394 * @return bool whether the current user is allowed to add this type of module to this course.
3396 function course_allowed_module($course, $modname) {
3397 global $DB;
3399 if (is_numeric($modname)) {
3400 throw new coding_exception('Function course_allowed_module no longer
3401 supports numeric module ids. Please update your code to pass the module name.');
3404 $capability = 'mod/' . $modname . ':addinstance';
3405 if (!get_capability_info($capability)) {
3406 // Debug warning that the capability does not exist, but no more than once per page.
3407 static $warned = array();
3408 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3409 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3410 debugging('The module ' . $modname . ' does not define the standard capability ' .
3411 $capability , DEBUG_DEVELOPER);
3412 $warned[$modname] = 1;
3415 // If the capability does not exist, the module can always be added.
3416 return true;
3419 $coursecontext = context_course::instance($course->id);
3420 return has_capability($capability, $coursecontext);
3424 * Recursively delete category including all subcategories and courses.
3425 * @param stdClass $category
3426 * @param boolean $showfeedback display some notices
3427 * @return array return deleted courses
3429 function category_delete_full($category, $showfeedback=true) {
3430 global $CFG, $DB;
3431 require_once($CFG->libdir.'/gradelib.php');
3432 require_once($CFG->libdir.'/questionlib.php');
3433 require_once($CFG->dirroot.'/cohort/lib.php');
3435 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3436 foreach ($children as $childcat) {
3437 category_delete_full($childcat, $showfeedback);
3441 $deletedcourses = array();
3442 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3443 foreach ($courses as $course) {
3444 if (!delete_course($course, false)) {
3445 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3447 $deletedcourses[] = $course;
3451 // move or delete cohorts in this context
3452 cohort_delete_category($category);
3454 // now delete anything that may depend on course category context
3455 grade_course_category_delete($category->id, 0, $showfeedback);
3456 if (!question_delete_course_category($category, 0, $showfeedback)) {
3457 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3460 // finally delete the category and it's context
3461 $DB->delete_records('course_categories', array('id'=>$category->id));
3462 delete_context(CONTEXT_COURSECAT, $category->id);
3464 events_trigger('course_category_deleted', $category);
3466 return $deletedcourses;
3470 * Delete category, but move contents to another category.
3471 * @param object $ccategory
3472 * @param int $newparentid category id
3473 * @return bool status
3475 function category_delete_move($category, $newparentid, $showfeedback=true) {
3476 global $CFG, $DB, $OUTPUT;
3477 require_once($CFG->libdir.'/gradelib.php');
3478 require_once($CFG->libdir.'/questionlib.php');
3479 require_once($CFG->dirroot.'/cohort/lib.php');
3481 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3482 return false;
3485 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3486 foreach ($children as $childcat) {
3487 move_category($childcat, $newparentcat);
3491 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3492 if (!move_courses(array_keys($courses), $newparentid)) {
3493 if ($showfeedback) {
3494 echo $OUTPUT->notification("Error moving courses");
3496 return false;
3498 if ($showfeedback) {
3499 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3503 // move or delete cohorts in this context
3504 cohort_delete_category($category);
3506 // now delete anything that may depend on course category context
3507 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3508 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3509 if ($showfeedback) {
3510 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3512 return false;
3515 // finally delete the category and it's context
3516 $DB->delete_records('course_categories', array('id'=>$category->id));
3517 delete_context(CONTEXT_COURSECAT, $category->id);
3519 events_trigger('course_category_deleted', $category);
3521 if ($showfeedback) {
3522 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3524 return true;
3528 * Efficiently moves many courses around while maintaining
3529 * sortorder in order.
3531 * @param array $courseids is an array of course ids
3532 * @param int $categoryid
3533 * @return bool success
3535 function move_courses($courseids, $categoryid) {
3536 global $CFG, $DB, $OUTPUT;
3538 if (empty($courseids)) {
3539 // nothing to do
3540 return;
3543 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3544 return false;
3547 $courseids = array_reverse($courseids);
3548 $newparent = context_coursecat::instance($category->id);
3549 $i = 1;
3551 foreach ($courseids as $courseid) {
3552 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3553 $course = new stdClass();
3554 $course->id = $courseid;
3555 $course->category = $category->id;
3556 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3557 if ($category->visible == 0) {
3558 // hide the course when moving into hidden category,
3559 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3560 $course->visible = 0;
3563 $DB->update_record('course', $course);
3565 $context = context_course::instance($course->id);
3566 context_moved($context, $newparent);
3569 fix_course_sortorder();
3571 return true;
3575 * Hide course category and child course and subcategories
3576 * @param stdClass $category
3577 * @return void
3579 function course_category_hide($category) {
3580 global $DB;
3582 $category->visible = 0;
3583 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3584 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3585 $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
3586 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3587 // get all child categories and hide too
3588 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3589 foreach ($subcats as $cat) {
3590 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3591 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3592 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3593 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3599 * Show course category and child course and subcategories
3600 * @param stdClass $category
3601 * @return void
3603 function course_category_show($category) {
3604 global $DB;
3606 $category->visible = 1;
3607 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3608 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3609 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3610 // get all child categories and unhide too
3611 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3612 foreach ($subcats as $cat) {
3613 if ($cat->visibleold) {
3614 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3616 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3622 * Efficiently moves a category - NOTE that this can have
3623 * a huge impact access-control-wise...
3625 function move_category($category, $newparentcat) {
3626 global $CFG, $DB;
3628 $context = context_coursecat::instance($category->id);
3630 $hidecat = false;
3631 if (empty($newparentcat->id)) {
3632 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3634 $newparent = context_system::instance();
3636 } else {
3637 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3638 $newparent = context_coursecat::instance($newparentcat->id);
3640 if (!$newparentcat->visible and $category->visible) {
3641 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3642 $hidecat = true;
3646 context_moved($context, $newparent);
3648 // now make it last in new category
3649 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3651 // and fix the sortorders
3652 fix_course_sortorder();
3654 if ($hidecat) {
3655 course_category_hide($category);
3660 * Returns the display name of the given section that the course prefers.
3662 * This function utilizes a callback that can be implemented within the course
3663 * formats lib.php file to customize the display name that is used to reference
3664 * the section.
3666 * By default (if callback is not defined) the method
3667 * {@see get_numeric_section_name} is called instead.
3669 * @param stdClass $course The course to get the section name for
3670 * @param stdClass $section Section object from database
3671 * @return Display name that the course format prefers, e.g. "Week 2"
3673 * @see get_generic_section_name
3675 function get_section_name(stdClass $course, stdClass $section) {
3676 global $CFG;
3678 /// Inelegant hack for bug 3408
3679 if ($course->format == 'site') {
3680 return get_string('site');
3683 // Use course formatter callback if it exists
3684 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3685 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3686 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3687 require_once $namingfile;
3689 if (function_exists($namingfunction)) {
3690 return $namingfunction($course, $section);
3693 // else, default behavior:
3694 return get_generic_section_name($course->format, $section);
3698 * Gets the generic section name for a courses section.
3700 * @param string $format Course format ID e.g. 'weeks' $course->format
3701 * @param stdClass $section Section object from database
3702 * @return Display name that the course format prefers, e.g. "Week 2"
3704 function get_generic_section_name($format, stdClass $section) {
3705 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3709 function course_format_uses_sections($format) {
3710 global $CFG;
3712 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3713 $featurefunction = 'callback_'.$format.'_uses_sections';
3714 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3715 require_once $featurefile;
3717 if (function_exists($featurefunction)) {
3718 return $featurefunction();
3721 return false;
3725 * Returns the information about the ajax support in the given source format
3727 * The returned object's property (boolean)capable indicates that
3728 * the course format supports Moodle course ajax features.
3729 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3731 * @param string $format
3732 * @return stdClass
3734 function course_format_ajax_support($format) {
3735 global $CFG;
3737 // set up default values
3738 $ajaxsupport = new stdClass();
3739 $ajaxsupport->capable = false;
3740 $ajaxsupport->testedbrowsers = array();
3742 // get the information from the course format library
3743 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3744 $featurefunction = 'callback_'.$format.'_ajax_support';
3745 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3746 require_once $featurefile;
3748 if (function_exists($featurefunction)) {
3749 $formatsupport = $featurefunction();
3750 if (isset($formatsupport->capable)) {
3751 $ajaxsupport->capable = $formatsupport->capable;
3753 if (is_array($formatsupport->testedbrowsers)) {
3754 $ajaxsupport->testedbrowsers = $formatsupport->testedbrowsers;
3758 return $ajaxsupport;
3762 * Can the current user delete this course?
3763 * Course creators have exception,
3764 * 1 day after the creation they can sill delete the course.
3765 * @param int $courseid
3766 * @return boolean
3768 function can_delete_course($courseid) {
3769 global $USER, $DB;
3771 $context = context_course::instance($courseid);
3773 if (has_capability('moodle/course:delete', $context)) {
3774 return true;
3777 // hack: now try to find out if creator created this course recently (1 day)
3778 if (!has_capability('moodle/course:create', $context)) {
3779 return false;
3782 $since = time() - 60*60*24;
3784 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3785 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3787 return $DB->record_exists_select('log', $select, $params);
3791 * Save the Your name for 'Some role' strings.
3793 * @param integer $courseid the id of this course.
3794 * @param array $data the data that came from the course settings form.
3796 function save_local_role_names($courseid, $data) {
3797 global $DB;
3798 $context = context_course::instance($courseid);
3800 foreach ($data as $fieldname => $value) {
3801 if (strpos($fieldname, 'role_') !== 0) {
3802 continue;
3804 list($ignored, $roleid) = explode('_', $fieldname);
3806 // make up our mind whether we want to delete, update or insert
3807 if (!$value) {
3808 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3810 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3811 $rolename->name = $value;
3812 $DB->update_record('role_names', $rolename);
3814 } else {
3815 $rolename = new stdClass;
3816 $rolename->contextid = $context->id;
3817 $rolename->roleid = $roleid;
3818 $rolename->name = $value;
3819 $DB->insert_record('role_names', $rolename);
3825 * Create a course and either return a $course object
3827 * Please note this functions does not verify any access control,
3828 * the calling code is responsible for all validation (usually it is the form definition).
3830 * @param array $editoroptions course description editor options
3831 * @param object $data - all the data needed for an entry in the 'course' table
3832 * @return object new course instance
3834 function create_course($data, $editoroptions = NULL) {
3835 global $CFG, $DB;
3837 //check the categoryid - must be given for all new courses
3838 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3840 //check if the shortname already exist
3841 if (!empty($data->shortname)) {
3842 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3843 throw new moodle_exception('shortnametaken');
3847 //check if the id number already exist
3848 if (!empty($data->idnumber)) {
3849 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3850 throw new moodle_exception('idnumbertaken');
3854 $data->timecreated = time();
3855 $data->timemodified = $data->timecreated;
3857 // place at beginning of any category
3858 $data->sortorder = 0;
3860 if ($editoroptions) {
3861 // summary text is updated later, we need context to store the files first
3862 $data->summary = '';
3863 $data->summary_format = FORMAT_HTML;
3866 if (!isset($data->visible)) {
3867 // data not from form, add missing visibility info
3868 $data->visible = $category->visible;
3870 $data->visibleold = $data->visible;
3872 $newcourseid = $DB->insert_record('course', $data);
3873 $context = context_course::instance($newcourseid, MUST_EXIST);
3875 if ($editoroptions) {
3876 // Save the files used in the summary editor and store
3877 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3878 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3879 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3882 $course = $DB->get_record('course', array('id'=>$newcourseid));
3884 // Setup the blocks
3885 blocks_add_default_course_blocks($course);
3887 $section = new stdClass();
3888 $section->course = $course->id; // Create a default section.
3889 $section->section = 0;
3890 $section->summaryformat = FORMAT_HTML;
3891 $DB->insert_record('course_sections', $section);
3893 fix_course_sortorder();
3895 // new context created - better mark it as dirty
3896 mark_context_dirty($context->path);
3898 // Save any custom role names.
3899 save_local_role_names($course->id, (array)$data);
3901 // set up enrolments
3902 enrol_course_updated(true, $course, $data);
3904 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3906 // Trigger events
3907 events_trigger('course_created', $course);
3909 return $course;
3913 * Create a new course category and marks the context as dirty
3915 * This function does not set the sortorder for the new category and
3916 * @see{fix_course_sortorder} should be called after creating a new course
3917 * category
3919 * Please note that this function does not verify access control.
3921 * @param object $category All of the data required for an entry in the course_categories table
3922 * @return object new course category
3924 function create_course_category($category) {
3925 global $DB;
3927 $category->timemodified = time();
3928 $category->id = $DB->insert_record('course_categories', $category);
3929 $category = $DB->get_record('course_categories', array('id' => $category->id));
3931 // We should mark the context as dirty
3932 $category->context = context_coursecat::instance($category->id);
3933 $category->context->mark_dirty();
3935 return $category;
3939 * Update a course.
3941 * Please note this functions does not verify any access control,
3942 * the calling code is responsible for all validation (usually it is the form definition).
3944 * @param object $data - all the data needed for an entry in the 'course' table
3945 * @param array $editoroptions course description editor options
3946 * @return void
3948 function update_course($data, $editoroptions = NULL) {
3949 global $CFG, $DB;
3951 $data->timemodified = time();
3953 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
3954 $context = context_course::instance($oldcourse->id);
3956 if ($editoroptions) {
3957 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3960 if (!isset($data->category) or empty($data->category)) {
3961 // prevent nulls and 0 in category field
3962 unset($data->category);
3964 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3966 if (!isset($data->visible)) {
3967 // data not from form, add missing visibility info
3968 $data->visible = $oldcourse->visible;
3971 if ($data->visible != $oldcourse->visible) {
3972 // reset the visibleold flag when manually hiding/unhiding course
3973 $data->visibleold = $data->visible;
3974 } else {
3975 if ($movecat) {
3976 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3977 if (empty($newcategory->visible)) {
3978 // make sure when moving into hidden category the course is hidden automatically
3979 $data->visible = 0;
3984 // Update with the new data
3985 $DB->update_record('course', $data);
3987 $course = $DB->get_record('course', array('id'=>$data->id));
3989 if ($movecat) {
3990 $newparent = context_coursecat::instance($course->category);
3991 context_moved($context, $newparent);
3994 fix_course_sortorder();
3996 // Test for and remove blocks which aren't appropriate anymore
3997 blocks_remove_inappropriate($course);
3999 // Save any custom role names.
4000 save_local_role_names($course->id, $data);
4002 // update enrol settings
4003 enrol_course_updated(false, $course, $data);
4005 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
4007 // Trigger events
4008 events_trigger('course_updated', $course);
4012 * Average number of participants
4013 * @return integer
4015 function average_number_of_participants() {
4016 global $DB, $SITE;
4018 //count total of enrolments for visible course (except front page)
4019 $sql = 'SELECT COUNT(*) FROM (
4020 SELECT DISTINCT ue.userid, e.courseid
4021 FROM {user_enrolments} ue, {enrol} e, {course} c
4022 WHERE ue.enrolid = e.id
4023 AND e.courseid <> :siteid
4024 AND c.id = e.courseid
4025 AND c.visible = 1) total';
4026 $params = array('siteid' => $SITE->id);
4027 $enrolmenttotal = $DB->count_records_sql($sql, $params);
4030 //count total of visible courses (minus front page)
4031 $coursetotal = $DB->count_records('course', array('visible' => 1));
4032 $coursetotal = $coursetotal - 1 ;
4034 //average of enrolment
4035 if (empty($coursetotal)) {
4036 $participantaverage = 0;
4037 } else {
4038 $participantaverage = $enrolmenttotal / $coursetotal;
4041 return $participantaverage;
4045 * Average number of course modules
4046 * @return integer
4048 function average_number_of_courses_modules() {
4049 global $DB, $SITE;
4051 //count total of visible course module (except front page)
4052 $sql = 'SELECT COUNT(*) FROM (
4053 SELECT cm.course, cm.module
4054 FROM {course} c, {course_modules} cm
4055 WHERE c.id = cm.course
4056 AND c.id <> :siteid
4057 AND cm.visible = 1
4058 AND c.visible = 1) total';
4059 $params = array('siteid' => $SITE->id);
4060 $moduletotal = $DB->count_records_sql($sql, $params);
4063 //count total of visible courses (minus front page)
4064 $coursetotal = $DB->count_records('course', array('visible' => 1));
4065 $coursetotal = $coursetotal - 1 ;
4067 //average of course module
4068 if (empty($coursetotal)) {
4069 $coursemoduleaverage = 0;
4070 } else {
4071 $coursemoduleaverage = $moduletotal / $coursetotal;
4074 return $coursemoduleaverage;
4078 * This class pertains to course requests and contains methods associated with
4079 * create, approving, and removing course requests.
4081 * Please note we do not allow embedded images here because there is no context
4082 * to store them with proper access control.
4084 * @copyright 2009 Sam Hemelryk
4085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4086 * @since Moodle 2.0
4088 * @property-read int $id
4089 * @property-read string $fullname
4090 * @property-read string $shortname
4091 * @property-read string $summary
4092 * @property-read int $summaryformat
4093 * @property-read int $summarytrust
4094 * @property-read string $reason
4095 * @property-read int $requester
4097 class course_request {
4100 * This is the stdClass that stores the properties for the course request
4101 * and is externally accessed through the __get magic method
4102 * @var stdClass
4104 protected $properties;
4107 * An array of options for the summary editor used by course request forms.
4108 * This is initially set by {@link summary_editor_options()}
4109 * @var array
4110 * @static
4112 protected static $summaryeditoroptions;
4115 * Static function to prepare the summary editor for working with a course
4116 * request.
4118 * @static
4119 * @param null|stdClass $data Optional, an object containing the default values
4120 * for the form, these may be modified when preparing the
4121 * editor so this should be called before creating the form
4122 * @return stdClass An object that can be used to set the default values for
4123 * an mforms form
4125 public static function prepare($data=null) {
4126 if ($data === null) {
4127 $data = new stdClass;
4129 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4130 return $data;
4134 * Static function to create a new course request when passed an array of properties
4135 * for it.
4137 * This function also handles saving any files that may have been used in the editor
4139 * @static
4140 * @param stdClass $data
4141 * @return course_request The newly created course request
4143 public static function create($data) {
4144 global $USER, $DB, $CFG;
4145 $data->requester = $USER->id;
4147 // Summary is a required field so copy the text over
4148 $data->summary = $data->summary_editor['text'];
4149 $data->summaryformat = $data->summary_editor['format'];
4151 $data->id = $DB->insert_record('course_request', $data);
4153 // Create a new course_request object and return it
4154 $request = new course_request($data);
4156 // Notify the admin if required.
4157 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4159 $a = new stdClass;
4160 $a->link = "$CFG->wwwroot/course/pending.php";
4161 $a->user = fullname($USER);
4162 $subject = get_string('courserequest');
4163 $message = get_string('courserequestnotifyemail', 'admin', $a);
4164 foreach ($users as $user) {
4165 $request->notify($user, $USER, 'courserequested', $subject, $message);
4169 return $request;
4173 * Returns an array of options to use with a summary editor
4175 * @uses course_request::$summaryeditoroptions
4176 * @return array An array of options to use with the editor
4178 public static function summary_editor_options() {
4179 global $CFG;
4180 if (self::$summaryeditoroptions === null) {
4181 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4183 return self::$summaryeditoroptions;
4187 * Loads the properties for this course request object. Id is required and if
4188 * only id is provided then we load the rest of the properties from the database
4190 * @param stdClass|int $properties Either an object containing properties
4191 * or the course_request id to load
4193 public function __construct($properties) {
4194 global $DB;
4195 if (empty($properties->id)) {
4196 if (empty($properties)) {
4197 throw new coding_exception('You must provide a course request id when creating a course_request object');
4199 $id = $properties;
4200 $properties = new stdClass;
4201 $properties->id = (int)$id;
4202 unset($id);
4204 if (empty($properties->requester)) {
4205 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4206 print_error('unknowncourserequest');
4208 } else {
4209 $this->properties = $properties;
4211 $this->properties->collision = null;
4215 * Returns the requested property
4217 * @param string $key
4218 * @return mixed
4220 public function __get($key) {
4221 return $this->properties->$key;
4225 * Override this to ensure empty($request->blah) calls return a reliable answer...
4227 * This is required because we define the __get method
4229 * @param mixed $key
4230 * @return bool True is it not empty, false otherwise
4232 public function __isset($key) {
4233 return (!empty($this->properties->$key));
4237 * Returns the user who requested this course
4239 * Uses a static var to cache the results and cut down the number of db queries
4241 * @staticvar array $requesters An array of cached users
4242 * @return stdClass The user who requested the course
4244 public function get_requester() {
4245 global $DB;
4246 static $requesters= array();
4247 if (!array_key_exists($this->properties->requester, $requesters)) {
4248 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4250 return $requesters[$this->properties->requester];
4254 * Checks that the shortname used by the course does not conflict with any other
4255 * courses that exist
4257 * @param string|null $shortnamemark The string to append to the requests shortname
4258 * should a conflict be found
4259 * @return bool true is there is a conflict, false otherwise
4261 public function check_shortname_collision($shortnamemark = '[*]') {
4262 global $DB;
4264 if ($this->properties->collision !== null) {
4265 return $this->properties->collision;
4268 if (empty($this->properties->shortname)) {
4269 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4270 $this->properties->collision = false;
4271 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4272 if (!empty($shortnamemark)) {
4273 $this->properties->shortname .= ' '.$shortnamemark;
4275 $this->properties->collision = true;
4276 } else {
4277 $this->properties->collision = false;
4279 return $this->properties->collision;
4283 * This function approves the request turning it into a course
4285 * This function converts the course request into a course, at the same time
4286 * transferring any files used in the summary to the new course and then removing
4287 * the course request and the files associated with it.
4289 * @return int The id of the course that was created from this request
4291 public function approve() {
4292 global $CFG, $DB, $USER;
4294 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4296 $category = get_course_category($CFG->defaultrequestcategory);
4297 $courseconfig = get_config('moodlecourse');
4299 // Transfer appropriate settings
4300 $data = clone($this->properties);
4301 unset($data->id);
4302 unset($data->reason);
4303 unset($data->requester);
4305 // Set category
4306 $data->category = $category->id;
4307 $data->sortorder = $category->sortorder; // place as the first in category
4309 // Set misc settings
4310 $data->requested = 1;
4312 // Apply course default settings
4313 $data->format = $courseconfig->format;
4314 $data->numsections = $courseconfig->numsections;
4315 $data->hiddensections = $courseconfig->hiddensections;
4316 $data->newsitems = $courseconfig->newsitems;
4317 $data->showgrades = $courseconfig->showgrades;
4318 $data->showreports = $courseconfig->showreports;
4319 $data->maxbytes = $courseconfig->maxbytes;
4320 $data->groupmode = $courseconfig->groupmode;
4321 $data->groupmodeforce = $courseconfig->groupmodeforce;
4322 $data->visible = $courseconfig->visible;
4323 $data->visibleold = $data->visible;
4324 $data->lang = $courseconfig->lang;
4326 $course = create_course($data);
4327 $context = context_course::instance($course->id, MUST_EXIST);
4329 // add enrol instances
4330 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4331 if ($manual = enrol_get_plugin('manual')) {
4332 $manual->add_default_instance($course);
4336 // enrol the requester as teacher if necessary
4337 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4338 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4341 $this->delete();
4343 $a = new stdClass();
4344 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
4345 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4346 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4348 return $course->id;
4352 * Reject a course request
4354 * This function rejects a course request, emailing the requesting user the
4355 * provided notice and then removing the request from the database
4357 * @param string $notice The message to display to the user
4359 public function reject($notice) {
4360 global $USER, $DB;
4361 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4362 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4363 $this->delete();
4367 * Deletes the course request and any associated files
4369 public function delete() {
4370 global $DB;
4371 $DB->delete_records('course_request', array('id' => $this->properties->id));
4375 * Send a message from one user to another using events_trigger
4377 * @param object $touser
4378 * @param object $fromuser
4379 * @param string $name
4380 * @param string $subject
4381 * @param string $message
4383 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4384 $eventdata = new stdClass();
4385 $eventdata->component = 'moodle';
4386 $eventdata->name = $name;
4387 $eventdata->userfrom = $fromuser;
4388 $eventdata->userto = $touser;
4389 $eventdata->subject = $subject;
4390 $eventdata->fullmessage = $message;
4391 $eventdata->fullmessageformat = FORMAT_PLAIN;
4392 $eventdata->fullmessagehtml = '';
4393 $eventdata->smallmessage = '';
4394 $eventdata->notification = 1;
4395 message_send($eventdata);
4400 * Return a list of page types
4401 * @param string $pagetype current page type
4402 * @param stdClass $parentcontext Block's parent context
4403 * @param stdClass $currentcontext Current context of block
4405 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4406 // if above course context ,display all course fomats
4407 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4408 if ($course->id == SITEID) {
4409 return array('*'=>get_string('page-x', 'pagetype'));
4410 } else {
4411 return array('*'=>get_string('page-x', 'pagetype'),
4412 'course-*'=>get_string('page-course-x', 'pagetype'),
4413 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4419 * Determine whether course ajax should be enabled for the specified course
4421 * @param stdClass $course The course to test against
4422 * @return boolean Whether course ajax is enabled or note
4424 function course_ajax_enabled($course) {
4425 global $CFG, $PAGE, $SITE;
4427 // Ajax must be enabled globally
4428 if (!$CFG->enableajax) {
4429 return false;
4432 // The user must be editing for AJAX to be included
4433 if (!$PAGE->user_is_editing()) {
4434 return false;
4437 // Check that the theme suports
4438 if (!$PAGE->theme->enablecourseajax) {
4439 return false;
4442 // Check that the course format supports ajax functionality
4443 // The site 'format' doesn't have information on course format support
4444 if ($SITE->id !== $course->id) {
4445 $courseformatajaxsupport = course_format_ajax_support($course->format);
4446 if (!$courseformatajaxsupport->capable) {
4447 return false;
4451 // All conditions have been met so course ajax should be enabled
4452 return true;
4456 * Include the relevant javascript and language strings for the resource
4457 * toolbox YUI module
4459 * @param integer $id The ID of the course being applied to
4460 * @param array $usedmodules An array containing the names of the modules in use on the page
4461 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4462 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4463 * * resourceurl The URL to post changes to for resource changes
4464 * * sectionurl The URL to post changes to for section changes
4465 * * pageparams Additional parameters to pass through in the post
4466 * @return bool
4468 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4469 global $PAGE, $SITE;
4471 // Ensure that ajax should be included
4472 if (!course_ajax_enabled($course)) {
4473 return false;
4476 if (!$config) {
4477 $config = new stdClass();
4480 // The URL to use for resource changes
4481 if (!isset($config->resourceurl)) {
4482 $config->resourceurl = '/course/rest.php';
4485 // The URL to use for section changes
4486 if (!isset($config->sectionurl)) {
4487 $config->sectionurl = '/course/rest.php';
4490 // Any additional parameters which need to be included on page submission
4491 if (!isset($config->pageparams)) {
4492 $config->pageparams = array();
4495 // Include toolboxes
4496 $PAGE->requires->yui_module('moodle-course-toolboxes',
4497 'M.course.init_resource_toolbox',
4498 array(array(
4499 'courseid' => $course->id,
4500 'ajaxurl' => $config->resourceurl,
4501 'config' => $config,
4504 $PAGE->requires->yui_module('moodle-course-toolboxes',
4505 'M.course.init_section_toolbox',
4506 array(array(
4507 'courseid' => $course->id,
4508 'format' => $course->format,
4509 'ajaxurl' => $config->sectionurl,
4510 'config' => $config,
4514 // Include course dragdrop
4515 if ($course->id != $SITE->id) {
4516 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4517 array(array(
4518 'courseid' => $course->id,
4519 'ajaxurl' => $config->sectionurl,
4520 'config' => $config,
4521 )), null, true);
4523 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4524 array(array(
4525 'courseid' => $course->id,
4526 'ajaxurl' => $config->resourceurl,
4527 'config' => $config,
4528 )), null, true);
4531 // Include blocks dragdrop
4532 $params = array(
4533 'courseid' => $course->id,
4534 'pagetype' => $PAGE->pagetype,
4535 'pagelayout' => $PAGE->pagelayout,
4536 'regions' => $PAGE->blocks->get_regions(),
4538 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4540 // Require various strings for the command toolbox
4541 $PAGE->requires->strings_for_js(array(
4542 'moveleft',
4543 'deletechecktype',
4544 'deletechecktypename',
4545 'edittitle',
4546 'edittitleinstructions',
4547 'show',
4548 'hide',
4549 'groupsnone',
4550 'groupsvisible',
4551 'groupsseparate',
4552 'clicktochangeinbrackets',
4553 'markthistopic',
4554 'markedthistopic',
4555 'move',
4556 'movesection',
4557 ), 'moodle');
4559 // Include format-specific strings
4560 if ($course->id != $SITE->id) {
4561 $PAGE->requires->strings_for_js(array(
4562 'showfromothers',
4563 'hidefromothers',
4564 ), 'format_' . $course->format);
4567 // For confirming resource deletion we need the name of the module in question
4568 foreach ($usedmodules as $module => $modname) {
4569 $PAGE->requires->string_for_js('pluginname', $module);
4572 // Load drag and drop upload AJAX.
4573 dndupload_add_to_course($course, $enabledmodules);
4575 // Add the module chooser
4576 $PAGE->requires->yui_module('moodle-course-modchooser',
4577 'M.course.init_chooser',
4578 array(array('courseid' => $course->id))
4580 $PAGE->requires->strings_for_js(array(
4581 'addresourceoractivity',
4582 'modchooserenable',
4583 'modchooserdisable',
4584 ), 'moodle');
4586 return true;
4590 * The URL to use for the specified course (with section)
4592 * @param stdClass $course The course to get the section name for
4593 * @param int $sectionno The section number to return a link to
4594 * @return moodle_url The url of course
4596 function course_get_url($course, $sectionno = null) {
4597 $url = new moodle_url('/course/view.php', array('id' => $course->id));
4599 if (!is_null($sectionno)) {
4600 if ($course->coursedisplay == COURSE_DISPLAY_MULTIPAGE) {
4601 $url->param('section', $sectionno);
4602 } else {
4603 $url->set_anchor('section-'.$sectionno);
4607 return $url;