MDL-40611 fix context cache size expectation
[moodle.git] / course / lib.php
blob93ee68339e49d343dc9c911f16bfa590a9314028
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core
24 * @subpackage course
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
37 /**
38 * Number of courses to display when summaries are included.
39 * @var int
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'calendar':
71 case 'category':
72 case 'mnet course':
73 if (strpos($url, '../') === 0) {
74 $url = ltrim($url, '.');
75 } else {
76 $url = "/course/$url";
78 break;
79 case 'user':
80 case 'blog':
81 $url = "/$module/$url";
82 break;
83 case 'upload':
84 $url = $url;
85 break;
86 case 'coursetags':
87 $url = '/'.$url;
88 break;
89 case 'library':
90 case '':
91 $url = '/';
92 break;
93 case 'message':
94 $url = "/message/$url";
95 break;
96 case 'notes':
97 $url = "/notes/$url";
98 break;
99 case 'tag':
100 $url = "/tag/$url";
101 break;
102 case 'role':
103 $url = '/'.$url;
104 break;
105 case 'grade':
106 $url = "/grade/$url";
107 break;
108 default:
109 $url = "/mod/$module/$url";
110 break;
113 //now let's sanitise urls - there might be some ugly nasties:-(
114 $parts = explode('?', $url);
115 $script = array_shift($parts);
116 if (strpos($script, 'http') === 0) {
117 $script = clean_param($script, PARAM_URL);
118 } else {
119 $script = clean_param($script, PARAM_PATH);
122 $query = '';
123 if ($parts) {
124 $query = implode('', $parts);
125 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
126 $parts = explode('&', $query);
127 $eq = urlencode('=');
128 foreach ($parts as $key=>$part) {
129 $part = urlencode(urldecode($part));
130 $part = str_replace($eq, '=', $part);
131 $parts[$key] = $part;
133 $query = '?'.implode('&amp;', $parts);
136 return $script.$query;
140 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
141 $modname="", $modid=0, $modaction="", $groupid=0) {
142 global $CFG, $DB;
144 // It is assumed that $date is the GMT time of midnight for that day,
145 // and so the next 86400 seconds worth of logs are printed.
147 /// Setup for group handling.
149 // TODO: I don't understand group/context/etc. enough to be able to do
150 // something interesting with it here
151 // What is the context of a remote course?
153 /// If the group mode is separate, and this user does not have editing privileges,
154 /// then only the user's group can be viewed.
155 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
156 // $groupid = get_current_group($course->id);
158 /// If this course doesn't have groups, no groupid can be specified.
159 //else if (!$course->groupmode) {
160 // $groupid = 0;
163 $groupid = 0;
165 $joins = array();
166 $where = '';
168 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
169 FROM {mnet_log} l
170 LEFT JOIN {user} u ON l.userid = u.id
171 WHERE ";
172 $params = array();
174 $where .= "l.hostid = :hostid";
175 $params['hostid'] = $hostid;
177 // TODO: Is 1 really a magic number referring to the sitename?
178 if ($course != SITEID || $modid != 0) {
179 $where .= " AND l.course=:courseid";
180 $params['courseid'] = $course;
183 if ($modname) {
184 $where .= " AND l.module = :modname";
185 $params['modname'] = $modname;
188 if ('site_errors' === $modid) {
189 $where .= " AND ( l.action='error' OR l.action='infected' )";
190 } else if ($modid) {
191 //TODO: This assumes that modids are the same across sites... probably
192 //not true
193 $where .= " AND l.cmid = :modid";
194 $params['modid'] = $modid;
197 if ($modaction) {
198 $firstletter = substr($modaction, 0, 1);
199 if ($firstletter == '-') {
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
201 $params['modaction'] = '%'.substr($modaction, 1).'%';
202 } else {
203 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
204 $params['modaction'] = '%'.$modaction.'%';
208 if ($user) {
209 $where .= " AND l.userid = :user";
210 $params['user'] = $user;
213 if ($date) {
214 $enddate = $date + 86400;
215 $where .= " AND l.time > :date AND l.time < :enddate";
216 $params['date'] = $date;
217 $params['enddate'] = $enddate;
220 $result = array();
221 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
222 if(!empty($result['totalcount'])) {
223 $where .= " ORDER BY $order";
224 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
225 } else {
226 $result['logs'] = array();
228 return $result;
231 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
232 $modname="", $modid=0, $modaction="", $groupid=0) {
233 global $DB, $SESSION, $USER;
234 // It is assumed that $date is the GMT time of midnight for that day,
235 // and so the next 86400 seconds worth of logs are printed.
237 /// Setup for group handling.
239 /// If the group mode is separate, and this user does not have editing privileges,
240 /// then only the user's group can be viewed.
241 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
242 if (isset($SESSION->currentgroup[$course->id])) {
243 $groupid = $SESSION->currentgroup[$course->id];
244 } else {
245 $groupid = groups_get_all_groups($course->id, $USER->id);
246 if (is_array($groupid)) {
247 $groupid = array_shift(array_keys($groupid));
248 $SESSION->currentgroup[$course->id] = $groupid;
249 } else {
250 $groupid = 0;
254 /// If this course doesn't have groups, no groupid can be specified.
255 else if (!$course->groupmode) {
256 $groupid = 0;
259 $joins = array();
260 $params = array();
262 if ($course->id != SITEID || $modid != 0) {
263 $joins[] = "l.course = :courseid";
264 $params['courseid'] = $course->id;
267 if ($modname) {
268 $joins[] = "l.module = :modname";
269 $params['modname'] = $modname;
272 if ('site_errors' === $modid) {
273 $joins[] = "( l.action='error' OR l.action='infected' )";
274 } else if ($modid) {
275 $joins[] = "l.cmid = :modid";
276 $params['modid'] = $modid;
279 if ($modaction) {
280 $firstletter = substr($modaction, 0, 1);
281 if ($firstletter == '-') {
282 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
283 $params['modaction'] = '%'.substr($modaction, 1).'%';
284 } else {
285 $joins[] = $DB->sql_like('l.action', ':modaction', false);
286 $params['modaction'] = '%'.$modaction.'%';
291 /// Getting all members of a group.
292 if ($groupid and !$user) {
293 if ($gusers = groups_get_members($groupid)) {
294 $gusers = array_keys($gusers);
295 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
296 } else {
297 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
300 else if ($user) {
301 $joins[] = "l.userid = :userid";
302 $params['userid'] = $user;
305 if ($date) {
306 $enddate = $date + 86400;
307 $joins[] = "l.time > :date AND l.time < :enddate";
308 $params['date'] = $date;
309 $params['enddate'] = $enddate;
312 $selector = implode(' AND ', $joins);
314 $totalcount = 0; // Initialise
315 $result = array();
316 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
317 $result['totalcount'] = $totalcount;
318 return $result;
322 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
323 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
325 global $CFG, $DB, $OUTPUT;
327 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
328 $modname, $modid, $modaction, $groupid)) {
329 echo $OUTPUT->notification("No logs found!");
330 echo $OUTPUT->footer();
331 exit;
334 $courses = array();
336 if ($course->id == SITEID) {
337 $courses[0] = '';
338 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
339 foreach ($ccc as $cc) {
340 $courses[$cc->id] = $cc->shortname;
343 } else {
344 $courses[$course->id] = $course->shortname;
347 $totalcount = $logs['totalcount'];
348 $count=0;
349 $ldcache = array();
350 $tt = getdate(time());
351 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
353 $strftimedatetime = get_string("strftimedatetime");
355 echo "<div class=\"info\">\n";
356 print_string("displayingrecords", "", $totalcount);
357 echo "</div>\n";
359 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
361 $table = new html_table();
362 $table->classes = array('logtable','generalbox');
363 $table->align = array('right', 'left', 'left');
364 $table->head = array(
365 get_string('time'),
366 get_string('ip_address'),
367 get_string('fullnameuser'),
368 get_string('action'),
369 get_string('info')
371 $table->data = array();
373 if ($course->id == SITEID) {
374 array_unshift($table->align, 'left');
375 array_unshift($table->head, get_string('course'));
378 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
379 if (empty($logs['logs'])) {
380 $logs['logs'] = array();
383 foreach ($logs['logs'] as $log) {
385 if (isset($ldcache[$log->module][$log->action])) {
386 $ld = $ldcache[$log->module][$log->action];
387 } else {
388 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
389 $ldcache[$log->module][$log->action] = $ld;
391 if ($ld && is_numeric($log->info)) {
392 // ugly hack to make sure fullname is shown correctly
393 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
394 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
395 } else {
396 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
400 //Filter log->info
401 $log->info = format_string($log->info);
403 // If $log->url has been trimmed short by the db size restriction
404 // code in add_to_log, keep a note so we don't add a link to a broken url
405 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
407 $row = array();
408 if ($course->id == SITEID) {
409 if (empty($log->course)) {
410 $row[] = get_string('site');
411 } else {
412 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
416 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
418 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
419 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
421 $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))));
423 $displayaction="$log->module $log->action";
424 if ($brokenurl) {
425 $row[] = $displayaction;
426 } else {
427 $link = make_log_url($log->module,$log->url);
428 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
430 $row[] = $log->info;
431 $table->data[] = $row;
434 echo html_writer::table($table);
435 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
439 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
440 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
442 global $CFG, $DB, $OUTPUT;
444 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
445 $modname, $modid, $modaction, $groupid)) {
446 echo $OUTPUT->notification("No logs found!");
447 echo $OUTPUT->footer();
448 exit;
451 if ($course->id == SITEID) {
452 $courses[0] = '';
453 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
454 foreach ($ccc as $cc) {
455 $courses[$cc->id] = $cc->shortname;
460 $totalcount = $logs['totalcount'];
461 $count=0;
462 $ldcache = array();
463 $tt = getdate(time());
464 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
466 $strftimedatetime = get_string("strftimedatetime");
468 echo "<div class=\"info\">\n";
469 print_string("displayingrecords", "", $totalcount);
470 echo "</div>\n";
472 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
474 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
475 echo "<tr>";
476 if ($course->id == SITEID) {
477 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
479 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
480 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
481 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
482 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
483 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
484 echo "</tr>\n";
486 if (empty($logs['logs'])) {
487 echo "</table>\n";
488 return;
491 $row = 1;
492 foreach ($logs['logs'] as $log) {
494 $log->info = $log->coursename;
495 $row = ($row + 1) % 2;
497 if (isset($ldcache[$log->module][$log->action])) {
498 $ld = $ldcache[$log->module][$log->action];
499 } else {
500 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
501 $ldcache[$log->module][$log->action] = $ld;
503 if (0 && $ld && !empty($log->info)) {
504 // ugly hack to make sure fullname is shown correctly
505 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
506 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
507 } else {
508 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
512 //Filter log->info
513 $log->info = format_string($log->info);
515 echo '<tr class="r'.$row.'">';
516 if ($course->id == SITEID) {
517 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
518 echo "<td class=\"r$row c0\" >\n";
519 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
520 echo "</td>\n";
522 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
523 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
524 echo "<td class=\"r$row c2\" >\n";
525 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
526 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
527 echo "</td>\n";
528 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
529 echo "<td class=\"r$row c3\" >\n";
530 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
531 echo "</td>\n";
532 echo "<td class=\"r$row c4\">\n";
533 echo $log->action .': '.$log->module;
534 echo "</td>\n";;
535 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
536 echo "</tr>\n";
538 echo "</table>\n";
540 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
544 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
545 $modid, $modaction, $groupid) {
546 global $DB, $CFG;
548 require_once($CFG->libdir . '/csvlib.class.php');
550 $csvexporter = new csv_export_writer('tab');
552 $header = array();
553 $header[] = get_string('course');
554 $header[] = get_string('time');
555 $header[] = get_string('ip_address');
556 $header[] = get_string('fullnameuser');
557 $header[] = get_string('action');
558 $header[] = get_string('info');
560 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
561 $modname, $modid, $modaction, $groupid)) {
562 return false;
565 $courses = array();
567 if ($course->id == SITEID) {
568 $courses[0] = '';
569 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
570 foreach ($ccc as $cc) {
571 $courses[$cc->id] = $cc->shortname;
574 } else {
575 $courses[$course->id] = $course->shortname;
578 $count=0;
579 $ldcache = array();
580 $tt = getdate(time());
581 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
583 $strftimedatetime = get_string("strftimedatetime");
585 $csvexporter->set_filename('logs', '.txt');
586 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
587 $csvexporter->add_data($title);
588 $csvexporter->add_data($header);
590 if (empty($logs['logs'])) {
591 return true;
594 foreach ($logs['logs'] as $log) {
595 if (isset($ldcache[$log->module][$log->action])) {
596 $ld = $ldcache[$log->module][$log->action];
597 } else {
598 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
599 $ldcache[$log->module][$log->action] = $ld;
601 if ($ld && is_numeric($log->info)) {
602 // ugly hack to make sure fullname is shown correctly
603 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
604 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
605 } else {
606 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
610 //Filter log->info
611 $log->info = format_string($log->info);
612 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
614 $coursecontext = context_course::instance($course->id);
615 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
616 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
617 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
618 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
619 $csvexporter->add_data($row);
621 $csvexporter->download_file();
622 return true;
626 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
627 $modid, $modaction, $groupid) {
629 global $CFG, $DB;
631 require_once("$CFG->libdir/excellib.class.php");
633 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
634 $modname, $modid, $modaction, $groupid)) {
635 return false;
638 $courses = array();
640 if ($course->id == SITEID) {
641 $courses[0] = '';
642 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
643 foreach ($ccc as $cc) {
644 $courses[$cc->id] = $cc->shortname;
647 } else {
648 $courses[$course->id] = $course->shortname;
651 $count=0;
652 $ldcache = array();
653 $tt = getdate(time());
654 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
656 $strftimedatetime = get_string("strftimedatetime");
658 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
659 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
660 $filename .= '.xls';
662 $workbook = new MoodleExcelWorkbook('-');
663 $workbook->send($filename);
665 $worksheet = array();
666 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
667 get_string('fullnameuser'), get_string('action'), get_string('info'));
669 // Creating worksheets
670 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
671 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
672 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
673 $worksheet[$wsnumber]->set_column(1, 1, 30);
674 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
675 userdate(time(), $strftimedatetime));
676 $col = 0;
677 foreach ($headers as $item) {
678 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
679 $col++;
683 if (empty($logs['logs'])) {
684 $workbook->close();
685 return true;
688 $formatDate =& $workbook->add_format();
689 $formatDate->set_num_format(get_string('log_excel_date_format'));
691 $row = FIRSTUSEDEXCELROW;
692 $wsnumber = 1;
693 $myxls =& $worksheet[$wsnumber];
694 foreach ($logs['logs'] as $log) {
695 if (isset($ldcache[$log->module][$log->action])) {
696 $ld = $ldcache[$log->module][$log->action];
697 } else {
698 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
699 $ldcache[$log->module][$log->action] = $ld;
701 if ($ld && is_numeric($log->info)) {
702 // ugly hack to make sure fullname is shown correctly
703 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
704 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
705 } else {
706 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
710 // Filter log->info
711 $log->info = format_string($log->info);
712 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
714 if ($nroPages>1) {
715 if ($row > EXCELROWS) {
716 $wsnumber++;
717 $myxls =& $worksheet[$wsnumber];
718 $row = FIRSTUSEDEXCELROW;
722 $coursecontext = context_course::instance($course->id);
724 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
725 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
726 $myxls->write($row, 2, $log->ip, '');
727 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
728 $myxls->write($row, 3, $fullname, '');
729 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
730 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
731 $myxls->write($row, 5, $log->info, '');
733 $row++;
736 $workbook->close();
737 return true;
740 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
741 $modid, $modaction, $groupid) {
743 global $CFG, $DB;
745 require_once("$CFG->libdir/odslib.class.php");
747 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
748 $modname, $modid, $modaction, $groupid)) {
749 return false;
752 $courses = array();
754 if ($course->id == SITEID) {
755 $courses[0] = '';
756 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
757 foreach ($ccc as $cc) {
758 $courses[$cc->id] = $cc->shortname;
761 } else {
762 $courses[$course->id] = $course->shortname;
765 $count=0;
766 $ldcache = array();
767 $tt = getdate(time());
768 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
770 $strftimedatetime = get_string("strftimedatetime");
772 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
773 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
774 $filename .= '.ods';
776 $workbook = new MoodleODSWorkbook('-');
777 $workbook->send($filename);
779 $worksheet = array();
780 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
781 get_string('fullnameuser'), get_string('action'), get_string('info'));
783 // Creating worksheets
784 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
785 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
786 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
787 $worksheet[$wsnumber]->set_column(1, 1, 30);
788 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
789 userdate(time(), $strftimedatetime));
790 $col = 0;
791 foreach ($headers as $item) {
792 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
793 $col++;
797 if (empty($logs['logs'])) {
798 $workbook->close();
799 return true;
802 $formatDate =& $workbook->add_format();
803 $formatDate->set_num_format(get_string('log_excel_date_format'));
805 $row = FIRSTUSEDEXCELROW;
806 $wsnumber = 1;
807 $myxls =& $worksheet[$wsnumber];
808 foreach ($logs['logs'] as $log) {
809 if (isset($ldcache[$log->module][$log->action])) {
810 $ld = $ldcache[$log->module][$log->action];
811 } else {
812 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
813 $ldcache[$log->module][$log->action] = $ld;
815 if ($ld && is_numeric($log->info)) {
816 // ugly hack to make sure fullname is shown correctly
817 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
818 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
819 } else {
820 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
824 // Filter log->info
825 $log->info = format_string($log->info);
826 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
828 if ($nroPages>1) {
829 if ($row > EXCELROWS) {
830 $wsnumber++;
831 $myxls =& $worksheet[$wsnumber];
832 $row = FIRSTUSEDEXCELROW;
836 $coursecontext = context_course::instance($course->id);
838 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
839 $myxls->write_date($row, 1, $log->time);
840 $myxls->write_string($row, 2, $log->ip);
841 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
842 $myxls->write_string($row, 3, $fullname);
843 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
844 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
845 $myxls->write_string($row, 5, $log->info);
847 $row++;
850 $workbook->close();
851 return true;
855 function print_overview($courses, array $remote_courses=array()) {
856 global $CFG, $USER, $DB, $OUTPUT;
858 $htmlarray = array();
859 if ($modules = $DB->get_records('modules')) {
860 foreach ($modules as $mod) {
861 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
862 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
863 $fname = $mod->name.'_print_overview';
864 if (function_exists($fname)) {
865 $fname($courses,$htmlarray);
870 foreach ($courses as $course) {
871 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
872 echo $OUTPUT->box_start('coursebox');
873 $attributes = array('title' => s($fullname));
874 if (empty($course->visible)) {
875 $attributes['class'] = 'dimmed';
877 echo $OUTPUT->heading(html_writer::link(
878 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
879 if (array_key_exists($course->id,$htmlarray)) {
880 foreach ($htmlarray[$course->id] as $modname => $html) {
881 echo $html;
884 echo $OUTPUT->box_end();
887 if (!empty($remote_courses)) {
888 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
890 foreach ($remote_courses as $course) {
891 echo $OUTPUT->box_start('coursebox');
892 $attributes = array('title' => s($course->fullname));
893 echo $OUTPUT->heading(html_writer::link(
894 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
895 format_string($course->shortname),
896 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
897 echo $OUTPUT->box_end();
903 * This function trawls through the logs looking for
904 * anything new since the user's last login
906 function print_recent_activity($course) {
907 // $course is an object
908 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
910 $context = context_course::instance($course->id);
912 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
914 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
916 if (!isguestuser()) {
917 if (!empty($USER->lastcourseaccess[$course->id])) {
918 if ($USER->lastcourseaccess[$course->id] > $timestart) {
919 $timestart = $USER->lastcourseaccess[$course->id];
924 echo '<div class="activitydate">';
925 echo get_string('activitysince', '', userdate($timestart));
926 echo '</div>';
927 echo '<div class="activityhead">';
929 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
931 echo "</div>\n";
933 $content = false;
935 /// Firstly, have there been any new enrolments?
937 $users = get_recent_enrolments($course->id, $timestart);
939 //Accessibility: new users now appear in an <OL> list.
940 if ($users) {
941 echo '<div class="newusers">';
942 echo $OUTPUT->heading(get_string("newusers").':', 3);
943 $content = true;
944 echo "<ol class=\"list\">\n";
945 foreach ($users as $user) {
946 $fullname = fullname($user, $viewfullnames);
947 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
949 echo "</ol>\n</div>\n";
952 /// Next, have there been any modifications to the course structure?
954 $modinfo = get_fast_modinfo($course);
956 $changelist = array();
958 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
959 module = 'course' AND
960 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
961 array($timestart, $course->id), "id ASC");
963 if ($logs) {
964 $actions = array('add mod', 'update mod', 'delete mod');
965 $newgones = array(); // added and later deleted items
966 foreach ($logs as $key => $log) {
967 if (!in_array($log->action, $actions)) {
968 continue;
970 $info = explode(' ', $log->info);
972 // note: in most cases I replaced hardcoding of label with use of
973 // $cm->has_view() but it was not possible to do this here because
974 // we don't necessarily have the $cm for it
975 if ($info[0] == 'label') { // Labels are ignored in recent activity
976 continue;
979 if (count($info) != 2) {
980 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
981 continue;
984 $modname = $info[0];
985 $instanceid = $info[1];
987 if ($log->action == 'delete mod') {
988 // unfortunately we do not know if the mod was visible
989 if (!array_key_exists($log->info, $newgones)) {
990 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
991 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
993 } else {
994 if (!isset($modinfo->instances[$modname][$instanceid])) {
995 if ($log->action == 'add mod') {
996 // do not display added and later deleted activities
997 $newgones[$log->info] = true;
999 continue;
1001 $cm = $modinfo->instances[$modname][$instanceid];
1002 if (!$cm->uservisible) {
1003 continue;
1006 if ($log->action == 'add mod') {
1007 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1008 $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>");
1010 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1011 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1012 $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>");
1018 if (!empty($changelist)) {
1019 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1020 $content = true;
1021 foreach ($changelist as $changeinfo => $change) {
1022 echo '<p class="activity">'.$change['text'].'</p>';
1026 /// Now display new things from each module
1028 $usedmodules = array();
1029 foreach($modinfo->cms as $cm) {
1030 if (isset($usedmodules[$cm->modname])) {
1031 continue;
1033 if (!$cm->uservisible) {
1034 continue;
1036 $usedmodules[$cm->modname] = $cm->modname;
1039 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1040 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1041 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1042 $print_recent_activity = $modname.'_print_recent_activity';
1043 if (function_exists($print_recent_activity)) {
1044 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1045 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1047 } else {
1048 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1052 if (! $content) {
1053 echo '<p class="message">'.get_string('nothingnew').'</p>';
1058 * For a given course, returns an array of course activity objects
1059 * Each item in the array contains he following properties:
1061 function get_array_of_activities($courseid) {
1062 // cm - course module id
1063 // mod - name of the module (eg forum)
1064 // section - the number of the section (eg week or topic)
1065 // name - the name of the instance
1066 // visible - is the instance visible or not
1067 // groupingid - grouping id
1068 // groupmembersonly - is this instance visible to group members only
1069 // extra - contains extra string to include in any link
1070 global $CFG, $DB;
1071 if(!empty($CFG->enableavailability)) {
1072 require_once($CFG->libdir.'/conditionlib.php');
1075 $course = $DB->get_record('course', array('id'=>$courseid));
1077 if (empty($course)) {
1078 throw new moodle_exception('courseidnotfound');
1081 $mod = array();
1083 $rawmods = get_course_mods($courseid);
1084 if (empty($rawmods)) {
1085 return $mod; // always return array
1088 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1089 foreach ($sections as $section) {
1090 if (!empty($section->sequence)) {
1091 $sequence = explode(",", $section->sequence);
1092 foreach ($sequence as $seq) {
1093 if (empty($rawmods[$seq])) {
1094 continue;
1096 $mod[$seq] = new stdClass();
1097 $mod[$seq]->id = $rawmods[$seq]->instance;
1098 $mod[$seq]->cm = $rawmods[$seq]->id;
1099 $mod[$seq]->mod = $rawmods[$seq]->modname;
1101 // Oh dear. Inconsistent names left here for backward compatibility.
1102 $mod[$seq]->section = $section->section;
1103 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1105 $mod[$seq]->module = $rawmods[$seq]->module;
1106 $mod[$seq]->added = $rawmods[$seq]->added;
1107 $mod[$seq]->score = $rawmods[$seq]->score;
1108 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1109 $mod[$seq]->visible = $rawmods[$seq]->visible;
1110 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1111 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1112 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1113 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1114 $mod[$seq]->indent = $rawmods[$seq]->indent;
1115 $mod[$seq]->completion = $rawmods[$seq]->completion;
1116 $mod[$seq]->extra = "";
1117 $mod[$seq]->completiongradeitemnumber =
1118 $rawmods[$seq]->completiongradeitemnumber;
1119 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1120 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1121 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1122 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1123 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1124 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1125 if (!empty($CFG->enableavailability)) {
1126 condition_info::fill_availability_conditions($rawmods[$seq]);
1127 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1128 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1129 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1132 $modname = $mod[$seq]->mod;
1133 $functionname = $modname."_get_coursemodule_info";
1135 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1136 continue;
1139 include_once("$CFG->dirroot/mod/$modname/lib.php");
1141 if ($hasfunction = function_exists($functionname)) {
1142 if ($info = $functionname($rawmods[$seq])) {
1143 if (!empty($info->icon)) {
1144 $mod[$seq]->icon = $info->icon;
1146 if (!empty($info->iconcomponent)) {
1147 $mod[$seq]->iconcomponent = $info->iconcomponent;
1149 if (!empty($info->name)) {
1150 $mod[$seq]->name = $info->name;
1152 if ($info instanceof cached_cm_info) {
1153 // When using cached_cm_info you can include three new fields
1154 // that aren't available for legacy code
1155 if (!empty($info->content)) {
1156 $mod[$seq]->content = $info->content;
1158 if (!empty($info->extraclasses)) {
1159 $mod[$seq]->extraclasses = $info->extraclasses;
1161 if (!empty($info->iconurl)) {
1162 $mod[$seq]->iconurl = $info->iconurl;
1164 if (!empty($info->onclick)) {
1165 $mod[$seq]->onclick = $info->onclick;
1167 if (!empty($info->customdata)) {
1168 $mod[$seq]->customdata = $info->customdata;
1170 } else {
1171 // When using a stdclass, the (horrible) deprecated ->extra field
1172 // is available for BC
1173 if (!empty($info->extra)) {
1174 $mod[$seq]->extra = $info->extra;
1179 // When there is no modname_get_coursemodule_info function,
1180 // but showdescriptions is enabled, then we use the 'intro'
1181 // and 'introformat' fields in the module table
1182 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1183 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1184 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1185 // Set content from intro and introformat. Filters are disabled
1186 // because we filter it with format_text at display time
1187 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1188 $modvalues, $rawmods[$seq]->id, false);
1190 // To save making another query just below, put name in here
1191 $mod[$seq]->name = $modvalues->name;
1194 if (!isset($mod[$seq]->name)) {
1195 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1198 // Minimise the database size by unsetting default options when they are
1199 // 'empty'. This list corresponds to code in the cm_info constructor.
1200 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1201 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1202 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1203 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1204 'completionview', 'completionexpected', 'score', 'showdescription')
1205 as $property) {
1206 if (property_exists($mod[$seq], $property) &&
1207 empty($mod[$seq]->{$property})) {
1208 unset($mod[$seq]->{$property});
1211 // Special case: this value is usually set to null, but may be 0
1212 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1213 is_null($mod[$seq]->completiongradeitemnumber)) {
1214 unset($mod[$seq]->completiongradeitemnumber);
1220 return $mod;
1224 * Returns the localised human-readable names of all used modules
1226 * @param bool $plural if true returns the plural forms of the names
1227 * @return array where key is the module name (component name without 'mod_') and
1228 * the value is the human-readable string. Array sorted alphabetically by value
1230 function get_module_types_names($plural = false) {
1231 static $modnames = null;
1232 global $DB, $CFG;
1233 if ($modnames === null) {
1234 $modnames = array(0 => array(), 1 => array());
1235 if ($allmods = $DB->get_records("modules")) {
1236 foreach ($allmods as $mod) {
1237 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1238 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1239 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1242 collatorlib::asort($modnames[0]);
1243 collatorlib::asort($modnames[1]);
1246 return $modnames[(int)$plural];
1250 * Set highlighted section. Only one section can be highlighted at the time.
1252 * @param int $courseid course id
1253 * @param int $marker highlight section with this number, 0 means remove higlightin
1254 * @return void
1256 function course_set_marker($courseid, $marker) {
1257 global $DB;
1258 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1259 format_base::reset_course_cache($courseid);
1263 * For a given course section, marks it visible or hidden,
1264 * and does the same for every activity in that section
1266 * @param int $courseid course id
1267 * @param int $sectionnumber The section number to adjust
1268 * @param int $visibility The new visibility
1269 * @return array A list of resources which were hidden in the section
1271 function set_section_visible($courseid, $sectionnumber, $visibility) {
1272 global $DB;
1274 $resourcestotoggle = array();
1275 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1276 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1277 if (!empty($section->sequence)) {
1278 $modules = explode(",", $section->sequence);
1279 foreach ($modules as $moduleid) {
1280 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1281 if ($visibility) {
1282 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1283 set_coursemodule_visible($moduleid, $cm->visibleold);
1284 } else {
1285 // We hide the section, so we hide the module but we store the original state in visibleold.
1286 set_coursemodule_visible($moduleid, 0);
1287 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1292 rebuild_course_cache($courseid, true);
1294 // Determine which modules are visible for AJAX update
1295 if (!empty($modules)) {
1296 list($insql, $params) = $DB->get_in_or_equal($modules);
1297 $select = 'id ' . $insql . ' AND visible = ?';
1298 array_push($params, $visibility);
1299 if (!$visibility) {
1300 $select .= ' AND visibleold = 1';
1302 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1305 return $resourcestotoggle;
1309 * Obtains shared data that is used in print_section when displaying a
1310 * course-module entry.
1312 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1314 * This data is also used in other areas of the code.
1315 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1316 * @param object $course Moodle course object
1317 * @return array An array with the following values in this order:
1318 * $content (optional extra content for after link),
1319 * $instancename (text of link)
1321 function get_print_section_cm_text(cm_info $cm, $course) {
1322 global $OUTPUT;
1324 // Get content from modinfo if specified. Content displays either
1325 // in addition to the standard link (below), or replaces it if
1326 // the link is turned off by setting ->url to null.
1327 if (($content = $cm->get_content()) !== '') {
1328 // Improve filter performance by preloading filter setttings for all
1329 // activities on the course (this does nothing if called multiple
1330 // times)
1331 filter_preload_activities($cm->get_modinfo());
1333 // Get module context
1334 $modulecontext = context_module::instance($cm->id);
1335 $labelformatoptions = new stdClass();
1336 $labelformatoptions->noclean = true;
1337 $labelformatoptions->overflowdiv = true;
1338 $labelformatoptions->context = $modulecontext;
1339 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1340 } else {
1341 $content = '';
1344 // Get course context
1345 $coursecontext = context_course::instance($course->id);
1346 $stringoptions = new stdClass;
1347 $stringoptions->context = $coursecontext;
1348 $instancename = format_string($cm->name, true, $stringoptions);
1349 return array($content, $instancename);
1353 * Prints a section full of activity modules
1355 * @param stdClass $course The course
1356 * @param stdClass|section_info $section The section object containing properties id and section
1357 * @param array $mods (argument not used)
1358 * @param array $modnamesused (argument not used)
1359 * @param bool $absolute All links are absolute
1360 * @param string $width Width of the container
1361 * @param bool $hidecompletion Hide completion status
1362 * @param int $sectionreturn The section to return to
1363 * @return void
1365 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1366 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1368 static $initialised;
1370 static $groupbuttons;
1371 static $groupbuttonslink;
1372 static $isediting;
1373 static $ismoving;
1374 static $strmovehere;
1375 static $strmovefull;
1376 static $strunreadpostsone;
1378 if (!isset($initialised)) {
1379 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1380 $groupbuttonslink = (!$course->groupmodeforce);
1381 $isediting = $PAGE->user_is_editing();
1382 $ismoving = $isediting && ismoving($course->id);
1383 if ($ismoving) {
1384 $strmovehere = get_string("movehere");
1385 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1387 $initialised = true;
1390 $modinfo = get_fast_modinfo($course);
1391 $completioninfo = new completion_info($course);
1393 //Accessibility: replace table with list <ul>, but don't output empty list.
1394 if (!empty($modinfo->sections[$section->section])) {
1396 // Fix bug #5027, don't want style=\"width:$width\".
1397 echo "<ul class=\"section img-text\">\n";
1399 foreach ($modinfo->sections[$section->section] as $modnumber) {
1400 $mod = $modinfo->cms[$modnumber];
1402 if ($ismoving and $mod->id == $USER->activitycopy) {
1403 // do not display moving mod
1404 continue;
1407 // We can continue (because it will not be displayed at all)
1408 // if:
1409 // 1) The activity is not visible to users
1410 // and
1411 // 2a) The 'showavailability' option is not set (if that is set,
1412 // we need to display the activity so we can show
1413 // availability info)
1414 // or
1415 // 2b) The 'availableinfo' is empty, i.e. the activity was
1416 // hidden in a way that leaves no info, such as using the
1417 // eye icon.
1418 if (!$mod->uservisible &&
1419 (empty($mod->showavailability) ||
1420 empty($mod->availableinfo))) {
1421 // visibility shortcut
1422 continue;
1425 // In some cases the activity is visible to user, but it is
1426 // dimmed. This is done if viewhiddenactivities is true and if:
1427 // 1. the activity is not visible, or
1428 // 2. the activity has dates set which do not include current, or
1429 // 3. the activity has any other conditions set (regardless of whether
1430 // current user meets them)
1431 $modcontext = context_module::instance($mod->id);
1432 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1433 $accessiblebutdim = false;
1434 $conditionalhidden = false;
1435 if ($canviewhidden) {
1436 $accessiblebutdim = !$mod->visible;
1437 if (!empty($CFG->enableavailability)) {
1438 $conditionalhidden = $mod->availablefrom > time() ||
1439 ($mod->availableuntil && $mod->availableuntil < time()) ||
1440 count($mod->conditionsgrade) > 0 ||
1441 count($mod->conditionscompletion) > 0;
1443 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1446 $liclasses = array();
1447 $liclasses[] = 'activity';
1448 $liclasses[] = $mod->modname;
1449 $liclasses[] = 'modtype_'.$mod->modname;
1450 $extraclasses = $mod->get_extra_classes();
1451 if ($extraclasses) {
1452 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1454 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1455 if ($ismoving) {
1456 echo '<a title="'.$strmovefull.'"'.
1457 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1458 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1459 ' alt="'.$strmovehere.'" /></a><br />
1463 $classes = array('mod-indent');
1464 if (!empty($mod->indent)) {
1465 $classes[] = 'mod-indent-'.$mod->indent;
1466 if ($mod->indent > 15) {
1467 $classes[] = 'mod-indent-huge';
1470 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1472 // Get data about this course-module
1473 list($content, $instancename) =
1474 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1476 //Accessibility: for files get description via icon, this is very ugly hack!
1477 $altname = '';
1478 $altname = $mod->modfullname;
1479 // Avoid unnecessary duplication: if e.g. a forum name already
1480 // includes the word forum (or Forum, etc) then it is unhelpful
1481 // to include that in the accessible description that is added.
1482 if (false !== strpos(textlib::strtolower($instancename),
1483 textlib::strtolower($altname))) {
1484 $altname = '';
1486 // File type after name, for alphabetic lists (screen reader).
1487 if ($altname) {
1488 $altname = get_accesshide(' '.$altname);
1491 // Start the div for the activity title, excluding the edit icons.
1492 echo html_writer::start_tag('div', array('class' => 'activityinstance'));
1494 // We may be displaying this just in order to show information
1495 // about visibility, without the actual link
1496 $contentpart = '';
1497 if ($mod->uservisible) {
1498 // Nope - in this case the link is fully working for user
1499 $linkclasses = '';
1500 $textclasses = '';
1501 if ($accessiblebutdim) {
1502 $linkclasses .= ' dimmed';
1503 $textclasses .= ' dimmed_text';
1504 if ($conditionalhidden) {
1505 $linkclasses .= ' conditionalhidden';
1506 $textclasses .= ' conditionalhidden';
1508 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
1509 } else {
1510 $accesstext = '';
1512 if ($linkclasses) {
1513 $linkcss = trim($linkclasses) . ' ';
1514 } else {
1515 $linkcss = '';
1517 if ($textclasses) {
1518 $textcss = trim($textclasses) . ' ';
1519 } else {
1520 $textcss = '';
1523 // Get on-click attribute value if specified and decode the onclick - it
1524 // has already been encoded for display (puke).
1525 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
1527 $groupinglabel = '';
1528 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1529 $groupings = groups_get_all_groupings($course->id);
1530 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
1531 array('class' => 'groupinglabel'));
1534 if ($url = $mod->get_url()) {
1535 // Display link itself.
1536 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
1537 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext .
1538 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
1539 echo html_writer::link($url, $activitylink, array('class' => $linkcss, 'onclick' => $onclick)) .
1540 $groupinglabel;
1542 // If specified, display extra content after link.
1543 if ($content) {
1544 $contentpart = html_writer::tag('div', $content, array('class' =>
1545 trim('contentafterlink ' . $textclasses)));
1547 } else {
1548 // No link, so display only content.
1549 $contentpart = html_writer::tag('div', $accesstext . $content, array('class' => $textcss));
1552 } else {
1553 $textclasses = $extraclasses;
1554 $textclasses .= ' dimmed_text';
1555 if ($textclasses) {
1556 $textcss = 'class="' . trim($textclasses) . '" ';
1557 } else {
1558 $textcss = '';
1560 $accesstext = '<span class="accesshide">' .
1561 get_string('notavailableyet', 'condition') .
1562 ': </span>';
1564 if ($url = $mod->get_url()) {
1565 // Display greyed-out text of link
1566 echo '<div ' . $textcss . $mod->extra .
1567 ' >' . '<img src="' . $mod->get_icon_url() .
1568 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1569 '</span></div>';
1571 // Do not display content after link when it is greyed out like this.
1572 } else {
1573 // No link, so display only content (also greyed)
1574 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1575 $accesstext . $content . '</div>';
1579 // Module can put text after the link (e.g. forum unread)
1580 echo $mod->get_after_link();
1582 // Closing the tag which contains everything but edit icons. $contentpart should not be part of this.
1583 echo html_writer::end_tag('div');
1585 // If there is content but NO link (eg label), then display the
1586 // content here (BEFORE any icons). In this case cons must be
1587 // displayed after the content so that it makes more sense visually
1588 // and for accessibility reasons, e.g. if you have a one-line label
1589 // it should work similarly (at least in terms of ordering) to an
1590 // activity.
1591 if (empty($url)) {
1592 echo $contentpart;
1595 if ($isediting) {
1596 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1597 if (! $mod->groupmodelink = $groupbuttonslink) {
1598 $mod->groupmode = $course->groupmode;
1601 } else {
1602 $mod->groupmode = false;
1604 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1605 echo $mod->get_after_edit_icons();
1608 // Completion
1609 $completion = $hidecompletion
1610 ? COMPLETION_TRACKING_NONE
1611 : $completioninfo->is_enabled($mod);
1612 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1613 !isguestuser() && $mod->uservisible) {
1614 $completiondata = $completioninfo->get_data($mod,true);
1615 $completionicon = '';
1616 if ($isediting) {
1617 switch ($completion) {
1618 case COMPLETION_TRACKING_MANUAL :
1619 $completionicon = 'manual-enabled'; break;
1620 case COMPLETION_TRACKING_AUTOMATIC :
1621 $completionicon = 'auto-enabled'; break;
1622 default: // wtf
1624 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1625 switch($completiondata->completionstate) {
1626 case COMPLETION_INCOMPLETE:
1627 $completionicon = 'manual-n'; break;
1628 case COMPLETION_COMPLETE:
1629 $completionicon = 'manual-y'; break;
1631 } else { // Automatic
1632 switch($completiondata->completionstate) {
1633 case COMPLETION_INCOMPLETE:
1634 $completionicon = 'auto-n'; break;
1635 case COMPLETION_COMPLETE:
1636 $completionicon = 'auto-y'; break;
1637 case COMPLETION_COMPLETE_PASS:
1638 $completionicon = 'auto-pass'; break;
1639 case COMPLETION_COMPLETE_FAIL:
1640 $completionicon = 'auto-fail'; break;
1643 if ($completionicon) {
1644 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1645 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1646 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1647 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1648 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1649 $newstate =
1650 $completiondata->completionstate==COMPLETION_COMPLETE
1651 ? COMPLETION_INCOMPLETE
1652 : COMPLETION_COMPLETE;
1653 // In manual mode the icon is a toggle form...
1655 // If this completion state is used by the
1656 // conditional activities system, we need to turn
1657 // off the JS.
1658 if (!empty($CFG->enableavailability) &&
1659 condition_info::completion_value_used_as_condition($course, $mod)) {
1660 $extraclass = ' preventjs';
1661 } else {
1662 $extraclass = '';
1664 echo html_writer::start_tag('form', array(
1665 'class' => 'togglecompletion' . $extraclass,
1666 'method' => 'post',
1667 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1668 echo html_writer::start_tag('div');
1669 echo html_writer::empty_tag('input', array(
1670 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1671 echo html_writer::empty_tag('input', array(
1672 'type' => 'hidden', 'name' => 'modulename',
1673 'value' => $mod->name));
1674 echo html_writer::empty_tag('input', array(
1675 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1676 echo html_writer::empty_tag('input', array(
1677 'type' => 'hidden', 'name' => 'completionstate',
1678 'value' => $newstate));
1679 echo html_writer::empty_tag('input', array(
1680 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle,
1681 'aria-live' => 'polite'));
1682 echo html_writer::end_tag('div');
1683 echo html_writer::end_tag('form');
1684 } else {
1685 // In auto mode, or when editing, the icon is just an image.
1686 echo html_writer::tag('span', html_writer::empty_tag('img', array(
1687 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgalt)),
1688 array('class' => 'autocompletion'));
1693 // If there is content AND a link, then display the content here
1694 // (AFTER any icons). Otherwise it was displayed before
1695 if (!empty($url)) {
1696 echo $contentpart;
1699 // Show availability information (for someone who isn't allowed to
1700 // see the activity itself, or for staff)
1701 if (!$mod->uservisible) {
1702 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1703 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1704 // Don't add availability information if user is not editing and activity is hidden.
1705 if ($mod->visible || $PAGE->user_is_editing()) {
1706 $hidinfoclass = '';
1707 if (!$mod->visible) {
1708 $hidinfoclass = 'hide';
1710 $ci = new condition_info($mod);
1711 $fullinfo = $ci->get_full_information();
1712 if($fullinfo) {
1713 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1714 ? 'userrestriction_visible'
1715 : 'userrestriction_hidden','condition',
1716 $fullinfo).'</div>';
1721 echo html_writer::end_tag('div');
1722 echo html_writer::end_tag('li')."\n";
1725 } elseif ($ismoving) {
1726 echo "<ul class=\"section\">\n";
1729 if ($ismoving) {
1730 echo '<li><a title="'.$strmovefull.'"'.
1731 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1732 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1733 ' alt="'.$strmovehere.'" /></a></li>
1736 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1737 echo "</ul><!--class='section'-->\n\n";
1742 * Prints the menus to add activities and resources.
1744 * @param stdClass $course The course
1745 * @param int $section relative section number (field course_sections.section)
1746 * @param null|array $modnames An array containing the list of modules and their names
1747 * if omitted will be taken from get_module_types_names()
1748 * @param bool $vertical Vertical orientation
1749 * @param bool $return Return the menus or send them to output
1750 * @param int $sectionreturn The section to link back to
1751 * @return void|string depending on $return
1753 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1754 global $CFG, $OUTPUT;
1756 if ($modnames === null) {
1757 $modnames = get_module_types_names();
1760 // check to see if user can add menus and there are modules to add
1761 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1762 || empty($modnames)) {
1763 if ($return) {
1764 return '';
1765 } else {
1766 return false;
1770 // Retrieve all modules with associated metadata
1771 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1773 // We'll sort resources and activities into two lists
1774 $resources = array();
1775 $activities = array();
1777 // We need to add the section section to the link for each module
1778 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1780 foreach ($modules as $module) {
1781 if (isset($module->types)) {
1782 // This module has a subtype
1783 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1784 $subtypes = array();
1785 foreach ($module->types as $subtype) {
1786 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1789 // Sort module subtypes into the list
1790 if (!empty($module->title)) {
1791 // This grouping has a name
1792 if ($module->archetype == MOD_CLASS_RESOURCE) {
1793 $resources[] = array($module->title=>$subtypes);
1794 } else {
1795 $activities[] = array($module->title=>$subtypes);
1797 } else {
1798 // This grouping does not have a name
1799 if ($module->archetype == MOD_CLASS_RESOURCE) {
1800 $resources = array_merge($resources, $subtypes);
1801 } else {
1802 $activities = array_merge($activities, $subtypes);
1805 } else {
1806 // This module has no subtypes
1807 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1808 $resources[$module->link . $sectionlink] = $module->title;
1809 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1810 // System modules cannot be added by user, do not add to dropdown
1811 } else {
1812 $activities[$module->link . $sectionlink] = $module->title;
1817 $straddactivity = get_string('addactivity');
1818 $straddresource = get_string('addresource');
1819 $sectionname = get_section_name($course, $section);
1820 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1821 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1823 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1825 if (!$vertical) {
1826 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1829 if (!empty($resources)) {
1830 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1831 $select->set_help_icon('resources');
1832 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1833 $output .= $OUTPUT->render($select);
1836 if (!empty($activities)) {
1837 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1838 $select->set_help_icon('activities');
1839 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1840 $output .= $OUTPUT->render($select);
1843 if (!$vertical) {
1844 $output .= html_writer::end_tag('div');
1847 $output .= html_writer::end_tag('div');
1849 if (course_ajax_enabled($course)) {
1850 $straddeither = get_string('addresourceoractivity');
1851 // The module chooser link
1852 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1853 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1854 $icon = $OUTPUT->pix_icon('t/add', '');
1855 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1856 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1857 $modchooser.= html_writer::end_tag('div');
1858 $modchooser.= html_writer::end_tag('div');
1860 // Wrap the normal output in a noscript div
1861 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1862 if ($usemodchooser) {
1863 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1864 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1865 } else {
1866 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1867 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1868 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1870 $output = $modchooser . $output;
1873 if ($return) {
1874 return $output;
1875 } else {
1876 echo $output;
1881 * Retrieve all metadata for the requested modules
1883 * @param object $course The Course
1884 * @param array $modnames An array containing the list of modules and their
1885 * names
1886 * @param int $sectionreturn The section to return to
1887 * @return array A list of stdClass objects containing metadata about each
1888 * module
1890 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1891 global $CFG, $OUTPUT;
1893 // get_module_metadata will be called once per section on the page and courses may show
1894 // different modules to one another
1895 static $modlist = array();
1896 if (!isset($modlist[$course->id])) {
1897 $modlist[$course->id] = array();
1900 $return = array();
1901 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1902 foreach($modnames as $modname => $modnamestr) {
1903 if (!course_allowed_module($course, $modname)) {
1904 continue;
1906 if (isset($modlist[$course->id][$modname])) {
1907 // This module is already cached
1908 $return[$modname] = $modlist[$course->id][$modname];
1909 continue;
1912 // Include the module lib
1913 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1914 if (!file_exists($libfile)) {
1915 continue;
1917 include_once($libfile);
1919 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1920 $gettypesfunc = $modname.'_get_types';
1921 if (function_exists($gettypesfunc)) {
1922 $types = $gettypesfunc();
1923 if (is_array($types) && count($types) > 0) {
1924 $group = new stdClass();
1925 $group->name = $modname;
1926 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1927 foreach($types as $type) {
1928 if ($type->typestr === '--') {
1929 continue;
1931 if (strpos($type->typestr, '--') === 0) {
1932 $group->title = str_replace('--', '', $type->typestr);
1933 continue;
1935 // Set the Sub Type metadata
1936 $subtype = new stdClass();
1937 $subtype->title = $type->typestr;
1938 $subtype->type = str_replace('&amp;', '&', $type->type);
1939 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1940 $subtype->archetype = $type->modclass;
1942 // The group archetype should match the subtype archetypes and all subtypes
1943 // should have the same archetype
1944 $group->archetype = $subtype->archetype;
1946 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1947 $subtype->help = get_string('help' . $subtype->name, $modname);
1949 $subtype->link = $urlbase . $subtype->type;
1950 $group->types[] = $subtype;
1952 $modlist[$course->id][$modname] = $group;
1954 } else {
1955 $module = new stdClass();
1956 $module->title = get_string('modulename', $modname);
1957 $module->name = $modname;
1958 $module->link = $urlbase . $modname;
1959 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1960 $sm = get_string_manager();
1961 if ($sm->string_exists('modulename_help', $modname)) {
1962 $module->help = get_string('modulename_help', $modname);
1963 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1964 $link = get_string('modulename_link', $modname);
1965 $linktext = get_string('morehelp');
1966 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1969 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1970 $modlist[$course->id][$modname] = $module;
1972 if (isset($modlist[$course->id][$modname])) {
1973 $return[$modname] = $modlist[$course->id][$modname];
1974 } else {
1975 debugging("Invalid module metadata configuration for {$modname}");
1979 return $return;
1983 * Return the course category context for the category with id $categoryid, except
1984 * that if $categoryid is 0, return the system context.
1986 * @param integer $categoryid a category id or 0.
1987 * @return object the corresponding context
1989 function get_category_or_system_context($categoryid) {
1990 if ($categoryid) {
1991 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1992 } else {
1993 return context_system::instance();
1998 * Gets the child categories of a given courses category. Uses a static cache
1999 * to make repeat calls efficient.
2001 * @param int $parentid the id of a course category.
2002 * @return array all the child course categories.
2004 function get_child_categories($parentid) {
2005 static $allcategories = null;
2007 // only fill in this variable the first time
2008 if (null == $allcategories) {
2009 $allcategories = array();
2011 $categories = get_categories();
2012 foreach ($categories as $category) {
2013 if (empty($allcategories[$category->parent])) {
2014 $allcategories[$category->parent] = array();
2016 $allcategories[$category->parent][] = $category;
2020 if (empty($allcategories[$parentid])) {
2021 return array();
2022 } else {
2023 return $allcategories[$parentid];
2028 * This function recursively travels the categories, building up a nice list
2029 * for display. It also makes an array that list all the parents for each
2030 * category.
2032 * For example, if you have a tree of categories like:
2033 * Miscellaneous (id = 1)
2034 * Subcategory (id = 2)
2035 * Sub-subcategory (id = 4)
2036 * Other category (id = 3)
2037 * Then after calling this function you will have
2038 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2039 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2040 * 3 => 'Other category');
2041 * $parents = array(2 => array(1), 4 => array(1, 2));
2043 * If you specify $requiredcapability, then only categories where the current
2044 * user has that capability will be added to $list, although all categories
2045 * will still be added to $parents, and if you only have $requiredcapability
2046 * in a child category, not the parent, then the child catgegory will still be
2047 * included.
2049 * If you specify the option $excluded, then that category, and all its children,
2050 * are omitted from the tree. This is useful when you are doing something like
2051 * moving categories, where you do not want to allow people to move a category
2052 * to be the child of itself.
2054 * @param array $list For output, accumulates an array categoryid => full category path name
2055 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2056 * @param string/array $requiredcapability if given, only categories where the current
2057 * user has this capability will be added to $list. Can also be an array of capabilities,
2058 * in which case they are all required.
2059 * @param integer $excludeid Omit this category and its children from the lists built.
2060 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2061 * @param string $path For internal use, as part of recursive calls.
2063 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2064 $excludeid = 0, $category = NULL, $path = "") {
2066 // initialize the arrays if needed
2067 if (!is_array($list)) {
2068 $list = array();
2070 if (!is_array($parents)) {
2071 $parents = array();
2074 if (empty($category)) {
2075 // Start at the top level.
2076 $category = new stdClass;
2077 $category->id = 0;
2078 } else {
2079 // This is the excluded category, don't include it.
2080 if ($excludeid > 0 && $excludeid == $category->id) {
2081 return;
2084 $context = context_coursecat::instance($category->id);
2085 $categoryname = format_string($category->name, true, array('context' => $context));
2087 // Update $path.
2088 if ($path) {
2089 $path = $path.' / '.$categoryname;
2090 } else {
2091 $path = $categoryname;
2094 // Add this category to $list, if the permissions check out.
2095 if (empty($requiredcapability)) {
2096 $list[$category->id] = $path;
2098 } else {
2099 $requiredcapability = (array)$requiredcapability;
2100 if (has_all_capabilities($requiredcapability, $context)) {
2101 $list[$category->id] = $path;
2106 // Add all the children recursively, while updating the parents array.
2107 if ($categories = get_child_categories($category->id)) {
2108 foreach ($categories as $cat) {
2109 if (!empty($category->id)) {
2110 if (isset($parents[$category->id])) {
2111 $parents[$cat->id] = $parents[$category->id];
2113 $parents[$cat->id][] = $category->id;
2115 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2121 * This function generates a structured array of courses and categories.
2123 * The depth of categories is limited by $CFG->maxcategorydepth however there
2124 * is no limit on the number of courses!
2126 * Suitable for use with the course renderers course_category_tree method:
2127 * $renderer = $PAGE->get_renderer('core','course');
2128 * echo $renderer->course_category_tree(get_course_category_tree());
2130 * @global moodle_database $DB
2131 * @param int $id
2132 * @param int $depth
2134 function get_course_category_tree($id = 0, $depth = 0) {
2135 global $DB, $CFG;
2136 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2137 $categories = get_child_categories($id);
2138 $categoryids = array();
2139 foreach ($categories as $key => &$category) {
2140 if (!$category->visible && !$viewhiddencats) {
2141 unset($categories[$key]);
2142 continue;
2144 $categoryids[$category->id] = $category;
2145 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2146 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2147 foreach ($subcategories as $subid=>$subcat) {
2148 $categoryids[$subid] = $subcat;
2150 $category->courses = array();
2154 if ($depth > 0) {
2155 // This is a recursive call so return the required array
2156 return array($categories, $categoryids);
2159 if (empty($categoryids)) {
2160 // No categories available (probably all hidden).
2161 return array();
2164 // The depth is 0 this function has just been called so we can finish it off
2166 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2167 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2168 $sql = "SELECT
2169 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2170 $ccselect
2171 FROM {course} c
2172 $ccjoin
2173 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2174 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2175 // loop throught them
2176 foreach ($courses as $course) {
2177 if ($course->id == SITEID) {
2178 continue;
2180 context_instance_preload($course);
2181 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2182 $categoryids[$course->category]->courses[$course->id] = $course;
2186 return $categories;
2190 * Recursive function to print out all the categories in a nice format
2191 * with or without courses included
2193 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2194 global $CFG;
2196 // maxcategorydepth == 0 meant no limit
2197 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2198 return;
2201 if (!$displaylist) {
2202 make_categories_list($displaylist, $parentslist);
2205 if ($category) {
2206 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2207 print_category_info($category, $depth, $showcourses);
2208 } else {
2209 return; // Don't bother printing children of invisible categories
2212 } else {
2213 $category = new stdClass();
2214 $category->id = "0";
2217 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2218 $countcats = count($categories);
2219 $count = 0;
2220 $first = true;
2221 $last = false;
2222 foreach ($categories as $cat) {
2223 $count++;
2224 if ($count == $countcats) {
2225 $last = true;
2227 $up = $first ? false : true;
2228 $down = $last ? false : true;
2229 $first = false;
2231 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2237 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2239 function make_categories_options() {
2240 make_categories_list($cats,$parents);
2241 foreach ($cats as $key => $value) {
2242 if (array_key_exists($key,$parents)) {
2243 if ($indent = count($parents[$key])) {
2244 for ($i = 0; $i < $indent; $i++) {
2245 $cats[$key] = '&nbsp;'.$cats[$key];
2250 return $cats;
2254 * Prints the category info in indented fashion
2255 * This function is only used by print_whole_category_list() above
2257 function print_category_info($category, $depth=0, $showcourses = false) {
2258 global $CFG, $DB, $OUTPUT;
2260 $strsummary = get_string('summary');
2262 $catlinkcss = null;
2263 if (!$category->visible) {
2264 $catlinkcss = array('class'=>'dimmed');
2266 static $coursecount = null;
2267 if (null === $coursecount) {
2268 // only need to check this once
2269 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2272 if ($showcourses and $coursecount) {
2273 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2274 } else {
2275 $catimage = "&nbsp;";
2278 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2279 $context = context_coursecat::instance($category->id);
2280 $fullname = format_string($category->name, true, array('context' => $context));
2282 if ($showcourses and $coursecount) {
2283 echo '<div class="categorylist clearfix">';
2284 $cat = '';
2285 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2286 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2287 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2289 $html = '';
2290 if ($depth > 0) {
2291 for ($i=0; $i< $depth; $i++) {
2292 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2293 $cat = '';
2295 } else {
2296 $html = $cat;
2298 echo html_writer::tag('div', $html, array('class'=>'category'));
2299 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2301 // does the depth exceed maxcategorydepth
2302 // maxcategorydepth == 0 or unset meant no limit
2303 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2304 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2305 foreach ($courses as $course) {
2306 $linkcss = null;
2307 if (!$course->visible) {
2308 $linkcss = array('class'=>'dimmed');
2311 $coursename = get_course_display_name_for_list($course);
2312 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2314 // print enrol info
2315 $courseicon = '';
2316 if ($icons = enrol_get_course_info_icons($course)) {
2317 foreach ($icons as $pix_icon) {
2318 $courseicon = $OUTPUT->render($pix_icon);
2322 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2324 if ($course->summary) {
2325 $link = new moodle_url('/course/info.php?id='.$course->id);
2326 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2327 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2328 array('title'=>$strsummary));
2330 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2333 $html = '';
2334 for ($i=0; $i <= $depth; $i++) {
2335 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2336 $coursecontent = '';
2338 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2341 echo '</div>';
2342 } else {
2343 echo '<div class="categorylist">';
2344 $html = '';
2345 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2346 if (count($courses) > 0) {
2347 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2350 if ($depth > 0) {
2351 for ($i=0; $i< $depth; $i++) {
2352 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2353 $cat = '';
2355 } else {
2356 $html = $cat;
2359 echo html_writer::tag('div', $html, array('class'=>'category'));
2360 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2361 echo '</div>';
2366 * Print the buttons relating to course requests.
2368 * @param object $systemcontext the system context.
2370 function print_course_request_buttons($systemcontext) {
2371 global $CFG, $DB, $OUTPUT;
2372 if (empty($CFG->enablecourserequests)) {
2373 return;
2375 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2376 /// Print a button to request a new course
2377 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2379 /// Print a button to manage pending requests
2380 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2381 $disabled = !$DB->record_exists('course_request', array());
2382 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2387 * Does the user have permission to edit things in this category?
2389 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2390 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2392 function can_edit_in_category($categoryid = 0) {
2393 $context = get_category_or_system_context($categoryid);
2394 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2398 * Prints the turn editing on/off button on course/index.php or course/category.php.
2400 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2401 * @return string HTML of the editing button, or empty string, if this user is not allowed
2402 * to see it.
2404 function update_category_button($categoryid = 0) {
2405 global $CFG, $PAGE, $OUTPUT;
2407 // Check permissions.
2408 if (!can_edit_in_category($categoryid)) {
2409 return '';
2412 // Work out the appropriate action.
2413 if ($PAGE->user_is_editing()) {
2414 $label = get_string('turneditingoff');
2415 $edit = 'off';
2416 } else {
2417 $label = get_string('turneditingon');
2418 $edit = 'on';
2421 // Generate the button HTML.
2422 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2423 if ($categoryid) {
2424 $options['id'] = $categoryid;
2425 $page = 'category.php';
2426 } else {
2427 $page = 'index.php';
2429 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2433 * Print courses in category. If category is 0 then all courses are printed.
2434 * @param int|stdClass $category category object or id.
2435 * @return bool true if courses found and printed, else false.
2437 function print_courses($category) {
2438 global $CFG, $OUTPUT;
2440 if (!is_object($category) && $category==0) {
2441 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2442 if (is_array($categories) && count($categories) == 1) {
2443 $category = array_shift($categories);
2444 $courses = get_courses_wmanagers($category->id,
2445 'c.sortorder ASC',
2446 array('summary','summaryformat'));
2447 } else {
2448 $courses = get_courses_wmanagers('all',
2449 'c.sortorder ASC',
2450 array('summary','summaryformat'));
2452 unset($categories);
2453 } else {
2454 $courses = get_courses_wmanagers($category->id,
2455 'c.sortorder ASC',
2456 array('summary','summaryformat'));
2459 if ($courses) {
2460 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2461 foreach ($courses as $course) {
2462 $coursecontext = context_course::instance($course->id);
2463 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2464 echo html_writer::start_tag('li');
2465 print_course($course);
2466 echo html_writer::end_tag('li');
2469 echo html_writer::end_tag('ul');
2470 } else {
2471 echo $OUTPUT->heading(get_string("nocoursesyet"));
2472 $context = context_system::instance();
2473 if (has_capability('moodle/course:create', $context)) {
2474 $options = array();
2475 if (!empty($category->id)) {
2476 $options['category'] = $category->id;
2477 } else {
2478 $options['category'] = $CFG->defaultrequestcategory;
2480 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2481 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2482 echo html_writer::end_tag('div');
2483 return false;
2486 return true;
2490 * Print a description of a course, suitable for browsing in a list.
2492 * @param object $course the course object.
2493 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2495 function print_course($course, $highlightterms = '') {
2496 global $CFG, $USER, $DB, $OUTPUT;
2498 $context = context_course::instance($course->id);
2500 // Rewrite file URLs so that they are correct
2501 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2503 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2504 echo html_writer::start_tag('div', array('class'=>'info'));
2505 echo html_writer::start_tag('h3', array('class'=>'name'));
2507 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2509 $coursename = get_course_display_name_for_list($course);
2510 $linktext = highlight($highlightterms, format_string($coursename));
2511 $linkparams = array('title'=>get_string('entercourse'));
2512 if (empty($course->visible)) {
2513 $linkparams['class'] = 'dimmed';
2515 echo html_writer::link($linkhref, $linktext, $linkparams);
2516 echo html_writer::end_tag('h3');
2518 /// first find all roles that are supposed to be displayed
2519 if (!empty($CFG->coursecontact)) {
2520 $managerroles = explode(',', $CFG->coursecontact);
2521 $rusers = array();
2523 if (!isset($course->managers)) {
2524 list($sort, $sortparams) = users_order_by_sql('u');
2525 $rusers = get_role_users($managerroles, $context, true,
2526 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2527 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2528 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2529 } else {
2530 // use the managers array if we have it for perf reasosn
2531 // populate the datastructure like output of get_role_users();
2532 foreach ($course->managers as $manager) {
2533 $user = clone($manager->user);
2534 $user->roleid = $manager->roleid;
2535 $user->rolename = $manager->rolename;
2536 $user->roleshortname = $manager->roleshortname;
2537 $user->rolecoursealias = $manager->rolecoursealias;
2538 $rusers[$user->id] = $user;
2542 $namesarray = array();
2543 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2544 foreach ($rusers as $ra) {
2545 if (isset($namesarray[$ra->id])) {
2546 // only display a user once with the higest sortorder role
2547 continue;
2550 $role = new stdClass();
2551 $role->id = $ra->roleid;
2552 $role->name = $ra->rolename;
2553 $role->shortname = $ra->roleshortname;
2554 $role->coursealias = $ra->rolecoursealias;
2555 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2557 $fullname = fullname($ra, $canviewfullnames);
2558 $namesarray[$ra->id] = $rolename.': '.
2559 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2562 if (!empty($namesarray)) {
2563 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2564 foreach ($namesarray as $name) {
2565 echo html_writer::tag('li', $name);
2567 echo html_writer::end_tag('ul');
2570 echo html_writer::end_tag('div'); // End of info div
2572 echo html_writer::start_tag('div', array('class'=>'summary'));
2573 $options = new stdClass();
2574 $options->noclean = true;
2575 $options->para = false;
2576 $options->overflowdiv = true;
2577 if (!isset($course->summaryformat)) {
2578 $course->summaryformat = FORMAT_MOODLE;
2580 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2581 if ($icons = enrol_get_course_info_icons($course)) {
2582 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2583 foreach ($icons as $icon) {
2584 $icon->attributes["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
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" 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" 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 $cmid = $DB->insert_record("course_modules", $mod);
2757 rebuild_course_cache($mod->course, true);
2758 return $cmid;
2762 * Creates missing course section(s) and rebuilds course cache
2764 * @param int|stdClass $courseorid course id or course object
2765 * @param int|array $sections list of relative section numbers to create
2766 * @return bool if there were any sections created
2768 function course_create_sections_if_missing($courseorid, $sections) {
2769 global $DB;
2770 if (!is_array($sections)) {
2771 $sections = array($sections);
2773 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2774 if (is_object($courseorid)) {
2775 $courseorid = $courseorid->id;
2777 $coursechanged = false;
2778 foreach ($sections as $sectionnum) {
2779 if (!in_array($sectionnum, $existing)) {
2780 $cw = new stdClass();
2781 $cw->course = $courseorid;
2782 $cw->section = $sectionnum;
2783 $cw->summary = '';
2784 $cw->summaryformat = FORMAT_HTML;
2785 $cw->sequence = '';
2786 $id = $DB->insert_record("course_sections", $cw);
2787 $coursechanged = true;
2790 if ($coursechanged) {
2791 rebuild_course_cache($courseorid, true);
2793 return $coursechanged;
2797 * Adds an existing module to the section
2799 * Updates both tables {course_sections} and {course_modules}
2801 * @param int|stdClass $courseorid course id or course object
2802 * @param int $cmid id of the module already existing in course_modules table
2803 * @param int $sectionnum relative number of the section (field course_sections.section)
2804 * If section does not exist it will be created
2805 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2806 * before which the module needs to be included. Null for inserting in the
2807 * end of the section
2808 * @return int The course_sections ID where the module is inserted
2810 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2811 global $DB, $COURSE;
2812 if (is_object($beforemod)) {
2813 $beforemod = $beforemod->id;
2815 if (is_object($courseorid)) {
2816 $courseid = $courseorid->id;
2817 } else {
2818 $courseid = $courseorid;
2820 course_create_sections_if_missing($courseorid, $sectionnum);
2821 // Do not try to use modinfo here, there is no guarantee it is valid!
2822 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
2823 $modarray = explode(",", trim($section->sequence));
2824 if (empty($section->sequence)) {
2825 $newsequence = "$cmid";
2826 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2827 $insertarray = array($cmid, $beforemod);
2828 array_splice($modarray, $key[0], 1, $insertarray);
2829 $newsequence = implode(",", $modarray);
2830 } else {
2831 $newsequence = "$section->sequence,$cmid";
2833 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2834 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
2835 if (is_object($courseorid)) {
2836 rebuild_course_cache($courseorid->id, true);
2837 } else {
2838 rebuild_course_cache($courseorid, true);
2840 return $section->id; // Return course_sections ID that was used.
2843 function set_coursemodule_groupmode($id, $groupmode) {
2844 global $DB;
2845 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2846 if ($cm->groupmode != $groupmode) {
2847 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2848 rebuild_course_cache($cm->course, true);
2850 return ($cm->groupmode != $groupmode);
2853 function set_coursemodule_idnumber($id, $idnumber) {
2854 global $DB;
2855 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2856 if ($cm->idnumber != $idnumber) {
2857 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2858 rebuild_course_cache($cm->course, true);
2860 return ($cm->idnumber != $idnumber);
2864 * Set the visibility of a module and inherent properties.
2866 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2867 * has been moved to {@link set_section_visible()} which was the only place from which
2868 * the parameter was used.
2870 * @param int $id of the module
2871 * @param int $visible state of the module
2872 * @return bool false when the module was not found, true otherwise
2874 function set_coursemodule_visible($id, $visible) {
2875 global $DB, $CFG;
2876 require_once($CFG->libdir.'/gradelib.php');
2878 // Trigger developer's attention when using the previously removed argument.
2879 if (func_num_args() > 2) {
2880 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2881 has been removed.', DEBUG_DEVELOPER);
2884 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2885 return false;
2888 // Create events and propagate visibility to associated grade items if the value has changed.
2889 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
2890 if ($cm->visible == $visible) {
2891 return true;
2894 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2895 return false;
2897 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2898 foreach($events as $event) {
2899 if ($visible) {
2900 show_event($event);
2901 } else {
2902 hide_event($event);
2907 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2908 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2909 if ($grade_items) {
2910 foreach ($grade_items as $grade_item) {
2911 $grade_item->set_hidden(!$visible);
2915 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2916 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2917 $cminfo = new stdClass();
2918 $cminfo->id = $id;
2919 $cminfo->visible = $visible;
2920 $cminfo->visibleold = $visible;
2921 $DB->update_record('course_modules', $cminfo);
2923 rebuild_course_cache($cm->course, true);
2924 return true;
2928 * Delete a course module and any associated data at the course level (events)
2929 * Until 1.5 this function simply marked a deleted flag ... now it
2930 * deletes it completely.
2933 function delete_course_module($id) {
2934 global $CFG, $DB;
2935 require_once($CFG->libdir.'/gradelib.php');
2936 require_once($CFG->dirroot.'/blog/lib.php');
2938 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2939 return true;
2941 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2942 //delete events from calendar
2943 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2944 foreach($events as $event) {
2945 delete_event($event->id);
2948 //delete grade items, outcome items and grades attached to modules
2949 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2950 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2951 foreach ($grade_items as $grade_item) {
2952 $grade_item->delete('moddelete');
2955 // Delete completion and availability data; it is better to do this even if the
2956 // features are not turned on, in case they were turned on previously (these will be
2957 // very quick on an empty table)
2958 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2959 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2960 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2961 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2962 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2964 delete_context(CONTEXT_MODULE, $cm->id);
2965 $DB->delete_records('course_modules', array('id'=>$cm->id));
2966 rebuild_course_cache($cm->course, true);
2967 return true;
2970 function delete_mod_from_section($modid, $sectionid) {
2971 global $DB;
2973 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2975 $modarray = explode(",", $section->sequence);
2977 if ($key = array_keys ($modarray, $modid)) {
2978 array_splice($modarray, $key[0], 1);
2979 $newsequence = implode(",", $modarray);
2980 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2981 rebuild_course_cache($section->course, true);
2982 return true;
2983 } else {
2984 return false;
2988 return false;
2992 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2994 * @param object $course course object
2995 * @param int $section Section number (not id!!!)
2996 * @param int $move (-1 or 1)
2997 * @return boolean true if section moved successfully
2998 * @todo MDL-33379 remove this function in 2.5
3000 function move_section($course, $section, $move) {
3001 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
3003 /// Moves a whole course section up and down within the course
3004 global $USER;
3006 if (!$move) {
3007 return true;
3010 $sectiondest = $section + $move;
3012 // compartibility with course formats using field 'numsections'
3013 $courseformatoptions = course_get_format($course)->get_format_options();
3014 if (array_key_exists('numsections', $courseformatoptions) &&
3015 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
3016 return false;
3019 $retval = move_section_to($course, $section, $sectiondest);
3020 return $retval;
3024 * Moves a section within a course, from a position to another.
3025 * Be very careful: $section and $destination refer to section number,
3026 * not id!.
3028 * @param object $course
3029 * @param int $section Section number (not id!!!)
3030 * @param int $destination
3031 * @return boolean Result
3033 function move_section_to($course, $section, $destination) {
3034 /// Moves a whole course section up and down within the course
3035 global $USER, $DB;
3037 if (!$destination && $destination != 0) {
3038 return true;
3041 // compartibility with course formats using field 'numsections'
3042 $courseformatoptions = course_get_format($course)->get_format_options();
3043 if ((array_key_exists('numsections', $courseformatoptions) &&
3044 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3045 return false;
3048 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3049 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3050 'section ASC, id ASC', 'id, section')) {
3051 return false;
3054 $movedsections = reorder_sections($sections, $section, $destination);
3056 // Update all sections. Do this in 2 steps to avoid breaking database
3057 // uniqueness constraint
3058 $transaction = $DB->start_delegated_transaction();
3059 foreach ($movedsections as $id => $position) {
3060 if ($sections[$id] !== $position) {
3061 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3064 foreach ($movedsections as $id => $position) {
3065 if ($sections[$id] !== $position) {
3066 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3070 // If we move the highlighted section itself, then just highlight the destination.
3071 // Adjust the higlighted section location if we move something over it either direction.
3072 if ($section == $course->marker) {
3073 course_set_marker($course->id, $destination);
3074 } elseif ($section > $course->marker && $course->marker >= $destination) {
3075 course_set_marker($course->id, $course->marker+1);
3076 } elseif ($section < $course->marker && $course->marker <= $destination) {
3077 course_set_marker($course->id, $course->marker-1);
3080 $transaction->allow_commit();
3081 rebuild_course_cache($course->id, true);
3082 return true;
3086 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3087 * an original position number and a target position number, rebuilds the array so that the
3088 * move is made without any duplication of section positions.
3089 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3090 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3092 * @param array $sections
3093 * @param int $origin_position
3094 * @param int $target_position
3095 * @return array
3097 function reorder_sections($sections, $origin_position, $target_position) {
3098 if (!is_array($sections)) {
3099 return false;
3102 // We can't move section position 0
3103 if ($origin_position < 1) {
3104 echo "We can't move section position 0";
3105 return false;
3108 // Locate origin section in sections array
3109 if (!$origin_key = array_search($origin_position, $sections)) {
3110 echo "searched position not in sections array";
3111 return false; // searched position not in sections array
3114 // Extract origin section
3115 $origin_section = $sections[$origin_key];
3116 unset($sections[$origin_key]);
3118 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3119 $found = false;
3120 $append_array = array();
3121 foreach ($sections as $id => $position) {
3122 if ($found) {
3123 $append_array[$id] = $position;
3124 unset($sections[$id]);
3126 if ($position == $target_position) {
3127 if ($target_position < $origin_position) {
3128 $append_array[$id] = $position;
3129 unset($sections[$id]);
3131 $found = true;
3135 // Append moved section
3136 $sections[$origin_key] = $origin_section;
3138 // Append rest of array (if applicable)
3139 if (!empty($append_array)) {
3140 foreach ($append_array as $id => $position) {
3141 $sections[$id] = $position;
3145 // Renumber positions
3146 $position = 0;
3147 foreach ($sections as $id => $p) {
3148 $sections[$id] = $position;
3149 $position++;
3152 return $sections;
3157 * Move the module object $mod to the specified $section
3158 * If $beforemod exists then that is the module
3159 * before which $modid should be inserted
3160 * All parameters are objects
3162 function moveto_module($mod, $section, $beforemod=NULL) {
3163 global $OUTPUT, $DB;
3165 /// Remove original module from original section
3166 if (! delete_mod_from_section($mod->id, $mod->section)) {
3167 echo $OUTPUT->notification("Could not delete module from existing section");
3170 // if moving to a hidden section then hide module
3171 if ($mod->section != $section->id) {
3172 if (!$section->visible && $mod->visible) {
3173 // Set this in the object because it is sent as a response to ajax calls.
3174 $mod->visible = 0;
3175 set_coursemodule_visible($mod->id, 0);
3176 // Set visibleold to 1 so module will be visible when section is made visible.
3177 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
3179 if ($section->visible && !$mod->visible) {
3180 set_coursemodule_visible($mod->id, $mod->visibleold);
3181 // Set this in the object because it is sent as a response to ajax calls.
3182 $mod->visible = $mod->visibleold;
3186 /// Add the module into the new section
3187 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3188 return true;
3192 * Produces the editing buttons for a module
3194 * @global core_renderer $OUTPUT
3195 * @staticvar type $str
3196 * @param stdClass $mod The module to produce editing buttons for
3197 * @param bool $absolute_ignored ignored - all links are absolute
3198 * @param bool $moveselect If true a move seleciton process is used (default true)
3199 * @param int $indent The current indenting
3200 * @param int $section The section to link back to
3201 * @return string XHTML for the editing buttons
3203 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3204 global $CFG, $OUTPUT, $COURSE;
3206 static $str;
3208 $coursecontext = context_course::instance($mod->course);
3209 $modcontext = context_module::instance($mod->id);
3211 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3212 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3214 // no permission to edit anything
3215 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3216 return false;
3219 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3221 if (!isset($str)) {
3222 $str = new stdClass;
3223 $str->assign = get_string("assignroles", 'role');
3224 $str->delete = get_string("delete");
3225 $str->move = get_string("move");
3226 $str->moveup = get_string("moveup");
3227 $str->movedown = get_string("movedown");
3228 $str->moveright = get_string("moveright");
3229 $str->moveleft = get_string("moveleft");
3230 $str->update = get_string("update");
3231 $str->duplicate = get_string("duplicate");
3232 $str->hide = get_string("hide");
3233 $str->show = get_string("show");
3234 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3235 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3236 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3237 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3238 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3239 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3240 $str->edittitle = get_string('edittitle', 'moodle');
3243 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3245 if ($section !== null) {
3246 $baseurl->param('sr', $section);
3248 $actions = array();
3250 // AJAX edit title
3251 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3252 $actions[] = new action_link(
3253 new moodle_url($baseurl, array('update' => $mod->id)),
3254 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3255 null,
3256 array('class' => 'editing_title', 'title' => $str->edittitle)
3260 // leftright
3261 if ($hasmanageactivities) {
3262 if (right_to_left()) { // Exchange arrows on RTL
3263 $rightarrow = 't/left';
3264 $leftarrow = 't/right';
3265 } else {
3266 $rightarrow = 't/right';
3267 $leftarrow = 't/left';
3270 if ($indent > 0) {
3271 $actions[] = new action_link(
3272 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3273 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3274 null,
3275 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3278 if ($indent >= 0) {
3279 $actions[] = new action_link(
3280 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3281 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3282 null,
3283 array('class' => 'editing_moveright', 'title' => $str->moveright)
3288 // move
3289 if ($hasmanageactivities) {
3290 if ($moveselect) {
3291 $actions[] = new action_link(
3292 new moodle_url($baseurl, array('copy' => $mod->id)),
3293 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3294 null,
3295 array('class' => 'editing_move', 'title' => $str->move)
3297 } else {
3298 $actions[] = new action_link(
3299 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3300 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3301 null,
3302 array('class' => 'editing_moveup', 'title' => $str->moveup)
3304 $actions[] = new action_link(
3305 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3306 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3307 null,
3308 array('class' => 'editing_movedown', 'title' => $str->movedown)
3313 // Update
3314 if ($hasmanageactivities) {
3315 $actions[] = new action_link(
3316 new moodle_url($baseurl, array('update' => $mod->id)),
3317 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3318 null,
3319 array('class' => 'editing_update', 'title' => $str->update)
3323 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3324 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3325 $actions[] = new action_link(
3326 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3327 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3328 null,
3329 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3333 // Delete
3334 if ($hasmanageactivities) {
3335 $actions[] = new action_link(
3336 new moodle_url($baseurl, array('delete' => $mod->id)),
3337 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3338 null,
3339 array('class' => 'editing_delete', 'title' => $str->delete)
3343 // hideshow
3344 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3345 if ($mod->visible) {
3346 $actions[] = new action_link(
3347 new moodle_url($baseurl, array('hide' => $mod->id)),
3348 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3349 null,
3350 array('class' => 'editing_hide', 'title' => $str->hide)
3352 } else {
3353 $actions[] = new action_link(
3354 new moodle_url($baseurl, array('show' => $mod->id)),
3355 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3356 null,
3357 array('class' => 'editing_show', 'title' => $str->show)
3362 // groupmode
3363 if ($hasmanageactivities and $mod->groupmode !== false) {
3364 if ($mod->groupmode == SEPARATEGROUPS) {
3365 $groupmode = 0;
3366 $grouptitle = $str->groupsseparate;
3367 $forcedgrouptitle = $str->forcedgroupsseparate;
3368 $groupclass = 'editing_groupsseparate';
3369 $groupimage = 't/groups';
3370 } else if ($mod->groupmode == VISIBLEGROUPS) {
3371 $groupmode = 1;
3372 $grouptitle = $str->groupsvisible;
3373 $forcedgrouptitle = $str->forcedgroupsvisible;
3374 $groupclass = 'editing_groupsvisible';
3375 $groupimage = 't/groupv';
3376 } else {
3377 $groupmode = 2;
3378 $grouptitle = $str->groupsnone;
3379 $forcedgrouptitle = $str->forcedgroupsnone;
3380 $groupclass = 'editing_groupsnone';
3381 $groupimage = 't/groupn';
3383 if ($mod->groupmodelink) {
3384 $actions[] = new action_link(
3385 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3386 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3387 null,
3388 array('class' => $groupclass, 'title' => $grouptitle)
3390 } else {
3391 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3395 // Assign
3396 if (has_capability('moodle/role:assign', $modcontext)){
3397 $actions[] = new action_link(
3398 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3399 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3400 null,
3401 array('class' => 'editing_assign', 'title' => $str->assign)
3405 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
3406 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
3407 // the course page HTML will allow this to be removed.
3408 $output = ' ' . html_writer::start_tag('span', array('class' => 'commands'));
3409 foreach ($actions as $action) {
3410 if ($action instanceof renderable) {
3411 $output .= $OUTPUT->render($action);
3412 } else {
3413 $output .= $action;
3416 $output .= html_writer::end_tag('span');
3417 return $output;
3421 * given a course object with shortname & fullname, this function will
3422 * truncate the the number of chars allowed and add ... if it was too long
3424 function course_format_name ($course,$max=100) {
3426 $context = context_course::instance($course->id);
3427 $shortname = format_string($course->shortname, true, array('context' => $context));
3428 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3429 $str = $shortname.': '. $fullname;
3430 if (textlib::strlen($str) <= $max) {
3431 return $str;
3433 else {
3434 return textlib::substr($str,0,$max-3).'...';
3439 * Is the user allowed to add this type of module to this course?
3440 * @param object $course the course settings. Only $course->id is used.
3441 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3442 * @return bool whether the current user is allowed to add this type of module to this course.
3444 function course_allowed_module($course, $modname) {
3445 if (is_numeric($modname)) {
3446 throw new coding_exception('Function course_allowed_module no longer
3447 supports numeric module ids. Please update your code to pass the module name.');
3450 $capability = 'mod/' . $modname . ':addinstance';
3451 if (!get_capability_info($capability)) {
3452 // Debug warning that the capability does not exist, but no more than once per page.
3453 static $warned = array();
3454 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3455 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3456 debugging('The module ' . $modname . ' does not define the standard capability ' .
3457 $capability , DEBUG_DEVELOPER);
3458 $warned[$modname] = 1;
3461 // If the capability does not exist, the module can always be added.
3462 return true;
3465 $coursecontext = context_course::instance($course->id);
3466 return has_capability($capability, $coursecontext);
3470 * Recursively delete category including all subcategories and courses.
3471 * @param stdClass $category
3472 * @param boolean $showfeedback display some notices
3473 * @return array return deleted courses
3475 function category_delete_full($category, $showfeedback=true) {
3476 global $CFG, $DB;
3477 require_once($CFG->libdir.'/gradelib.php');
3478 require_once($CFG->libdir.'/questionlib.php');
3479 require_once($CFG->dirroot.'/cohort/lib.php');
3481 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3482 foreach ($children as $childcat) {
3483 category_delete_full($childcat, $showfeedback);
3487 $deletedcourses = array();
3488 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3489 foreach ($courses as $course) {
3490 if (!delete_course($course, false)) {
3491 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3493 $deletedcourses[] = $course;
3497 // move or delete cohorts in this context
3498 cohort_delete_category($category);
3500 // now delete anything that may depend on course category context
3501 grade_course_category_delete($category->id, 0, $showfeedback);
3502 if (!question_delete_course_category($category, 0, $showfeedback)) {
3503 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3506 // finally delete the category and it's context
3507 $DB->delete_records('course_categories', array('id'=>$category->id));
3508 delete_context(CONTEXT_COURSECAT, $category->id);
3509 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3511 events_trigger('course_category_deleted', $category);
3513 return $deletedcourses;
3517 * Delete category, but move contents to another category.
3518 * @param object $ccategory
3519 * @param int $newparentid category id
3520 * @return bool status
3522 function category_delete_move($category, $newparentid, $showfeedback=true) {
3523 global $CFG, $DB, $OUTPUT;
3524 require_once($CFG->libdir.'/gradelib.php');
3525 require_once($CFG->libdir.'/questionlib.php');
3526 require_once($CFG->dirroot.'/cohort/lib.php');
3528 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3529 return false;
3532 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3533 foreach ($children as $childcat) {
3534 move_category($childcat, $newparentcat);
3538 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3539 if (!move_courses(array_keys($courses), $newparentid)) {
3540 if ($showfeedback) {
3541 echo $OUTPUT->notification("Error moving courses");
3543 return false;
3545 if ($showfeedback) {
3546 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3550 // move or delete cohorts in this context
3551 cohort_delete_category($category);
3553 // now delete anything that may depend on course category context
3554 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3555 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3556 if ($showfeedback) {
3557 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3559 return false;
3562 // finally delete the category and it's context
3563 $DB->delete_records('course_categories', array('id'=>$category->id));
3564 delete_context(CONTEXT_COURSECAT, $category->id);
3565 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3567 events_trigger('course_category_deleted', $category);
3569 if ($showfeedback) {
3570 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3572 return true;
3576 * Efficiently moves many courses around while maintaining
3577 * sortorder in order.
3579 * @param array $courseids is an array of course ids
3580 * @param int $categoryid
3581 * @return bool success
3583 function move_courses($courseids, $categoryid) {
3584 global $CFG, $DB, $OUTPUT;
3586 if (empty($courseids)) {
3587 // nothing to do
3588 return;
3591 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3592 return false;
3595 $courseids = array_reverse($courseids);
3596 $newparent = context_coursecat::instance($category->id);
3597 $i = 1;
3599 foreach ($courseids as $courseid) {
3600 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3601 $course = new stdClass();
3602 $course->id = $courseid;
3603 $course->category = $category->id;
3604 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3605 if ($category->visible == 0) {
3606 // hide the course when moving into hidden category,
3607 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3608 $course->visible = 0;
3611 $DB->update_record('course', $course);
3612 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
3614 $context = context_course::instance($course->id);
3615 context_moved($context, $newparent);
3618 fix_course_sortorder();
3620 return true;
3624 * Hide course category and child course and subcategories
3625 * @param stdClass $category
3626 * @return void
3628 function course_category_hide($category) {
3629 global $DB;
3631 $category->visible = 0;
3632 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3633 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3634 $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
3635 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3636 // get all child categories and hide too
3637 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3638 foreach ($subcats as $cat) {
3639 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3640 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3641 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3642 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3645 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$category->id", $category->id);
3649 * Show course category and child course and subcategories
3650 * @param stdClass $category
3651 * @return void
3653 function course_category_show($category) {
3654 global $DB;
3656 $category->visible = 1;
3657 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3658 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3659 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3660 // get all child categories and unhide too
3661 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3662 foreach ($subcats as $cat) {
3663 if ($cat->visibleold) {
3664 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3666 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3669 add_to_log(SITEID, "category", "show", "editcategory.php?id=$category->id", $category->id);
3673 * Efficiently moves a category - NOTE that this can have
3674 * a huge impact access-control-wise...
3676 function move_category($category, $newparentcat) {
3677 global $CFG, $DB;
3679 $context = context_coursecat::instance($category->id);
3681 $hidecat = false;
3682 if (empty($newparentcat->id)) {
3683 $DB->set_field('course_categories', 'parent', 0, array('id' => $category->id));
3684 $newparent = context_system::instance();
3685 } else {
3686 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $category->id));
3687 $newparent = context_coursecat::instance($newparentcat->id);
3689 if (!$newparentcat->visible and $category->visible) {
3690 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3691 $hidecat = true;
3695 context_moved($context, $newparent);
3697 // now make it last in new category
3698 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3700 // Log action.
3701 add_to_log(SITEID, "category", "move", "editcategory.php?id=$category->id", $category->id);
3703 // and fix the sortorders
3704 fix_course_sortorder();
3706 if ($hidecat) {
3707 course_category_hide($category);
3712 * Returns the display name of the given section that the course prefers
3714 * Implementation of this function is provided by course format
3715 * @see format_base::get_section_name()
3717 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
3718 * @param int|stdClass $section Section object from database or just field course_sections.section
3719 * @return string Display name that the course format prefers, e.g. "Week 2"
3721 function get_section_name($courseorid, $section) {
3722 return course_get_format($courseorid)->get_section_name($section);
3726 * Tells if current course format uses sections
3728 * @param string $format Course format ID e.g. 'weeks' $course->format
3729 * @return bool
3731 function course_format_uses_sections($format) {
3732 $course = new stdClass();
3733 $course->format = $format;
3734 return course_get_format($course)->uses_sections();
3738 * Returns the information about the ajax support in the given source format
3740 * The returned object's property (boolean)capable indicates that
3741 * the course format supports Moodle course ajax features.
3742 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3744 * @param string $format
3745 * @return stdClass
3747 function course_format_ajax_support($format) {
3748 $course = new stdClass();
3749 $course->format = $format;
3750 return course_get_format($course)->supports_ajax();
3754 * Can the current user delete this course?
3755 * Course creators have exception,
3756 * 1 day after the creation they can sill delete the course.
3757 * @param int $courseid
3758 * @return boolean
3760 function can_delete_course($courseid) {
3761 global $USER, $DB;
3763 $context = context_course::instance($courseid);
3765 if (has_capability('moodle/course:delete', $context)) {
3766 return true;
3769 // hack: now try to find out if creator created this course recently (1 day)
3770 if (!has_capability('moodle/course:create', $context)) {
3771 return false;
3774 $since = time() - 60*60*24;
3776 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3777 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3779 return $DB->record_exists_select('log', $select, $params);
3783 * Save the Your name for 'Some role' strings.
3785 * @param integer $courseid the id of this course.
3786 * @param array $data the data that came from the course settings form.
3788 function save_local_role_names($courseid, $data) {
3789 global $DB;
3790 $context = context_course::instance($courseid);
3792 foreach ($data as $fieldname => $value) {
3793 if (strpos($fieldname, 'role_') !== 0) {
3794 continue;
3796 list($ignored, $roleid) = explode('_', $fieldname);
3798 // make up our mind whether we want to delete, update or insert
3799 if (!$value) {
3800 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3802 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3803 $rolename->name = $value;
3804 $DB->update_record('role_names', $rolename);
3806 } else {
3807 $rolename = new stdClass;
3808 $rolename->contextid = $context->id;
3809 $rolename->roleid = $roleid;
3810 $rolename->name = $value;
3811 $DB->insert_record('role_names', $rolename);
3817 * Create a course and either return a $course object
3819 * Please note this functions does not verify any access control,
3820 * the calling code is responsible for all validation (usually it is the form definition).
3822 * @param array $editoroptions course description editor options
3823 * @param object $data - all the data needed for an entry in the 'course' table
3824 * @return object new course instance
3826 function create_course($data, $editoroptions = NULL) {
3827 global $CFG, $DB;
3829 //check the categoryid - must be given for all new courses
3830 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3832 //check if the shortname already exist
3833 if (!empty($data->shortname)) {
3834 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3835 throw new moodle_exception('shortnametaken');
3839 //check if the id number already exist
3840 if (!empty($data->idnumber)) {
3841 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3842 throw new moodle_exception('idnumbertaken');
3846 $data->timecreated = time();
3847 $data->timemodified = $data->timecreated;
3849 // place at beginning of any category
3850 $data->sortorder = 0;
3852 if ($editoroptions) {
3853 // summary text is updated later, we need context to store the files first
3854 $data->summary = '';
3855 $data->summary_format = FORMAT_HTML;
3858 if (!isset($data->visible)) {
3859 // data not from form, add missing visibility info
3860 $data->visible = $category->visible;
3862 $data->visibleold = $data->visible;
3864 $newcourseid = $DB->insert_record('course', $data);
3865 $context = context_course::instance($newcourseid, MUST_EXIST);
3867 if ($editoroptions) {
3868 // Save the files used in the summary editor and store
3869 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3870 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3871 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3874 // update course format options
3875 course_get_format($newcourseid)->update_course_format_options($data);
3877 $course = course_get_format($newcourseid)->get_course();
3879 // Setup the blocks
3880 blocks_add_default_course_blocks($course);
3882 // Create a default section.
3883 course_create_sections_if_missing($course, 0);
3885 fix_course_sortorder();
3887 // new context created - better mark it as dirty
3888 mark_context_dirty($context->path);
3890 // Save any custom role names.
3891 save_local_role_names($course->id, (array)$data);
3893 // set up enrolments
3894 enrol_course_updated(true, $course, $data);
3896 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3898 // Trigger events
3899 events_trigger('course_created', $course);
3901 return $course;
3905 * Create a new course category and marks the context as dirty
3907 * This function does not set the sortorder for the new category and
3908 * @see{fix_course_sortorder} should be called after creating a new course
3909 * category
3911 * Please note that this function does not verify access control.
3913 * @param object $category All of the data required for an entry in the course_categories table
3914 * @return object new course category
3916 function create_course_category($category) {
3917 global $DB;
3919 $category->timemodified = time();
3920 $category->id = $DB->insert_record('course_categories', $category);
3921 $category = $DB->get_record('course_categories', array('id' => $category->id));
3923 // We should mark the context as dirty
3924 $category->context = context_coursecat::instance($category->id);
3925 $category->context->mark_dirty();
3927 return $category;
3931 * Update a course.
3933 * Please note this functions does not verify any access control,
3934 * the calling code is responsible for all validation (usually it is the form definition).
3936 * @param object $data - all the data needed for an entry in the 'course' table
3937 * @param array $editoroptions course description editor options
3938 * @return void
3940 function update_course($data, $editoroptions = NULL) {
3941 global $CFG, $DB;
3943 $data->timemodified = time();
3945 $oldcourse = course_get_format($data->id)->get_course();
3946 $context = context_course::instance($oldcourse->id);
3948 if ($editoroptions) {
3949 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3952 if (!isset($data->category) or empty($data->category)) {
3953 // prevent nulls and 0 in category field
3954 unset($data->category);
3956 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3958 if (!isset($data->visible)) {
3959 // data not from form, add missing visibility info
3960 $data->visible = $oldcourse->visible;
3963 if ($data->visible != $oldcourse->visible) {
3964 // reset the visibleold flag when manually hiding/unhiding course
3965 $data->visibleold = $data->visible;
3966 } else {
3967 if ($movecat) {
3968 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3969 if (empty($newcategory->visible)) {
3970 // make sure when moving into hidden category the course is hidden automatically
3971 $data->visible = 0;
3976 // Update with the new data
3977 $DB->update_record('course', $data);
3978 // make sure the modinfo cache is reset
3979 rebuild_course_cache($data->id);
3981 // update course format options with full course data
3982 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
3984 $course = $DB->get_record('course', array('id'=>$data->id));
3986 if ($movecat) {
3987 $newparent = context_coursecat::instance($course->category);
3988 context_moved($context, $newparent);
3991 fix_course_sortorder();
3993 // Test for and remove blocks which aren't appropriate anymore
3994 blocks_remove_inappropriate($course);
3996 // Save any custom role names.
3997 save_local_role_names($course->id, $data);
3999 // update enrol settings
4000 enrol_course_updated(false, $course, $data);
4002 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
4004 // Trigger events
4005 events_trigger('course_updated', $course);
4007 if ($oldcourse->format !== $course->format) {
4008 // Remove all options stored for the previous format
4009 // We assume that new course format migrated everything it needed watching trigger
4010 // 'course_updated' and in method format_XXX::update_course_format_options()
4011 $DB->delete_records('course_format_options',
4012 array('courseid' => $course->id, 'format' => $oldcourse->format));
4017 * Average number of participants
4018 * @return integer
4020 function average_number_of_participants() {
4021 global $DB, $SITE;
4023 //count total of enrolments for visible course (except front page)
4024 $sql = 'SELECT COUNT(*) FROM (
4025 SELECT DISTINCT ue.userid, e.courseid
4026 FROM {user_enrolments} ue, {enrol} e, {course} c
4027 WHERE ue.enrolid = e.id
4028 AND e.courseid <> :siteid
4029 AND c.id = e.courseid
4030 AND c.visible = 1) total';
4031 $params = array('siteid' => $SITE->id);
4032 $enrolmenttotal = $DB->count_records_sql($sql, $params);
4035 //count total of visible courses (minus front page)
4036 $coursetotal = $DB->count_records('course', array('visible' => 1));
4037 $coursetotal = $coursetotal - 1 ;
4039 //average of enrolment
4040 if (empty($coursetotal)) {
4041 $participantaverage = 0;
4042 } else {
4043 $participantaverage = $enrolmenttotal / $coursetotal;
4046 return $participantaverage;
4050 * Average number of course modules
4051 * @return integer
4053 function average_number_of_courses_modules() {
4054 global $DB, $SITE;
4056 //count total of visible course module (except front page)
4057 $sql = 'SELECT COUNT(*) FROM (
4058 SELECT cm.course, cm.module
4059 FROM {course} c, {course_modules} cm
4060 WHERE c.id = cm.course
4061 AND c.id <> :siteid
4062 AND cm.visible = 1
4063 AND c.visible = 1) total';
4064 $params = array('siteid' => $SITE->id);
4065 $moduletotal = $DB->count_records_sql($sql, $params);
4068 //count total of visible courses (minus front page)
4069 $coursetotal = $DB->count_records('course', array('visible' => 1));
4070 $coursetotal = $coursetotal - 1 ;
4072 //average of course module
4073 if (empty($coursetotal)) {
4074 $coursemoduleaverage = 0;
4075 } else {
4076 $coursemoduleaverage = $moduletotal / $coursetotal;
4079 return $coursemoduleaverage;
4083 * This class pertains to course requests and contains methods associated with
4084 * create, approving, and removing course requests.
4086 * Please note we do not allow embedded images here because there is no context
4087 * to store them with proper access control.
4089 * @copyright 2009 Sam Hemelryk
4090 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4091 * @since Moodle 2.0
4093 * @property-read int $id
4094 * @property-read string $fullname
4095 * @property-read string $shortname
4096 * @property-read string $summary
4097 * @property-read int $summaryformat
4098 * @property-read int $summarytrust
4099 * @property-read string $reason
4100 * @property-read int $requester
4102 class course_request {
4105 * This is the stdClass that stores the properties for the course request
4106 * and is externally accessed through the __get magic method
4107 * @var stdClass
4109 protected $properties;
4112 * An array of options for the summary editor used by course request forms.
4113 * This is initially set by {@link summary_editor_options()}
4114 * @var array
4115 * @static
4117 protected static $summaryeditoroptions;
4120 * Static function to prepare the summary editor for working with a course
4121 * request.
4123 * @static
4124 * @param null|stdClass $data Optional, an object containing the default values
4125 * for the form, these may be modified when preparing the
4126 * editor so this should be called before creating the form
4127 * @return stdClass An object that can be used to set the default values for
4128 * an mforms form
4130 public static function prepare($data=null) {
4131 if ($data === null) {
4132 $data = new stdClass;
4134 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4135 return $data;
4139 * Static function to create a new course request when passed an array of properties
4140 * for it.
4142 * This function also handles saving any files that may have been used in the editor
4144 * @static
4145 * @param stdClass $data
4146 * @return course_request The newly created course request
4148 public static function create($data) {
4149 global $USER, $DB, $CFG;
4150 $data->requester = $USER->id;
4152 // Setting the default category if none set.
4153 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
4154 $data->category = $CFG->defaultrequestcategory;
4157 // Summary is a required field so copy the text over
4158 $data->summary = $data->summary_editor['text'];
4159 $data->summaryformat = $data->summary_editor['format'];
4161 $data->id = $DB->insert_record('course_request', $data);
4163 // Create a new course_request object and return it
4164 $request = new course_request($data);
4166 // Notify the admin if required.
4167 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4169 $a = new stdClass;
4170 $a->link = "$CFG->wwwroot/course/pending.php";
4171 $a->user = fullname($USER);
4172 $subject = get_string('courserequest');
4173 $message = get_string('courserequestnotifyemail', 'admin', $a);
4174 foreach ($users as $user) {
4175 $request->notify($user, $USER, 'courserequested', $subject, $message);
4179 return $request;
4183 * Returns an array of options to use with a summary editor
4185 * @uses course_request::$summaryeditoroptions
4186 * @return array An array of options to use with the editor
4188 public static function summary_editor_options() {
4189 global $CFG;
4190 if (self::$summaryeditoroptions === null) {
4191 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4193 return self::$summaryeditoroptions;
4197 * Loads the properties for this course request object. Id is required and if
4198 * only id is provided then we load the rest of the properties from the database
4200 * @param stdClass|int $properties Either an object containing properties
4201 * or the course_request id to load
4203 public function __construct($properties) {
4204 global $DB;
4205 if (empty($properties->id)) {
4206 if (empty($properties)) {
4207 throw new coding_exception('You must provide a course request id when creating a course_request object');
4209 $id = $properties;
4210 $properties = new stdClass;
4211 $properties->id = (int)$id;
4212 unset($id);
4214 if (empty($properties->requester)) {
4215 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4216 print_error('unknowncourserequest');
4218 } else {
4219 $this->properties = $properties;
4221 $this->properties->collision = null;
4225 * Returns the requested property
4227 * @param string $key
4228 * @return mixed
4230 public function __get($key) {
4231 return $this->properties->$key;
4235 * Override this to ensure empty($request->blah) calls return a reliable answer...
4237 * This is required because we define the __get method
4239 * @param mixed $key
4240 * @return bool True is it not empty, false otherwise
4242 public function __isset($key) {
4243 return (!empty($this->properties->$key));
4247 * Returns the user who requested this course
4249 * Uses a static var to cache the results and cut down the number of db queries
4251 * @staticvar array $requesters An array of cached users
4252 * @return stdClass The user who requested the course
4254 public function get_requester() {
4255 global $DB;
4256 static $requesters= array();
4257 if (!array_key_exists($this->properties->requester, $requesters)) {
4258 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4260 return $requesters[$this->properties->requester];
4264 * Checks that the shortname used by the course does not conflict with any other
4265 * courses that exist
4267 * @param string|null $shortnamemark The string to append to the requests shortname
4268 * should a conflict be found
4269 * @return bool true is there is a conflict, false otherwise
4271 public function check_shortname_collision($shortnamemark = '[*]') {
4272 global $DB;
4274 if ($this->properties->collision !== null) {
4275 return $this->properties->collision;
4278 if (empty($this->properties->shortname)) {
4279 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4280 $this->properties->collision = false;
4281 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4282 if (!empty($shortnamemark)) {
4283 $this->properties->shortname .= ' '.$shortnamemark;
4285 $this->properties->collision = true;
4286 } else {
4287 $this->properties->collision = false;
4289 return $this->properties->collision;
4293 * This function approves the request turning it into a course
4295 * This function converts the course request into a course, at the same time
4296 * transferring any files used in the summary to the new course and then removing
4297 * the course request and the files associated with it.
4299 * @return int The id of the course that was created from this request
4301 public function approve() {
4302 global $CFG, $DB, $USER;
4304 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4306 $courseconfig = get_config('moodlecourse');
4308 // Transfer appropriate settings
4309 $data = clone($this->properties);
4310 unset($data->id);
4311 unset($data->reason);
4312 unset($data->requester);
4314 // If the category is not set, if the current user does not have the rights to change the category, or if the
4315 // category does not exist, we set the default category to the course to be approved.
4316 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
4317 if (empty($data->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
4318 (!$category = get_course_category($data->category))) {
4319 $category = get_course_category($CFG->defaultrequestcategory);
4322 // Set category
4323 $data->category = $category->id;
4324 $data->sortorder = $category->sortorder; // place as the first in category
4326 // Set misc settings
4327 $data->requested = 1;
4329 // Apply course default settings
4330 $data->format = $courseconfig->format;
4331 $data->newsitems = $courseconfig->newsitems;
4332 $data->showgrades = $courseconfig->showgrades;
4333 $data->showreports = $courseconfig->showreports;
4334 $data->maxbytes = $courseconfig->maxbytes;
4335 $data->groupmode = $courseconfig->groupmode;
4336 $data->groupmodeforce = $courseconfig->groupmodeforce;
4337 $data->visible = $courseconfig->visible;
4338 $data->visibleold = $data->visible;
4339 $data->lang = $courseconfig->lang;
4341 $course = create_course($data);
4342 $context = context_course::instance($course->id, MUST_EXIST);
4344 // add enrol instances
4345 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4346 if ($manual = enrol_get_plugin('manual')) {
4347 $manual->add_default_instance($course);
4351 // enrol the requester as teacher if necessary
4352 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4353 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4356 $this->delete();
4358 $a = new stdClass();
4359 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
4360 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4361 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4363 return $course->id;
4367 * Reject a course request
4369 * This function rejects a course request, emailing the requesting user the
4370 * provided notice and then removing the request from the database
4372 * @param string $notice The message to display to the user
4374 public function reject($notice) {
4375 global $USER, $DB;
4376 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4377 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4378 $this->delete();
4382 * Deletes the course request and any associated files
4384 public function delete() {
4385 global $DB;
4386 $DB->delete_records('course_request', array('id' => $this->properties->id));
4390 * Send a message from one user to another using events_trigger
4392 * @param object $touser
4393 * @param object $fromuser
4394 * @param string $name
4395 * @param string $subject
4396 * @param string $message
4398 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4399 $eventdata = new stdClass();
4400 $eventdata->component = 'moodle';
4401 $eventdata->name = $name;
4402 $eventdata->userfrom = $fromuser;
4403 $eventdata->userto = $touser;
4404 $eventdata->subject = $subject;
4405 $eventdata->fullmessage = $message;
4406 $eventdata->fullmessageformat = FORMAT_PLAIN;
4407 $eventdata->fullmessagehtml = '';
4408 $eventdata->smallmessage = '';
4409 $eventdata->notification = 1;
4410 message_send($eventdata);
4415 * Return a list of page types
4416 * @param string $pagetype current page type
4417 * @param stdClass $parentcontext Block's parent context
4418 * @param stdClass $currentcontext Current context of block
4420 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4421 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
4422 if (isset($currentcontext)) {
4423 // if above course context ,display all course fomats
4424 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4425 if ($course->id == SITEID) {
4426 return array('*'=>get_string('page-x', 'pagetype'));
4429 return array('*'=>get_string('page-x', 'pagetype'),
4430 'course-*'=>get_string('page-course-x', 'pagetype'),
4431 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4436 * Determine whether course ajax should be enabled for the specified course
4438 * @param stdClass $course The course to test against
4439 * @return boolean Whether course ajax is enabled or note
4441 function course_ajax_enabled($course) {
4442 global $CFG, $PAGE, $SITE;
4444 // Ajax must be enabled globally
4445 if (!$CFG->enableajax) {
4446 return false;
4449 // The user must be editing for AJAX to be included
4450 if (!$PAGE->user_is_editing()) {
4451 return false;
4454 // Check that the theme suports
4455 if (!$PAGE->theme->enablecourseajax) {
4456 return false;
4459 // Check that the course format supports ajax functionality
4460 // The site 'format' doesn't have information on course format support
4461 if ($SITE->id !== $course->id) {
4462 $courseformatajaxsupport = course_format_ajax_support($course->format);
4463 if (!$courseformatajaxsupport->capable) {
4464 return false;
4468 // All conditions have been met so course ajax should be enabled
4469 return true;
4473 * Include the relevant javascript and language strings for the resource
4474 * toolbox YUI module
4476 * @param integer $id The ID of the course being applied to
4477 * @param array $usedmodules An array containing the names of the modules in use on the page
4478 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4479 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4480 * * resourceurl The URL to post changes to for resource changes
4481 * * sectionurl The URL to post changes to for section changes
4482 * * pageparams Additional parameters to pass through in the post
4483 * @return bool
4485 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4486 global $PAGE, $SITE;
4488 // Ensure that ajax should be included
4489 if (!course_ajax_enabled($course)) {
4490 return false;
4493 if (!$config) {
4494 $config = new stdClass();
4497 // The URL to use for resource changes
4498 if (!isset($config->resourceurl)) {
4499 $config->resourceurl = '/course/rest.php';
4502 // The URL to use for section changes
4503 if (!isset($config->sectionurl)) {
4504 $config->sectionurl = '/course/rest.php';
4507 // Any additional parameters which need to be included on page submission
4508 if (!isset($config->pageparams)) {
4509 $config->pageparams = array();
4512 // Include toolboxes
4513 $PAGE->requires->yui_module('moodle-course-toolboxes',
4514 'M.course.init_resource_toolbox',
4515 array(array(
4516 'courseid' => $course->id,
4517 'ajaxurl' => $config->resourceurl,
4518 'config' => $config,
4521 $PAGE->requires->yui_module('moodle-course-toolboxes',
4522 'M.course.init_section_toolbox',
4523 array(array(
4524 'courseid' => $course->id,
4525 'format' => $course->format,
4526 'ajaxurl' => $config->sectionurl,
4527 'config' => $config,
4531 // Include course dragdrop
4532 if ($course->id != $SITE->id) {
4533 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4534 array(array(
4535 'courseid' => $course->id,
4536 'ajaxurl' => $config->sectionurl,
4537 'config' => $config,
4538 )), null, true);
4540 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4541 array(array(
4542 'courseid' => $course->id,
4543 'ajaxurl' => $config->resourceurl,
4544 'config' => $config,
4545 )), null, true);
4548 // Include blocks dragdrop
4549 $params = array(
4550 'courseid' => $course->id,
4551 'pagetype' => $PAGE->pagetype,
4552 'pagelayout' => $PAGE->pagelayout,
4553 'subpage' => $PAGE->subpage,
4554 'regions' => $PAGE->blocks->get_regions(),
4556 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4558 // Require various strings for the command toolbox
4559 $PAGE->requires->strings_for_js(array(
4560 'moveleft',
4561 'deletechecktype',
4562 'deletechecktypename',
4563 'edittitle',
4564 'edittitleinstructions',
4565 'show',
4566 'hide',
4567 'groupsnone',
4568 'groupsvisible',
4569 'groupsseparate',
4570 'clicktochangeinbrackets',
4571 'markthistopic',
4572 'markedthistopic',
4573 'move',
4574 'movesection',
4575 ), 'moodle');
4577 // Include format-specific strings
4578 if ($course->id != $SITE->id) {
4579 $PAGE->requires->strings_for_js(array(
4580 'showfromothers',
4581 'hidefromothers',
4582 ), 'format_' . $course->format);
4585 // For confirming resource deletion we need the name of the module in question
4586 foreach ($usedmodules as $module => $modname) {
4587 $PAGE->requires->string_for_js('pluginname', $module);
4590 // Load drag and drop upload AJAX.
4591 dndupload_add_to_course($course, $enabledmodules);
4593 // Add the module chooser
4594 $PAGE->requires->yui_module('moodle-course-modchooser',
4595 'M.course.init_chooser',
4596 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
4598 $PAGE->requires->strings_for_js(array(
4599 'addresourceoractivity',
4600 'modchooserenable',
4601 'modchooserdisable',
4602 ), 'moodle');
4604 return true;
4608 * Returns the sorted list of available course formats, filtered by enabled if necessary
4610 * @param bool $enabledonly return only formats that are enabled
4611 * @return array array of sorted format names
4613 function get_sorted_course_formats($enabledonly = false) {
4614 global $CFG;
4615 $formats = get_plugin_list('format');
4617 if (!empty($CFG->format_plugins_sortorder)) {
4618 $order = explode(',', $CFG->format_plugins_sortorder);
4619 $order = array_merge(array_intersect($order, array_keys($formats)),
4620 array_diff(array_keys($formats), $order));
4621 } else {
4622 $order = array_keys($formats);
4624 if (!$enabledonly) {
4625 return $order;
4627 $sortedformats = array();
4628 foreach ($order as $formatname) {
4629 if (!get_config('format_'.$formatname, 'disabled')) {
4630 $sortedformats[] = $formatname;
4633 return $sortedformats;
4637 * The URL to use for the specified course (with section)
4639 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
4640 * @param int|stdClass $section Section object from database or just field course_sections.section
4641 * if omitted the course view page is returned
4642 * @param array $options options for view URL. At the moment core uses:
4643 * 'navigation' (bool) if true and section has no separate page, the function returns null
4644 * 'sr' (int) used by multipage formats to specify to which section to return
4645 * @return moodle_url The url of course
4647 function course_get_url($courseorid, $section = null, $options = array()) {
4648 return course_get_format($courseorid)->get_view_url($section, $options);