Merge branch 'MDL-41568-en_fix-24' of git://github.com/mudrd8mz/moodle into MOODLE_24...
[moodle.git] / course / lib.php
blob1796bae10da0939f662801b31bec2521bdc7ef27
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 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
1163 $url = new moodle_url($info->iconurl);
1164 $mod[$seq]->iconurl = $url->out(false);
1166 if (!empty($info->onclick)) {
1167 $mod[$seq]->onclick = $info->onclick;
1169 if (!empty($info->customdata)) {
1170 $mod[$seq]->customdata = $info->customdata;
1172 } else {
1173 // When using a stdclass, the (horrible) deprecated ->extra field
1174 // is available for BC
1175 if (!empty($info->extra)) {
1176 $mod[$seq]->extra = $info->extra;
1181 // When there is no modname_get_coursemodule_info function,
1182 // but showdescriptions is enabled, then we use the 'intro'
1183 // and 'introformat' fields in the module table
1184 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1185 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1186 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1187 // Set content from intro and introformat. Filters are disabled
1188 // because we filter it with format_text at display time
1189 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1190 $modvalues, $rawmods[$seq]->id, false);
1192 // To save making another query just below, put name in here
1193 $mod[$seq]->name = $modvalues->name;
1196 if (!isset($mod[$seq]->name)) {
1197 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1200 // Minimise the database size by unsetting default options when they are
1201 // 'empty'. This list corresponds to code in the cm_info constructor.
1202 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1203 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1204 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1205 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1206 'completionview', 'completionexpected', 'score', 'showdescription')
1207 as $property) {
1208 if (property_exists($mod[$seq], $property) &&
1209 empty($mod[$seq]->{$property})) {
1210 unset($mod[$seq]->{$property});
1213 // Special case: this value is usually set to null, but may be 0
1214 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1215 is_null($mod[$seq]->completiongradeitemnumber)) {
1216 unset($mod[$seq]->completiongradeitemnumber);
1222 return $mod;
1226 * Returns the localised human-readable names of all used modules
1228 * @param bool $plural if true returns the plural forms of the names
1229 * @return array where key is the module name (component name without 'mod_') and
1230 * the value is the human-readable string. Array sorted alphabetically by value
1232 function get_module_types_names($plural = false) {
1233 static $modnames = null;
1234 global $DB, $CFG;
1235 if ($modnames === null) {
1236 $modnames = array(0 => array(), 1 => array());
1237 if ($allmods = $DB->get_records("modules")) {
1238 foreach ($allmods as $mod) {
1239 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1240 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1241 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1244 collatorlib::asort($modnames[0]);
1245 collatorlib::asort($modnames[1]);
1248 return $modnames[(int)$plural];
1252 * Set highlighted section. Only one section can be highlighted at the time.
1254 * @param int $courseid course id
1255 * @param int $marker highlight section with this number, 0 means remove higlightin
1256 * @return void
1258 function course_set_marker($courseid, $marker) {
1259 global $DB;
1260 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1261 format_base::reset_course_cache($courseid);
1265 * For a given course section, marks it visible or hidden,
1266 * and does the same for every activity in that section
1268 * @param int $courseid course id
1269 * @param int $sectionnumber The section number to adjust
1270 * @param int $visibility The new visibility
1271 * @return array A list of resources which were hidden in the section
1273 function set_section_visible($courseid, $sectionnumber, $visibility) {
1274 global $DB;
1276 $resourcestotoggle = array();
1277 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1278 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1279 if (!empty($section->sequence)) {
1280 $modules = explode(",", $section->sequence);
1281 foreach ($modules as $moduleid) {
1282 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1283 if ($visibility) {
1284 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1285 set_coursemodule_visible($moduleid, $cm->visibleold);
1286 } else {
1287 // We hide the section, so we hide the module but we store the original state in visibleold.
1288 set_coursemodule_visible($moduleid, 0);
1289 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1294 rebuild_course_cache($courseid, true);
1296 // Determine which modules are visible for AJAX update
1297 if (!empty($modules)) {
1298 list($insql, $params) = $DB->get_in_or_equal($modules);
1299 $select = 'id ' . $insql . ' AND visible = ?';
1300 array_push($params, $visibility);
1301 if (!$visibility) {
1302 $select .= ' AND visibleold = 1';
1304 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1307 return $resourcestotoggle;
1311 * Obtains shared data that is used in print_section when displaying a
1312 * course-module entry.
1314 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1316 * This data is also used in other areas of the code.
1317 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1318 * @param object $course Moodle course object
1319 * @return array An array with the following values in this order:
1320 * $content (optional extra content for after link),
1321 * $instancename (text of link)
1323 function get_print_section_cm_text(cm_info $cm, $course) {
1324 global $OUTPUT;
1326 // Get content from modinfo if specified. Content displays either
1327 // in addition to the standard link (below), or replaces it if
1328 // the link is turned off by setting ->url to null.
1329 if (($content = $cm->get_content()) !== '') {
1330 // Improve filter performance by preloading filter setttings for all
1331 // activities on the course (this does nothing if called multiple
1332 // times)
1333 filter_preload_activities($cm->get_modinfo());
1335 // Get module context
1336 $modulecontext = context_module::instance($cm->id);
1337 $labelformatoptions = new stdClass();
1338 $labelformatoptions->noclean = true;
1339 $labelformatoptions->overflowdiv = true;
1340 $labelformatoptions->context = $modulecontext;
1341 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1342 } else {
1343 $content = '';
1346 // Get course context
1347 $coursecontext = context_course::instance($course->id);
1348 $stringoptions = new stdClass;
1349 $stringoptions->context = $coursecontext;
1350 $instancename = format_string($cm->name, true, $stringoptions);
1351 return array($content, $instancename);
1355 * Prints a section full of activity modules
1357 * @param stdClass $course The course
1358 * @param stdClass|section_info $section The section object containing properties id and section
1359 * @param array $mods (argument not used)
1360 * @param array $modnamesused (argument not used)
1361 * @param bool $absolute All links are absolute
1362 * @param string $width Width of the container
1363 * @param bool $hidecompletion Hide completion status
1364 * @param int $sectionreturn The section to return to
1365 * @return void
1367 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1368 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1370 static $initialised;
1372 static $groupbuttons;
1373 static $groupbuttonslink;
1374 static $isediting;
1375 static $ismoving;
1376 static $strmovehere;
1377 static $strmovefull;
1378 static $strunreadpostsone;
1380 if (!isset($initialised)) {
1381 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1382 $groupbuttonslink = (!$course->groupmodeforce);
1383 $isediting = $PAGE->user_is_editing();
1384 $ismoving = $isediting && ismoving($course->id);
1385 if ($ismoving) {
1386 $strmovehere = get_string("movehere");
1387 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1389 $initialised = true;
1392 $modinfo = get_fast_modinfo($course);
1393 $completioninfo = new completion_info($course);
1395 //Accessibility: replace table with list <ul>, but don't output empty list.
1396 if (!empty($modinfo->sections[$section->section])) {
1398 // Fix bug #5027, don't want style=\"width:$width\".
1399 echo "<ul class=\"section img-text\">\n";
1401 foreach ($modinfo->sections[$section->section] as $modnumber) {
1402 $mod = $modinfo->cms[$modnumber];
1404 if ($ismoving and $mod->id == $USER->activitycopy) {
1405 // do not display moving mod
1406 continue;
1409 // We can continue (because it will not be displayed at all)
1410 // if:
1411 // 1) The activity is not visible to users
1412 // and
1413 // 2a) The 'showavailability' option is not set (if that is set,
1414 // we need to display the activity so we can show
1415 // availability info)
1416 // or
1417 // 2b) The 'availableinfo' is empty, i.e. the activity was
1418 // hidden in a way that leaves no info, such as using the
1419 // eye icon.
1420 if (!$mod->uservisible &&
1421 (empty($mod->showavailability) ||
1422 empty($mod->availableinfo))) {
1423 // visibility shortcut
1424 continue;
1427 // In some cases the activity is visible to user, but it is
1428 // dimmed. This is done if viewhiddenactivities is true and if:
1429 // 1. the activity is not visible, or
1430 // 2. the activity has dates set which do not include current, or
1431 // 3. the activity has any other conditions set (regardless of whether
1432 // current user meets them)
1433 $modcontext = context_module::instance($mod->id);
1434 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1435 $accessiblebutdim = false;
1436 $conditionalhidden = false;
1437 if ($canviewhidden) {
1438 $accessiblebutdim = !$mod->visible;
1439 if (!empty($CFG->enableavailability)) {
1440 $conditionalhidden = $mod->availablefrom > time() ||
1441 ($mod->availableuntil && $mod->availableuntil < time()) ||
1442 count($mod->conditionsgrade) > 0 ||
1443 count($mod->conditionscompletion) > 0;
1445 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1448 $liclasses = array();
1449 $liclasses[] = 'activity';
1450 $liclasses[] = $mod->modname;
1451 $liclasses[] = 'modtype_'.$mod->modname;
1452 $extraclasses = $mod->get_extra_classes();
1453 if ($extraclasses) {
1454 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1456 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1457 if ($ismoving) {
1458 echo '<a title="'.$strmovefull.'"'.
1459 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1460 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1461 ' alt="'.$strmovehere.'" /></a><br />
1465 $classes = array('mod-indent');
1466 if (!empty($mod->indent)) {
1467 $classes[] = 'mod-indent-'.$mod->indent;
1468 if ($mod->indent > 15) {
1469 $classes[] = 'mod-indent-huge';
1472 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1474 // Get data about this course-module
1475 list($content, $instancename) =
1476 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1478 //Accessibility: for files get description via icon, this is very ugly hack!
1479 $altname = '';
1480 $altname = $mod->modfullname;
1481 // Avoid unnecessary duplication: if e.g. a forum name already
1482 // includes the word forum (or Forum, etc) then it is unhelpful
1483 // to include that in the accessible description that is added.
1484 if (false !== strpos(textlib::strtolower($instancename),
1485 textlib::strtolower($altname))) {
1486 $altname = '';
1488 // File type after name, for alphabetic lists (screen reader).
1489 if ($altname) {
1490 $altname = get_accesshide(' '.$altname);
1493 // Start the div for the activity title, excluding the edit icons.
1494 echo html_writer::start_tag('div', array('class' => 'activityinstance'));
1496 // We may be displaying this just in order to show information
1497 // about visibility, without the actual link
1498 $contentpart = '';
1499 if ($mod->uservisible) {
1500 // Nope - in this case the link is fully working for user
1501 $linkclasses = '';
1502 $textclasses = '';
1503 if ($accessiblebutdim) {
1504 $linkclasses .= ' dimmed';
1505 $textclasses .= ' dimmed_text';
1506 if ($conditionalhidden) {
1507 $linkclasses .= ' conditionalhidden';
1508 $textclasses .= ' conditionalhidden';
1510 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
1511 } else {
1512 $accesstext = '';
1514 if ($linkclasses) {
1515 $linkcss = trim($linkclasses) . ' ';
1516 } else {
1517 $linkcss = '';
1519 if ($textclasses) {
1520 $textcss = trim($textclasses) . ' ';
1521 } else {
1522 $textcss = '';
1525 // Get on-click attribute value if specified and decode the onclick - it
1526 // has already been encoded for display (puke).
1527 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
1529 $groupinglabel = '';
1530 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1531 $groupings = groups_get_all_groupings($course->id);
1532 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
1533 array('class' => 'groupinglabel'));
1536 if ($url = $mod->get_url()) {
1537 // Display link itself.
1538 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
1539 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext .
1540 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
1541 echo html_writer::link($url, $activitylink, array('class' => $linkcss, 'onclick' => $onclick)) .
1542 $groupinglabel;
1544 // If specified, display extra content after link.
1545 if ($content) {
1546 $contentpart = html_writer::tag('div', $content, array('class' =>
1547 trim('contentafterlink ' . $textclasses)));
1549 } else {
1550 // No link, so display only content.
1551 $contentpart = html_writer::tag('div', $accesstext . $content, array('class' => $textcss));
1554 } else {
1555 $textclasses = $extraclasses;
1556 $textclasses .= ' dimmed_text';
1557 if ($textclasses) {
1558 $textcss = 'class="' . trim($textclasses) . '" ';
1559 } else {
1560 $textcss = '';
1562 $accesstext = '<span class="accesshide">' .
1563 get_string('notavailableyet', 'condition') .
1564 ': </span>';
1566 if ($url = $mod->get_url()) {
1567 // Display greyed-out text of link
1568 echo '<div ' . $textcss . $mod->extra .
1569 ' >' . '<img src="' . $mod->get_icon_url() .
1570 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1571 '</span></div>';
1573 // Do not display content after link when it is greyed out like this.
1574 } else {
1575 // No link, so display only content (also greyed)
1576 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1577 $accesstext . $content . '</div>';
1581 // Module can put text after the link (e.g. forum unread)
1582 echo $mod->get_after_link();
1584 // Closing the tag which contains everything but edit icons. $contentpart should not be part of this.
1585 echo html_writer::end_tag('div');
1587 // If there is content but NO link (eg label), then display the
1588 // content here (BEFORE any icons). In this case cons must be
1589 // displayed after the content so that it makes more sense visually
1590 // and for accessibility reasons, e.g. if you have a one-line label
1591 // it should work similarly (at least in terms of ordering) to an
1592 // activity.
1593 if (empty($url)) {
1594 echo $contentpart;
1597 if ($isediting) {
1598 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1599 if (! $mod->groupmodelink = $groupbuttonslink) {
1600 $mod->groupmode = $course->groupmode;
1603 } else {
1604 $mod->groupmode = false;
1606 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1607 echo $mod->get_after_edit_icons();
1610 // Completion
1611 $completion = $hidecompletion
1612 ? COMPLETION_TRACKING_NONE
1613 : $completioninfo->is_enabled($mod);
1614 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1615 !isguestuser() && $mod->uservisible) {
1616 $completiondata = $completioninfo->get_data($mod,true);
1617 $completionicon = '';
1618 if ($isediting) {
1619 switch ($completion) {
1620 case COMPLETION_TRACKING_MANUAL :
1621 $completionicon = 'manual-enabled'; break;
1622 case COMPLETION_TRACKING_AUTOMATIC :
1623 $completionicon = 'auto-enabled'; break;
1624 default: // wtf
1626 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1627 switch($completiondata->completionstate) {
1628 case COMPLETION_INCOMPLETE:
1629 $completionicon = 'manual-n'; break;
1630 case COMPLETION_COMPLETE:
1631 $completionicon = 'manual-y'; break;
1633 } else { // Automatic
1634 switch($completiondata->completionstate) {
1635 case COMPLETION_INCOMPLETE:
1636 $completionicon = 'auto-n'; break;
1637 case COMPLETION_COMPLETE:
1638 $completionicon = 'auto-y'; break;
1639 case COMPLETION_COMPLETE_PASS:
1640 $completionicon = 'auto-pass'; break;
1641 case COMPLETION_COMPLETE_FAIL:
1642 $completionicon = 'auto-fail'; break;
1645 if ($completionicon) {
1646 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1647 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1648 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1649 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1650 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1651 $newstate =
1652 $completiondata->completionstate==COMPLETION_COMPLETE
1653 ? COMPLETION_INCOMPLETE
1654 : COMPLETION_COMPLETE;
1655 // In manual mode the icon is a toggle form...
1657 // If this completion state is used by the
1658 // conditional activities system, we need to turn
1659 // off the JS.
1660 if (!empty($CFG->enableavailability) &&
1661 condition_info::completion_value_used_as_condition($course, $mod)) {
1662 $extraclass = ' preventjs';
1663 } else {
1664 $extraclass = '';
1666 echo html_writer::start_tag('form', array(
1667 'class' => 'togglecompletion' . $extraclass,
1668 'method' => 'post',
1669 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1670 echo html_writer::start_tag('div');
1671 echo html_writer::empty_tag('input', array(
1672 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1673 echo html_writer::empty_tag('input', array(
1674 'type' => 'hidden', 'name' => 'modulename',
1675 'value' => $mod->name));
1676 echo html_writer::empty_tag('input', array(
1677 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1678 echo html_writer::empty_tag('input', array(
1679 'type' => 'hidden', 'name' => 'completionstate',
1680 'value' => $newstate));
1681 echo html_writer::empty_tag('input', array(
1682 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle,
1683 'aria-live' => 'polite'));
1684 echo html_writer::end_tag('div');
1685 echo html_writer::end_tag('form');
1686 } else {
1687 // In auto mode, or when editing, the icon is just an image.
1688 echo html_writer::tag('span', html_writer::empty_tag('img', array(
1689 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgalt)),
1690 array('class' => 'autocompletion'));
1695 // If there is content AND a link, then display the content here
1696 // (AFTER any icons). Otherwise it was displayed before
1697 if (!empty($url)) {
1698 echo $contentpart;
1701 // Show availability information (for someone who isn't allowed to
1702 // see the activity itself, or for staff)
1703 if (!$mod->uservisible) {
1704 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1705 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1706 // Don't add availability information if user is not editing and activity is hidden.
1707 if ($mod->visible || $PAGE->user_is_editing()) {
1708 $hidinfoclass = '';
1709 if (!$mod->visible) {
1710 $hidinfoclass = 'hide';
1712 $ci = new condition_info($mod);
1713 $fullinfo = $ci->get_full_information();
1714 if($fullinfo) {
1715 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1716 ? 'userrestriction_visible'
1717 : 'userrestriction_hidden','condition',
1718 $fullinfo).'</div>';
1723 echo html_writer::end_tag('div');
1724 echo html_writer::end_tag('li')."\n";
1727 } elseif ($ismoving) {
1728 echo "<ul class=\"section\">\n";
1731 if ($ismoving) {
1732 echo '<li><a title="'.$strmovefull.'"'.
1733 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1734 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1735 ' alt="'.$strmovehere.'" /></a></li>
1738 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1739 echo "</ul><!--class='section'-->\n\n";
1744 * Prints the menus to add activities and resources.
1746 * @param stdClass $course The course
1747 * @param int $section relative section number (field course_sections.section)
1748 * @param null|array $modnames An array containing the list of modules and their names
1749 * if omitted will be taken from get_module_types_names()
1750 * @param bool $vertical Vertical orientation
1751 * @param bool $return Return the menus or send them to output
1752 * @param int $sectionreturn The section to link back to
1753 * @return void|string depending on $return
1755 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1756 global $CFG, $OUTPUT;
1758 if ($modnames === null) {
1759 $modnames = get_module_types_names();
1762 // check to see if user can add menus and there are modules to add
1763 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1764 || empty($modnames)) {
1765 if ($return) {
1766 return '';
1767 } else {
1768 return false;
1772 // Retrieve all modules with associated metadata
1773 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1775 // We'll sort resources and activities into two lists
1776 $resources = array();
1777 $activities = array();
1779 // We need to add the section section to the link for each module
1780 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1782 foreach ($modules as $module) {
1783 if (isset($module->types)) {
1784 // This module has a subtype
1785 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1786 $subtypes = array();
1787 foreach ($module->types as $subtype) {
1788 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1791 // Sort module subtypes into the list
1792 if (!empty($module->title)) {
1793 // This grouping has a name
1794 if ($module->archetype == MOD_CLASS_RESOURCE) {
1795 $resources[] = array($module->title=>$subtypes);
1796 } else {
1797 $activities[] = array($module->title=>$subtypes);
1799 } else {
1800 // This grouping does not have a name
1801 if ($module->archetype == MOD_CLASS_RESOURCE) {
1802 $resources = array_merge($resources, $subtypes);
1803 } else {
1804 $activities = array_merge($activities, $subtypes);
1807 } else {
1808 // This module has no subtypes
1809 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1810 $resources[$module->link . $sectionlink] = $module->title;
1811 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1812 // System modules cannot be added by user, do not add to dropdown
1813 } else {
1814 $activities[$module->link . $sectionlink] = $module->title;
1819 $straddactivity = get_string('addactivity');
1820 $straddresource = get_string('addresource');
1821 $sectionname = get_section_name($course, $section);
1822 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1823 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1825 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1827 if (!$vertical) {
1828 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1831 if (!empty($resources)) {
1832 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1833 $select->set_help_icon('resources');
1834 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1835 $output .= $OUTPUT->render($select);
1838 if (!empty($activities)) {
1839 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1840 $select->set_help_icon('activities');
1841 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1842 $output .= $OUTPUT->render($select);
1845 if (!$vertical) {
1846 $output .= html_writer::end_tag('div');
1849 $output .= html_writer::end_tag('div');
1851 if (course_ajax_enabled($course)) {
1852 $straddeither = get_string('addresourceoractivity');
1853 // The module chooser link
1854 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1855 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1856 $icon = $OUTPUT->pix_icon('t/add', '');
1857 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1858 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1859 $modchooser.= html_writer::end_tag('div');
1860 $modchooser.= html_writer::end_tag('div');
1862 // Wrap the normal output in a noscript div
1863 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1864 if ($usemodchooser) {
1865 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1866 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1867 } else {
1868 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1869 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1870 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1872 $output = $modchooser . $output;
1875 if ($return) {
1876 return $output;
1877 } else {
1878 echo $output;
1883 * Retrieve all metadata for the requested modules
1885 * @param object $course The Course
1886 * @param array $modnames An array containing the list of modules and their
1887 * names
1888 * @param int $sectionreturn The section to return to
1889 * @return array A list of stdClass objects containing metadata about each
1890 * module
1892 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1893 global $CFG, $OUTPUT;
1895 // get_module_metadata will be called once per section on the page and courses may show
1896 // different modules to one another
1897 static $modlist = array();
1898 if (!isset($modlist[$course->id])) {
1899 $modlist[$course->id] = array();
1902 $return = array();
1903 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1904 foreach($modnames as $modname => $modnamestr) {
1905 if (!course_allowed_module($course, $modname)) {
1906 continue;
1908 if (isset($modlist[$course->id][$modname])) {
1909 // This module is already cached
1910 $return[$modname] = $modlist[$course->id][$modname];
1911 continue;
1914 // Include the module lib
1915 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1916 if (!file_exists($libfile)) {
1917 continue;
1919 include_once($libfile);
1921 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1922 $gettypesfunc = $modname.'_get_types';
1923 if (function_exists($gettypesfunc)) {
1924 $types = $gettypesfunc();
1925 if (is_array($types) && count($types) > 0) {
1926 $group = new stdClass();
1927 $group->name = $modname;
1928 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1929 foreach($types as $type) {
1930 if ($type->typestr === '--') {
1931 continue;
1933 if (strpos($type->typestr, '--') === 0) {
1934 $group->title = str_replace('--', '', $type->typestr);
1935 continue;
1937 // Set the Sub Type metadata
1938 $subtype = new stdClass();
1939 $subtype->title = $type->typestr;
1940 $subtype->type = str_replace('&amp;', '&', $type->type);
1941 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1942 $subtype->archetype = $type->modclass;
1944 // The group archetype should match the subtype archetypes and all subtypes
1945 // should have the same archetype
1946 $group->archetype = $subtype->archetype;
1948 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1949 $subtype->help = get_string('help' . $subtype->name, $modname);
1951 $subtype->link = $urlbase . $subtype->type;
1952 $group->types[] = $subtype;
1954 $modlist[$course->id][$modname] = $group;
1956 } else {
1957 $module = new stdClass();
1958 $module->title = get_string('modulename', $modname);
1959 $module->name = $modname;
1960 $module->link = $urlbase . $modname;
1961 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1962 $sm = get_string_manager();
1963 if ($sm->string_exists('modulename_help', $modname)) {
1964 $module->help = get_string('modulename_help', $modname);
1965 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1966 $link = get_string('modulename_link', $modname);
1967 $linktext = get_string('morehelp');
1968 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1971 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1972 $modlist[$course->id][$modname] = $module;
1974 if (isset($modlist[$course->id][$modname])) {
1975 $return[$modname] = $modlist[$course->id][$modname];
1976 } else {
1977 debugging("Invalid module metadata configuration for {$modname}");
1981 return $return;
1985 * Return the course category context for the category with id $categoryid, except
1986 * that if $categoryid is 0, return the system context.
1988 * @param integer $categoryid a category id or 0.
1989 * @return object the corresponding context
1991 function get_category_or_system_context($categoryid) {
1992 if ($categoryid) {
1993 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1994 } else {
1995 return context_system::instance();
2000 * Gets the child categories of a given courses category. Uses a static cache
2001 * to make repeat calls efficient.
2003 * @param int $parentid the id of a course category.
2004 * @return array all the child course categories.
2006 function get_child_categories($parentid) {
2007 static $allcategories = null;
2009 // only fill in this variable the first time
2010 if (null == $allcategories) {
2011 $allcategories = array();
2013 $categories = get_categories();
2014 foreach ($categories as $category) {
2015 if (empty($allcategories[$category->parent])) {
2016 $allcategories[$category->parent] = array();
2018 $allcategories[$category->parent][] = $category;
2022 if (empty($allcategories[$parentid])) {
2023 return array();
2024 } else {
2025 return $allcategories[$parentid];
2030 * This function recursively travels the categories, building up a nice list
2031 * for display. It also makes an array that list all the parents for each
2032 * category.
2034 * For example, if you have a tree of categories like:
2035 * Miscellaneous (id = 1)
2036 * Subcategory (id = 2)
2037 * Sub-subcategory (id = 4)
2038 * Other category (id = 3)
2039 * Then after calling this function you will have
2040 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2041 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2042 * 3 => 'Other category');
2043 * $parents = array(2 => array(1), 4 => array(1, 2));
2045 * If you specify $requiredcapability, then only categories where the current
2046 * user has that capability will be added to $list, although all categories
2047 * will still be added to $parents, and if you only have $requiredcapability
2048 * in a child category, not the parent, then the child catgegory will still be
2049 * included.
2051 * If you specify the option $excluded, then that category, and all its children,
2052 * are omitted from the tree. This is useful when you are doing something like
2053 * moving categories, where you do not want to allow people to move a category
2054 * to be the child of itself.
2056 * @param array $list For output, accumulates an array categoryid => full category path name
2057 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2058 * @param string/array $requiredcapability if given, only categories where the current
2059 * user has this capability will be added to $list. Can also be an array of capabilities,
2060 * in which case they are all required.
2061 * @param integer $excludeid Omit this category and its children from the lists built.
2062 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2063 * @param string $path For internal use, as part of recursive calls.
2065 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2066 $excludeid = 0, $category = NULL, $path = "") {
2068 // initialize the arrays if needed
2069 if (!is_array($list)) {
2070 $list = array();
2072 if (!is_array($parents)) {
2073 $parents = array();
2076 if (empty($category)) {
2077 // Start at the top level.
2078 $category = new stdClass;
2079 $category->id = 0;
2080 } else {
2081 // This is the excluded category, don't include it.
2082 if ($excludeid > 0 && $excludeid == $category->id) {
2083 return;
2086 $context = context_coursecat::instance($category->id);
2087 $categoryname = format_string($category->name, true, array('context' => $context));
2089 // Update $path.
2090 if ($path) {
2091 $path = $path.' / '.$categoryname;
2092 } else {
2093 $path = $categoryname;
2096 // Add this category to $list, if the permissions check out.
2097 if (empty($requiredcapability)) {
2098 $list[$category->id] = $path;
2100 } else {
2101 $requiredcapability = (array)$requiredcapability;
2102 if (has_all_capabilities($requiredcapability, $context)) {
2103 $list[$category->id] = $path;
2108 // Add all the children recursively, while updating the parents array.
2109 if ($categories = get_child_categories($category->id)) {
2110 foreach ($categories as $cat) {
2111 if (!empty($category->id)) {
2112 if (isset($parents[$category->id])) {
2113 $parents[$cat->id] = $parents[$category->id];
2115 $parents[$cat->id][] = $category->id;
2117 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2123 * This function generates a structured array of courses and categories.
2125 * The depth of categories is limited by $CFG->maxcategorydepth however there
2126 * is no limit on the number of courses!
2128 * Suitable for use with the course renderers course_category_tree method:
2129 * $renderer = $PAGE->get_renderer('core','course');
2130 * echo $renderer->course_category_tree(get_course_category_tree());
2132 * @global moodle_database $DB
2133 * @param int $id
2134 * @param int $depth
2136 function get_course_category_tree($id = 0, $depth = 0) {
2137 global $DB, $CFG;
2138 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2139 $categories = get_child_categories($id);
2140 $categoryids = array();
2141 foreach ($categories as $key => &$category) {
2142 if (!$category->visible && !$viewhiddencats) {
2143 unset($categories[$key]);
2144 continue;
2146 $categoryids[$category->id] = $category;
2147 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2148 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2149 foreach ($subcategories as $subid=>$subcat) {
2150 $categoryids[$subid] = $subcat;
2152 $category->courses = array();
2156 if ($depth > 0) {
2157 // This is a recursive call so return the required array
2158 return array($categories, $categoryids);
2161 if (empty($categoryids)) {
2162 // No categories available (probably all hidden).
2163 return array();
2166 // The depth is 0 this function has just been called so we can finish it off
2168 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2169 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2170 $sql = "SELECT
2171 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2172 $ccselect
2173 FROM {course} c
2174 $ccjoin
2175 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2176 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2177 // loop throught them
2178 foreach ($courses as $course) {
2179 if ($course->id == SITEID) {
2180 continue;
2182 context_instance_preload($course);
2183 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2184 $categoryids[$course->category]->courses[$course->id] = $course;
2188 return $categories;
2192 * Recursive function to print out all the categories in a nice format
2193 * with or without courses included
2195 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2196 global $CFG;
2198 // maxcategorydepth == 0 meant no limit
2199 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2200 return;
2203 if (!$displaylist) {
2204 make_categories_list($displaylist, $parentslist);
2207 if ($category) {
2208 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2209 print_category_info($category, $depth, $showcourses);
2210 } else {
2211 return; // Don't bother printing children of invisible categories
2214 } else {
2215 $category = new stdClass();
2216 $category->id = "0";
2219 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2220 $countcats = count($categories);
2221 $count = 0;
2222 $first = true;
2223 $last = false;
2224 foreach ($categories as $cat) {
2225 $count++;
2226 if ($count == $countcats) {
2227 $last = true;
2229 $up = $first ? false : true;
2230 $down = $last ? false : true;
2231 $first = false;
2233 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2239 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2241 function make_categories_options() {
2242 make_categories_list($cats,$parents);
2243 foreach ($cats as $key => $value) {
2244 if (array_key_exists($key,$parents)) {
2245 if ($indent = count($parents[$key])) {
2246 for ($i = 0; $i < $indent; $i++) {
2247 $cats[$key] = '&nbsp;'.$cats[$key];
2252 return $cats;
2256 * Prints the category info in indented fashion
2257 * This function is only used by print_whole_category_list() above
2259 function print_category_info($category, $depth=0, $showcourses = false) {
2260 global $CFG, $DB, $OUTPUT;
2262 $strsummary = get_string('summary');
2264 $catlinkcss = null;
2265 if (!$category->visible) {
2266 $catlinkcss = array('class'=>'dimmed');
2268 static $coursecount = null;
2269 if (null === $coursecount) {
2270 // only need to check this once
2271 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2274 if ($showcourses and $coursecount) {
2275 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2276 } else {
2277 $catimage = "&nbsp;";
2280 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2281 $context = context_coursecat::instance($category->id);
2282 $fullname = format_string($category->name, true, array('context' => $context));
2284 if ($showcourses and $coursecount) {
2285 echo '<div class="categorylist clearfix">';
2286 $cat = '';
2287 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2288 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2289 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2291 $html = '';
2292 if ($depth > 0) {
2293 for ($i=0; $i< $depth; $i++) {
2294 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2295 $cat = '';
2297 } else {
2298 $html = $cat;
2300 echo html_writer::tag('div', $html, array('class'=>'category'));
2301 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2303 // does the depth exceed maxcategorydepth
2304 // maxcategorydepth == 0 or unset meant no limit
2305 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2306 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2307 foreach ($courses as $course) {
2308 $linkcss = null;
2309 if (!$course->visible) {
2310 $linkcss = array('class'=>'dimmed');
2313 $coursename = get_course_display_name_for_list($course);
2314 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2316 // print enrol info
2317 $courseicon = '';
2318 if ($icons = enrol_get_course_info_icons($course)) {
2319 foreach ($icons as $pix_icon) {
2320 $courseicon = $OUTPUT->render($pix_icon);
2324 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2326 if ($course->summary) {
2327 $link = new moodle_url('/course/info.php?id='.$course->id);
2328 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2329 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2330 array('title'=>$strsummary));
2332 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2335 $html = '';
2336 for ($i=0; $i <= $depth; $i++) {
2337 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2338 $coursecontent = '';
2340 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2343 echo '</div>';
2344 } else {
2345 echo '<div class="categorylist">';
2346 $html = '';
2347 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2348 if (count($courses) > 0) {
2349 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2352 if ($depth > 0) {
2353 for ($i=0; $i< $depth; $i++) {
2354 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2355 $cat = '';
2357 } else {
2358 $html = $cat;
2361 echo html_writer::tag('div', $html, array('class'=>'category'));
2362 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2363 echo '</div>';
2368 * Print the buttons relating to course requests.
2370 * @param object $systemcontext the system context.
2372 function print_course_request_buttons($systemcontext) {
2373 global $CFG, $DB, $OUTPUT;
2374 if (empty($CFG->enablecourserequests)) {
2375 return;
2377 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2378 /// Print a button to request a new course
2379 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2381 /// Print a button to manage pending requests
2382 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2383 $disabled = !$DB->record_exists('course_request', array());
2384 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2389 * Does the user have permission to edit things in this category?
2391 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2392 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2394 function can_edit_in_category($categoryid = 0) {
2395 $context = get_category_or_system_context($categoryid);
2396 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2400 * Prints the turn editing on/off button on course/index.php or course/category.php.
2402 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2403 * @return string HTML of the editing button, or empty string, if this user is not allowed
2404 * to see it.
2406 function update_category_button($categoryid = 0) {
2407 global $CFG, $PAGE, $OUTPUT;
2409 // Check permissions.
2410 if (!can_edit_in_category($categoryid)) {
2411 return '';
2414 // Work out the appropriate action.
2415 if ($PAGE->user_is_editing()) {
2416 $label = get_string('turneditingoff');
2417 $edit = 'off';
2418 } else {
2419 $label = get_string('turneditingon');
2420 $edit = 'on';
2423 // Generate the button HTML.
2424 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2425 if ($categoryid) {
2426 $options['id'] = $categoryid;
2427 $page = 'category.php';
2428 } else {
2429 $page = 'index.php';
2431 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2435 * Print courses in category. If category is 0 then all courses are printed.
2436 * @param int|stdClass $category category object or id.
2437 * @return bool true if courses found and printed, else false.
2439 function print_courses($category) {
2440 global $CFG, $OUTPUT;
2442 if (!is_object($category) && $category==0) {
2443 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2444 if (is_array($categories) && count($categories) == 1) {
2445 $category = array_shift($categories);
2446 $courses = get_courses_wmanagers($category->id,
2447 'c.sortorder ASC',
2448 array('summary','summaryformat'));
2449 } else {
2450 $courses = get_courses_wmanagers('all',
2451 'c.sortorder ASC',
2452 array('summary','summaryformat'));
2454 unset($categories);
2455 } else {
2456 $courses = get_courses_wmanagers($category->id,
2457 'c.sortorder ASC',
2458 array('summary','summaryformat'));
2461 if ($courses) {
2462 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2463 foreach ($courses as $course) {
2464 $coursecontext = context_course::instance($course->id);
2465 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2466 echo html_writer::start_tag('li');
2467 print_course($course);
2468 echo html_writer::end_tag('li');
2471 echo html_writer::end_tag('ul');
2472 } else {
2473 echo $OUTPUT->heading(get_string("nocoursesyet"));
2474 $context = context_system::instance();
2475 if (has_capability('moodle/course:create', $context)) {
2476 $options = array();
2477 if (!empty($category->id)) {
2478 $options['category'] = $category->id;
2479 } else {
2480 $options['category'] = $CFG->defaultrequestcategory;
2482 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2483 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2484 echo html_writer::end_tag('div');
2485 return false;
2488 return true;
2492 * Print a description of a course, suitable for browsing in a list.
2494 * @param object $course the course object.
2495 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2497 function print_course($course, $highlightterms = '') {
2498 global $CFG, $USER, $DB, $OUTPUT;
2500 $context = context_course::instance($course->id);
2502 // Rewrite file URLs so that they are correct
2503 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2505 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2506 echo html_writer::start_tag('div', array('class'=>'info'));
2507 echo html_writer::start_tag('h3', array('class'=>'name'));
2509 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2511 $coursename = get_course_display_name_for_list($course);
2512 $linktext = highlight($highlightterms, format_string($coursename));
2513 $linkparams = array('title'=>get_string('entercourse'));
2514 if (empty($course->visible)) {
2515 $linkparams['class'] = 'dimmed';
2517 echo html_writer::link($linkhref, $linktext, $linkparams);
2518 echo html_writer::end_tag('h3');
2520 /// first find all roles that are supposed to be displayed
2521 if (!empty($CFG->coursecontact)) {
2522 $managerroles = explode(',', $CFG->coursecontact);
2523 $rusers = array();
2525 if (!isset($course->managers)) {
2526 list($sort, $sortparams) = users_order_by_sql('u');
2527 $rusers = get_role_users($managerroles, $context, true,
2528 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2529 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2530 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2531 } else {
2532 // use the managers array if we have it for perf reasosn
2533 // populate the datastructure like output of get_role_users();
2534 foreach ($course->managers as $manager) {
2535 $user = clone($manager->user);
2536 $user->roleid = $manager->roleid;
2537 $user->rolename = $manager->rolename;
2538 $user->roleshortname = $manager->roleshortname;
2539 $user->rolecoursealias = $manager->rolecoursealias;
2540 $rusers[$user->id] = $user;
2544 $namesarray = array();
2545 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2546 foreach ($rusers as $ra) {
2547 if (isset($namesarray[$ra->id])) {
2548 // only display a user once with the higest sortorder role
2549 continue;
2552 $role = new stdClass();
2553 $role->id = $ra->roleid;
2554 $role->name = $ra->rolename;
2555 $role->shortname = $ra->roleshortname;
2556 $role->coursealias = $ra->rolecoursealias;
2557 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2559 $fullname = fullname($ra, $canviewfullnames);
2560 $namesarray[$ra->id] = $rolename.': '.
2561 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2564 if (!empty($namesarray)) {
2565 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2566 foreach ($namesarray as $name) {
2567 echo html_writer::tag('li', $name);
2569 echo html_writer::end_tag('ul');
2572 echo html_writer::end_tag('div'); // End of info div
2574 echo html_writer::start_tag('div', array('class'=>'summary'));
2575 $options = new stdClass();
2576 $options->noclean = true;
2577 $options->para = false;
2578 $options->overflowdiv = true;
2579 if (!isset($course->summaryformat)) {
2580 $course->summaryformat = FORMAT_MOODLE;
2582 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2583 if ($icons = enrol_get_course_info_icons($course)) {
2584 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2585 foreach ($icons as $icon) {
2586 $icon->attributes["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
2587 echo $OUTPUT->render($icon);
2589 echo html_writer::end_tag('div'); // End of enrolmenticons div
2591 echo html_writer::end_tag('div'); // End of summary div
2592 echo html_writer::end_tag('div'); // End of coursebox div
2596 * Prints custom user information on the home page.
2597 * Over time this can include all sorts of information
2599 function print_my_moodle() {
2600 global $USER, $CFG, $DB, $OUTPUT;
2602 if (!isloggedin() or isguestuser()) {
2603 print_error('nopermissions', '', '', 'See My Moodle');
2606 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2607 $rhosts = array();
2608 $rcourses = array();
2609 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2610 $rcourses = get_my_remotecourses($USER->id);
2611 $rhosts = get_my_remotehosts();
2614 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2616 if (!empty($courses)) {
2617 echo '<ul class="unlist">';
2618 foreach ($courses as $course) {
2619 if ($course->id == SITEID) {
2620 continue;
2622 echo '<li>';
2623 print_course($course);
2624 echo "</li>\n";
2626 echo "</ul>\n";
2629 // MNET
2630 if (!empty($rcourses)) {
2631 // at the IDP, we know of all the remote courses
2632 foreach ($rcourses as $course) {
2633 print_remote_course($course, "100%");
2635 } elseif (!empty($rhosts)) {
2636 // non-IDP, we know of all the remote servers, but not courses
2637 foreach ($rhosts as $host) {
2638 print_remote_host($host, "100%");
2641 unset($course);
2642 unset($host);
2644 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2645 echo "<table width=\"100%\"><tr><td align=\"center\">";
2646 print_course_search("", false, "short");
2647 echo "</td><td align=\"center\">";
2648 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2649 echo "</td></tr></table>\n";
2652 } else {
2653 if ($DB->count_records("course_categories") > 1) {
2654 echo $OUTPUT->box_start("categorybox");
2655 print_whole_category_list();
2656 echo $OUTPUT->box_end();
2657 } else {
2658 print_courses(0);
2664 function print_course_search($value="", $return=false, $format="plain") {
2665 global $CFG;
2666 static $count = 0;
2668 $count++;
2670 $id = 'coursesearch';
2672 if ($count > 1) {
2673 $id .= $count;
2676 $strsearchcourses= get_string("searchcourses");
2678 if ($format == 'plain') {
2679 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2680 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2681 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2682 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2683 $output .= '<input type="submit" value="'.get_string('go').'" />';
2684 $output .= '</fieldset></form>';
2685 } else if ($format == 'short') {
2686 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2687 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2688 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2689 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" value="'.s($value).'" />';
2690 $output .= '<input type="submit" value="'.get_string('go').'" />';
2691 $output .= '</fieldset></form>';
2692 } else if ($format == 'navbar') {
2693 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2694 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2695 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2696 $output .= '<input type="text" id="navsearchbox" size="20" name="search" value="'.s($value).'" />';
2697 $output .= '<input type="submit" value="'.get_string('go').'" />';
2698 $output .= '</fieldset></form>';
2701 if ($return) {
2702 return $output;
2704 echo $output;
2707 function print_remote_course($course, $width="100%") {
2708 global $CFG, $USER;
2710 $linkcss = '';
2712 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2714 echo '<div class="coursebox remotecoursebox clearfix">';
2715 echo '<div class="info">';
2716 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2717 $linkcss.' href="'.$url.'">'
2718 . format_string($course->fullname) .'</a><br />'
2719 . format_string($course->hostname) . ' : '
2720 . format_string($course->cat_name) . ' : '
2721 . format_string($course->shortname). '</div>';
2722 echo '</div><div class="summary">';
2723 $options = new stdClass();
2724 $options->noclean = true;
2725 $options->para = false;
2726 $options->overflowdiv = true;
2727 echo format_text($course->summary, $course->summaryformat, $options);
2728 echo '</div>';
2729 echo '</div>';
2732 function print_remote_host($host, $width="100%") {
2733 global $OUTPUT;
2735 $linkcss = '';
2737 echo '<div class="coursebox clearfix">';
2738 echo '<div class="info">';
2739 echo '<div class="name">';
2740 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2741 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2742 . s($host['name']).'</a> - ';
2743 echo $host['count'] . ' ' . get_string('courses');
2744 echo '</div>';
2745 echo '</div>';
2746 echo '</div>';
2750 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2752 function add_course_module($mod) {
2753 global $DB;
2755 $mod->added = time();
2756 unset($mod->id);
2758 $cmid = $DB->insert_record("course_modules", $mod);
2759 rebuild_course_cache($mod->course, true);
2760 return $cmid;
2764 * Creates missing course section(s) and rebuilds course cache
2766 * @param int|stdClass $courseorid course id or course object
2767 * @param int|array $sections list of relative section numbers to create
2768 * @return bool if there were any sections created
2770 function course_create_sections_if_missing($courseorid, $sections) {
2771 global $DB;
2772 if (!is_array($sections)) {
2773 $sections = array($sections);
2775 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2776 if (is_object($courseorid)) {
2777 $courseorid = $courseorid->id;
2779 $coursechanged = false;
2780 foreach ($sections as $sectionnum) {
2781 if (!in_array($sectionnum, $existing)) {
2782 $cw = new stdClass();
2783 $cw->course = $courseorid;
2784 $cw->section = $sectionnum;
2785 $cw->summary = '';
2786 $cw->summaryformat = FORMAT_HTML;
2787 $cw->sequence = '';
2788 $id = $DB->insert_record("course_sections", $cw);
2789 $coursechanged = true;
2792 if ($coursechanged) {
2793 rebuild_course_cache($courseorid, true);
2795 return $coursechanged;
2799 * Adds an existing module to the section
2801 * Updates both tables {course_sections} and {course_modules}
2803 * Note: This function does not use modinfo PROVIDED that the section you are
2804 * adding the module to already exists. If the section does not exist, it will
2805 * build modinfo if necessary and create the section.
2807 * @param int|stdClass $courseorid course id or course object
2808 * @param int $cmid id of the module already existing in course_modules table
2809 * @param int $sectionnum relative number of the section (field course_sections.section)
2810 * If section does not exist it will be created
2811 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2812 * before which the module needs to be included. Null for inserting in the
2813 * end of the section
2814 * @return int The course_sections ID where the module is inserted
2816 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2817 global $DB, $COURSE;
2818 if (is_object($beforemod)) {
2819 $beforemod = $beforemod->id;
2821 if (is_object($courseorid)) {
2822 $courseid = $courseorid->id;
2823 } else {
2824 $courseid = $courseorid;
2826 // Do not try to use modinfo here, there is no guarantee it is valid!
2827 $section = $DB->get_record('course_sections',
2828 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
2829 if (!$section) {
2830 // This function call requires modinfo.
2831 course_create_sections_if_missing($courseorid, $sectionnum);
2832 $section = $DB->get_record('course_sections',
2833 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
2836 $modarray = explode(",", trim($section->sequence));
2837 if (empty($section->sequence)) {
2838 $newsequence = "$cmid";
2839 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2840 $insertarray = array($cmid, $beforemod);
2841 array_splice($modarray, $key[0], 1, $insertarray);
2842 $newsequence = implode(",", $modarray);
2843 } else {
2844 $newsequence = "$section->sequence,$cmid";
2846 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2847 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
2848 if (is_object($courseorid)) {
2849 rebuild_course_cache($courseorid->id, true);
2850 } else {
2851 rebuild_course_cache($courseorid, true);
2853 return $section->id; // Return course_sections ID that was used.
2856 function set_coursemodule_groupmode($id, $groupmode) {
2857 global $DB;
2858 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2859 if ($cm->groupmode != $groupmode) {
2860 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2861 rebuild_course_cache($cm->course, true);
2863 return ($cm->groupmode != $groupmode);
2866 function set_coursemodule_idnumber($id, $idnumber) {
2867 global $DB;
2868 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2869 if ($cm->idnumber != $idnumber) {
2870 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2871 rebuild_course_cache($cm->course, true);
2873 return ($cm->idnumber != $idnumber);
2877 * Set the visibility of a module and inherent properties.
2879 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2880 * has been moved to {@link set_section_visible()} which was the only place from which
2881 * the parameter was used.
2883 * @param int $id of the module
2884 * @param int $visible state of the module
2885 * @return bool false when the module was not found, true otherwise
2887 function set_coursemodule_visible($id, $visible) {
2888 global $DB, $CFG;
2889 require_once($CFG->libdir.'/gradelib.php');
2891 // Trigger developer's attention when using the previously removed argument.
2892 if (func_num_args() > 2) {
2893 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2894 has been removed.', DEBUG_DEVELOPER);
2897 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2898 return false;
2901 // Create events and propagate visibility to associated grade items if the value has changed.
2902 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
2903 if ($cm->visible == $visible) {
2904 return true;
2907 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2908 return false;
2910 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2911 foreach($events as $event) {
2912 if ($visible) {
2913 show_event($event);
2914 } else {
2915 hide_event($event);
2920 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2921 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2922 if ($grade_items) {
2923 foreach ($grade_items as $grade_item) {
2924 $grade_item->set_hidden(!$visible);
2928 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2929 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2930 $cminfo = new stdClass();
2931 $cminfo->id = $id;
2932 $cminfo->visible = $visible;
2933 $cminfo->visibleold = $visible;
2934 $DB->update_record('course_modules', $cminfo);
2936 rebuild_course_cache($cm->course, true);
2937 return true;
2941 * Delete a course module and any associated data at the course level (events)
2942 * Until 1.5 this function simply marked a deleted flag ... now it
2943 * deletes it completely.
2946 function delete_course_module($id) {
2947 global $CFG, $DB;
2948 require_once($CFG->libdir.'/gradelib.php');
2949 require_once($CFG->dirroot.'/blog/lib.php');
2951 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2952 return true;
2954 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2955 //delete events from calendar
2956 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2957 foreach($events as $event) {
2958 delete_event($event->id);
2961 //delete grade items, outcome items and grades attached to modules
2962 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2963 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2964 foreach ($grade_items as $grade_item) {
2965 $grade_item->delete('moddelete');
2968 // Delete completion and availability data; it is better to do this even if the
2969 // features are not turned on, in case they were turned on previously (these will be
2970 // very quick on an empty table)
2971 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2972 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2973 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2974 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2975 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2977 delete_context(CONTEXT_MODULE, $cm->id);
2978 $DB->delete_records('course_modules', array('id'=>$cm->id));
2979 rebuild_course_cache($cm->course, true);
2980 return true;
2983 function delete_mod_from_section($modid, $sectionid) {
2984 global $DB;
2986 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2988 $modarray = explode(",", $section->sequence);
2990 if ($key = array_keys ($modarray, $modid)) {
2991 array_splice($modarray, $key[0], 1);
2992 $newsequence = implode(",", $modarray);
2993 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2994 rebuild_course_cache($section->course, true);
2995 return true;
2996 } else {
2997 return false;
3001 return false;
3005 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
3007 * @param object $course course object
3008 * @param int $section Section number (not id!!!)
3009 * @param int $move (-1 or 1)
3010 * @return boolean true if section moved successfully
3011 * @todo MDL-33379 remove this function in 2.5
3013 function move_section($course, $section, $move) {
3014 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
3016 /// Moves a whole course section up and down within the course
3017 global $USER;
3019 if (!$move) {
3020 return true;
3023 $sectiondest = $section + $move;
3025 // compartibility with course formats using field 'numsections'
3026 $courseformatoptions = course_get_format($course)->get_format_options();
3027 if (array_key_exists('numsections', $courseformatoptions) &&
3028 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
3029 return false;
3032 $retval = move_section_to($course, $section, $sectiondest);
3033 return $retval;
3037 * Moves a section within a course, from a position to another.
3038 * Be very careful: $section and $destination refer to section number,
3039 * not id!.
3041 * @param object $course
3042 * @param int $section Section number (not id!!!)
3043 * @param int $destination
3044 * @return boolean Result
3046 function move_section_to($course, $section, $destination) {
3047 /// Moves a whole course section up and down within the course
3048 global $USER, $DB;
3050 if (!$destination && $destination != 0) {
3051 return true;
3054 // compartibility with course formats using field 'numsections'
3055 $courseformatoptions = course_get_format($course)->get_format_options();
3056 if ((array_key_exists('numsections', $courseformatoptions) &&
3057 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3058 return false;
3061 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3062 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3063 'section ASC, id ASC', 'id, section')) {
3064 return false;
3067 $movedsections = reorder_sections($sections, $section, $destination);
3069 // Update all sections. Do this in 2 steps to avoid breaking database
3070 // uniqueness constraint
3071 $transaction = $DB->start_delegated_transaction();
3072 foreach ($movedsections as $id => $position) {
3073 if ($sections[$id] !== $position) {
3074 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3077 foreach ($movedsections as $id => $position) {
3078 if ($sections[$id] !== $position) {
3079 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3083 // If we move the highlighted section itself, then just highlight the destination.
3084 // Adjust the higlighted section location if we move something over it either direction.
3085 if ($section == $course->marker) {
3086 course_set_marker($course->id, $destination);
3087 } elseif ($section > $course->marker && $course->marker >= $destination) {
3088 course_set_marker($course->id, $course->marker+1);
3089 } elseif ($section < $course->marker && $course->marker <= $destination) {
3090 course_set_marker($course->id, $course->marker-1);
3093 $transaction->allow_commit();
3094 rebuild_course_cache($course->id, true);
3095 return true;
3099 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3100 * an original position number and a target position number, rebuilds the array so that the
3101 * move is made without any duplication of section positions.
3102 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3103 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3105 * @param array $sections
3106 * @param int $origin_position
3107 * @param int $target_position
3108 * @return array
3110 function reorder_sections($sections, $origin_position, $target_position) {
3111 if (!is_array($sections)) {
3112 return false;
3115 // We can't move section position 0
3116 if ($origin_position < 1) {
3117 echo "We can't move section position 0";
3118 return false;
3121 // Locate origin section in sections array
3122 if (!$origin_key = array_search($origin_position, $sections)) {
3123 echo "searched position not in sections array";
3124 return false; // searched position not in sections array
3127 // Extract origin section
3128 $origin_section = $sections[$origin_key];
3129 unset($sections[$origin_key]);
3131 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3132 $found = false;
3133 $append_array = array();
3134 foreach ($sections as $id => $position) {
3135 if ($found) {
3136 $append_array[$id] = $position;
3137 unset($sections[$id]);
3139 if ($position == $target_position) {
3140 if ($target_position < $origin_position) {
3141 $append_array[$id] = $position;
3142 unset($sections[$id]);
3144 $found = true;
3148 // Append moved section
3149 $sections[$origin_key] = $origin_section;
3151 // Append rest of array (if applicable)
3152 if (!empty($append_array)) {
3153 foreach ($append_array as $id => $position) {
3154 $sections[$id] = $position;
3158 // Renumber positions
3159 $position = 0;
3160 foreach ($sections as $id => $p) {
3161 $sections[$id] = $position;
3162 $position++;
3165 return $sections;
3170 * Move the module object $mod to the specified $section
3171 * If $beforemod exists then that is the module
3172 * before which $modid should be inserted
3173 * All parameters are objects
3175 function moveto_module($mod, $section, $beforemod=NULL) {
3176 global $OUTPUT, $DB;
3178 /// Remove original module from original section
3179 if (! delete_mod_from_section($mod->id, $mod->section)) {
3180 echo $OUTPUT->notification("Could not delete module from existing section");
3183 // if moving to a hidden section then hide module
3184 if ($mod->section != $section->id) {
3185 if (!$section->visible && $mod->visible) {
3186 // Set this in the object because it is sent as a response to ajax calls.
3187 $mod->visible = 0;
3188 set_coursemodule_visible($mod->id, 0);
3189 // Set visibleold to 1 so module will be visible when section is made visible.
3190 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
3192 if ($section->visible && !$mod->visible) {
3193 set_coursemodule_visible($mod->id, $mod->visibleold);
3194 // Set this in the object because it is sent as a response to ajax calls.
3195 $mod->visible = $mod->visibleold;
3199 /// Add the module into the new section
3200 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3201 return true;
3205 * Produces the editing buttons for a module
3207 * @global core_renderer $OUTPUT
3208 * @staticvar type $str
3209 * @param stdClass $mod The module to produce editing buttons for
3210 * @param bool $absolute_ignored ignored - all links are absolute
3211 * @param bool $moveselect If true a move seleciton process is used (default true)
3212 * @param int $indent The current indenting
3213 * @param int $section The section to link back to
3214 * @return string XHTML for the editing buttons
3216 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3217 global $CFG, $OUTPUT, $COURSE;
3219 static $str;
3221 $coursecontext = context_course::instance($mod->course);
3222 $modcontext = context_module::instance($mod->id);
3224 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3225 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3227 // no permission to edit anything
3228 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3229 return false;
3232 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3234 if (!isset($str)) {
3235 $str = new stdClass;
3236 $str->assign = get_string("assignroles", 'role');
3237 $str->delete = get_string("delete");
3238 $str->move = get_string("move");
3239 $str->moveup = get_string("moveup");
3240 $str->movedown = get_string("movedown");
3241 $str->moveright = get_string("moveright");
3242 $str->moveleft = get_string("moveleft");
3243 $str->update = get_string("update");
3244 $str->duplicate = get_string("duplicate");
3245 $str->hide = get_string("hide");
3246 $str->show = get_string("show");
3247 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3248 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3249 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3250 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3251 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3252 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3253 $str->edittitle = get_string('edittitle', 'moodle');
3256 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3258 if ($section !== null) {
3259 $baseurl->param('sr', $section);
3261 $actions = array();
3263 // AJAX edit title
3264 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3265 $actions[] = new action_link(
3266 new moodle_url($baseurl, array('update' => $mod->id)),
3267 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3268 null,
3269 array('class' => 'editing_title', 'title' => $str->edittitle)
3273 // leftright
3274 if ($hasmanageactivities) {
3275 if (right_to_left()) { // Exchange arrows on RTL
3276 $rightarrow = 't/left';
3277 $leftarrow = 't/right';
3278 } else {
3279 $rightarrow = 't/right';
3280 $leftarrow = 't/left';
3283 if ($indent > 0) {
3284 $actions[] = new action_link(
3285 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3286 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3287 null,
3288 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3291 if ($indent >= 0) {
3292 $actions[] = new action_link(
3293 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3294 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3295 null,
3296 array('class' => 'editing_moveright', 'title' => $str->moveright)
3301 // move
3302 if ($hasmanageactivities) {
3303 if ($moveselect) {
3304 $actions[] = new action_link(
3305 new moodle_url($baseurl, array('copy' => $mod->id)),
3306 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3307 null,
3308 array('class' => 'editing_move', 'title' => $str->move)
3310 } else {
3311 $actions[] = new action_link(
3312 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3313 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3314 null,
3315 array('class' => 'editing_moveup', 'title' => $str->moveup)
3317 $actions[] = new action_link(
3318 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3319 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3320 null,
3321 array('class' => 'editing_movedown', 'title' => $str->movedown)
3326 // Update
3327 if ($hasmanageactivities) {
3328 $actions[] = new action_link(
3329 new moodle_url($baseurl, array('update' => $mod->id)),
3330 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3331 null,
3332 array('class' => 'editing_update', 'title' => $str->update)
3336 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3337 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3338 $actions[] = new action_link(
3339 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3340 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3341 null,
3342 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3346 // Delete
3347 if ($hasmanageactivities) {
3348 $actions[] = new action_link(
3349 new moodle_url($baseurl, array('delete' => $mod->id)),
3350 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3351 null,
3352 array('class' => 'editing_delete', 'title' => $str->delete)
3356 // hideshow
3357 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3358 if ($mod->visible) {
3359 $actions[] = new action_link(
3360 new moodle_url($baseurl, array('hide' => $mod->id)),
3361 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3362 null,
3363 array('class' => 'editing_hide', 'title' => $str->hide)
3365 } else {
3366 $actions[] = new action_link(
3367 new moodle_url($baseurl, array('show' => $mod->id)),
3368 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3369 null,
3370 array('class' => 'editing_show', 'title' => $str->show)
3375 // groupmode
3376 if ($hasmanageactivities and $mod->groupmode !== false) {
3377 if ($mod->groupmode == SEPARATEGROUPS) {
3378 $groupmode = 0;
3379 $grouptitle = $str->groupsseparate;
3380 $forcedgrouptitle = $str->forcedgroupsseparate;
3381 $groupclass = 'editing_groupsseparate';
3382 $groupimage = 't/groups';
3383 } else if ($mod->groupmode == VISIBLEGROUPS) {
3384 $groupmode = 1;
3385 $grouptitle = $str->groupsvisible;
3386 $forcedgrouptitle = $str->forcedgroupsvisible;
3387 $groupclass = 'editing_groupsvisible';
3388 $groupimage = 't/groupv';
3389 } else {
3390 $groupmode = 2;
3391 $grouptitle = $str->groupsnone;
3392 $forcedgrouptitle = $str->forcedgroupsnone;
3393 $groupclass = 'editing_groupsnone';
3394 $groupimage = 't/groupn';
3396 if ($mod->groupmodelink) {
3397 $actions[] = new action_link(
3398 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3399 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3400 null,
3401 array('class' => $groupclass, 'title' => $grouptitle)
3403 } else {
3404 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3408 // Assign
3409 if (has_capability('moodle/role:assign', $modcontext)){
3410 $actions[] = new action_link(
3411 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3412 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3413 null,
3414 array('class' => 'editing_assign', 'title' => $str->assign)
3418 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
3419 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
3420 // the course page HTML will allow this to be removed.
3421 $output = ' ' . html_writer::start_tag('span', array('class' => 'commands'));
3422 foreach ($actions as $action) {
3423 if ($action instanceof renderable) {
3424 $output .= $OUTPUT->render($action);
3425 } else {
3426 $output .= $action;
3429 $output .= html_writer::end_tag('span');
3430 return $output;
3434 * given a course object with shortname & fullname, this function will
3435 * truncate the the number of chars allowed and add ... if it was too long
3437 function course_format_name ($course,$max=100) {
3439 $context = context_course::instance($course->id);
3440 $shortname = format_string($course->shortname, true, array('context' => $context));
3441 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3442 $str = $shortname.': '. $fullname;
3443 if (textlib::strlen($str) <= $max) {
3444 return $str;
3446 else {
3447 return textlib::substr($str,0,$max-3).'...';
3452 * Is the user allowed to add this type of module to this course?
3453 * @param object $course the course settings. Only $course->id is used.
3454 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3455 * @return bool whether the current user is allowed to add this type of module to this course.
3457 function course_allowed_module($course, $modname) {
3458 if (is_numeric($modname)) {
3459 throw new coding_exception('Function course_allowed_module no longer
3460 supports numeric module ids. Please update your code to pass the module name.');
3463 $capability = 'mod/' . $modname . ':addinstance';
3464 if (!get_capability_info($capability)) {
3465 // Debug warning that the capability does not exist, but no more than once per page.
3466 static $warned = array();
3467 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3468 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3469 debugging('The module ' . $modname . ' does not define the standard capability ' .
3470 $capability , DEBUG_DEVELOPER);
3471 $warned[$modname] = 1;
3474 // If the capability does not exist, the module can always be added.
3475 return true;
3478 $coursecontext = context_course::instance($course->id);
3479 return has_capability($capability, $coursecontext);
3483 * Recursively delete category including all subcategories and courses.
3484 * @param stdClass $category
3485 * @param boolean $showfeedback display some notices
3486 * @return array return deleted courses
3488 function category_delete_full($category, $showfeedback=true) {
3489 global $CFG, $DB;
3490 require_once($CFG->libdir.'/gradelib.php');
3491 require_once($CFG->libdir.'/questionlib.php');
3492 require_once($CFG->dirroot.'/cohort/lib.php');
3494 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3495 foreach ($children as $childcat) {
3496 category_delete_full($childcat, $showfeedback);
3500 $deletedcourses = array();
3501 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3502 foreach ($courses as $course) {
3503 if (!delete_course($course, false)) {
3504 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3506 $deletedcourses[] = $course;
3510 // move or delete cohorts in this context
3511 cohort_delete_category($category);
3513 // now delete anything that may depend on course category context
3514 grade_course_category_delete($category->id, 0, $showfeedback);
3515 if (!question_delete_course_category($category, 0, $showfeedback)) {
3516 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3519 // finally delete the category and it's context
3520 $DB->delete_records('course_categories', array('id'=>$category->id));
3521 delete_context(CONTEXT_COURSECAT, $category->id);
3522 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3524 events_trigger('course_category_deleted', $category);
3526 return $deletedcourses;
3530 * Delete category, but move contents to another category.
3531 * @param object $ccategory
3532 * @param int $newparentid category id
3533 * @return bool status
3535 function category_delete_move($category, $newparentid, $showfeedback=true) {
3536 global $CFG, $DB, $OUTPUT;
3537 require_once($CFG->libdir.'/gradelib.php');
3538 require_once($CFG->libdir.'/questionlib.php');
3539 require_once($CFG->dirroot.'/cohort/lib.php');
3541 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3542 return false;
3545 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3546 foreach ($children as $childcat) {
3547 move_category($childcat, $newparentcat);
3551 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3552 if (!move_courses(array_keys($courses), $newparentid)) {
3553 if ($showfeedback) {
3554 echo $OUTPUT->notification("Error moving courses");
3556 return false;
3558 if ($showfeedback) {
3559 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3563 // move or delete cohorts in this context
3564 cohort_delete_category($category);
3566 // now delete anything that may depend on course category context
3567 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3568 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3569 if ($showfeedback) {
3570 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3572 return false;
3575 // finally delete the category and it's context
3576 $DB->delete_records('course_categories', array('id'=>$category->id));
3577 delete_context(CONTEXT_COURSECAT, $category->id);
3578 add_to_log(SITEID, "category", "delete", "index.php", "$category->name (ID $category->id)");
3580 events_trigger('course_category_deleted', $category);
3582 if ($showfeedback) {
3583 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3585 return true;
3589 * Efficiently moves many courses around while maintaining
3590 * sortorder in order.
3592 * @param array $courseids is an array of course ids
3593 * @param int $categoryid
3594 * @return bool success
3596 function move_courses($courseids, $categoryid) {
3597 global $CFG, $DB, $OUTPUT;
3599 if (empty($courseids)) {
3600 // nothing to do
3601 return;
3604 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3605 return false;
3608 $courseids = array_reverse($courseids);
3609 $newparent = context_coursecat::instance($category->id);
3610 $i = 1;
3612 foreach ($courseids as $courseid) {
3613 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3614 $course = new stdClass();
3615 $course->id = $courseid;
3616 $course->category = $category->id;
3617 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3618 if ($category->visible == 0) {
3619 // hide the course when moving into hidden category,
3620 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3621 $course->visible = 0;
3624 $DB->update_record('course', $course);
3625 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
3627 $context = context_course::instance($course->id);
3628 context_moved($context, $newparent);
3631 fix_course_sortorder();
3633 return true;
3637 * Hide course category and child course and subcategories
3638 * @param stdClass $category
3639 * @return void
3641 function course_category_hide($category) {
3642 global $DB;
3644 $category->visible = 0;
3645 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3646 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3647 $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
3648 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3649 // get all child categories and hide too
3650 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3651 foreach ($subcats as $cat) {
3652 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3653 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3654 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3655 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3658 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$category->id", $category->id);
3662 * Show course category and child course and subcategories
3663 * @param stdClass $category
3664 * @return void
3666 function course_category_show($category) {
3667 global $DB;
3669 $category->visible = 1;
3670 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3671 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3672 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3673 // get all child categories and unhide too
3674 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3675 foreach ($subcats as $cat) {
3676 if ($cat->visibleold) {
3677 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3679 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3682 add_to_log(SITEID, "category", "show", "editcategory.php?id=$category->id", $category->id);
3686 * Efficiently moves a category - NOTE that this can have
3687 * a huge impact access-control-wise...
3689 function move_category($category, $newparentcat) {
3690 global $CFG, $DB;
3692 $context = context_coursecat::instance($category->id);
3694 $hidecat = false;
3695 if (empty($newparentcat->id)) {
3696 $DB->set_field('course_categories', 'parent', 0, array('id' => $category->id));
3697 $newparent = context_system::instance();
3698 } else {
3699 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $category->id));
3700 $newparent = context_coursecat::instance($newparentcat->id);
3702 if (!$newparentcat->visible and $category->visible) {
3703 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3704 $hidecat = true;
3708 context_moved($context, $newparent);
3710 // now make it last in new category
3711 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3713 // Log action.
3714 add_to_log(SITEID, "category", "move", "editcategory.php?id=$category->id", $category->id);
3716 // and fix the sortorders
3717 fix_course_sortorder();
3719 if ($hidecat) {
3720 course_category_hide($category);
3725 * Returns the display name of the given section that the course prefers
3727 * Implementation of this function is provided by course format
3728 * @see format_base::get_section_name()
3730 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
3731 * @param int|stdClass $section Section object from database or just field course_sections.section
3732 * @return string Display name that the course format prefers, e.g. "Week 2"
3734 function get_section_name($courseorid, $section) {
3735 return course_get_format($courseorid)->get_section_name($section);
3739 * Tells if current course format uses sections
3741 * @param string $format Course format ID e.g. 'weeks' $course->format
3742 * @return bool
3744 function course_format_uses_sections($format) {
3745 $course = new stdClass();
3746 $course->format = $format;
3747 return course_get_format($course)->uses_sections();
3751 * Returns the information about the ajax support in the given source format
3753 * The returned object's property (boolean)capable indicates that
3754 * the course format supports Moodle course ajax features.
3755 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3757 * @param string $format
3758 * @return stdClass
3760 function course_format_ajax_support($format) {
3761 $course = new stdClass();
3762 $course->format = $format;
3763 return course_get_format($course)->supports_ajax();
3767 * Can the current user delete this course?
3768 * Course creators have exception,
3769 * 1 day after the creation they can sill delete the course.
3770 * @param int $courseid
3771 * @return boolean
3773 function can_delete_course($courseid) {
3774 global $USER, $DB;
3776 $context = context_course::instance($courseid);
3778 if (has_capability('moodle/course:delete', $context)) {
3779 return true;
3782 // hack: now try to find out if creator created this course recently (1 day)
3783 if (!has_capability('moodle/course:create', $context)) {
3784 return false;
3787 $since = time() - 60*60*24;
3789 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3790 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3792 return $DB->record_exists_select('log', $select, $params);
3796 * Save the Your name for 'Some role' strings.
3798 * @param integer $courseid the id of this course.
3799 * @param array $data the data that came from the course settings form.
3801 function save_local_role_names($courseid, $data) {
3802 global $DB;
3803 $context = context_course::instance($courseid);
3805 foreach ($data as $fieldname => $value) {
3806 if (strpos($fieldname, 'role_') !== 0) {
3807 continue;
3809 list($ignored, $roleid) = explode('_', $fieldname);
3811 // make up our mind whether we want to delete, update or insert
3812 if (!$value) {
3813 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3815 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3816 $rolename->name = $value;
3817 $DB->update_record('role_names', $rolename);
3819 } else {
3820 $rolename = new stdClass;
3821 $rolename->contextid = $context->id;
3822 $rolename->roleid = $roleid;
3823 $rolename->name = $value;
3824 $DB->insert_record('role_names', $rolename);
3830 * Create a course and either return a $course object
3832 * Please note this functions does not verify any access control,
3833 * the calling code is responsible for all validation (usually it is the form definition).
3835 * @param array $editoroptions course description editor options
3836 * @param object $data - all the data needed for an entry in the 'course' table
3837 * @return object new course instance
3839 function create_course($data, $editoroptions = NULL) {
3840 global $CFG, $DB;
3842 //check the categoryid - must be given for all new courses
3843 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3845 //check if the shortname already exist
3846 if (!empty($data->shortname)) {
3847 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3848 throw new moodle_exception('shortnametaken');
3852 //check if the id number already exist
3853 if (!empty($data->idnumber)) {
3854 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3855 throw new moodle_exception('idnumbertaken');
3859 $data->timecreated = time();
3860 $data->timemodified = $data->timecreated;
3862 // place at beginning of any category
3863 $data->sortorder = 0;
3865 if ($editoroptions) {
3866 // summary text is updated later, we need context to store the files first
3867 $data->summary = '';
3868 $data->summary_format = FORMAT_HTML;
3871 if (!isset($data->visible)) {
3872 // data not from form, add missing visibility info
3873 $data->visible = $category->visible;
3875 $data->visibleold = $data->visible;
3877 $newcourseid = $DB->insert_record('course', $data);
3878 $context = context_course::instance($newcourseid, MUST_EXIST);
3880 if ($editoroptions) {
3881 // Save the files used in the summary editor and store
3882 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3883 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3884 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3887 // update course format options
3888 course_get_format($newcourseid)->update_course_format_options($data);
3890 $course = course_get_format($newcourseid)->get_course();
3892 // Setup the blocks
3893 blocks_add_default_course_blocks($course);
3895 // Create a default section.
3896 course_create_sections_if_missing($course, 0);
3898 fix_course_sortorder();
3900 // new context created - better mark it as dirty
3901 mark_context_dirty($context->path);
3903 // Save any custom role names.
3904 save_local_role_names($course->id, (array)$data);
3906 // set up enrolments
3907 enrol_course_updated(true, $course, $data);
3909 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3911 // Trigger events
3912 events_trigger('course_created', $course);
3914 return $course;
3918 * Create a new course category and marks the context as dirty
3920 * This function does not set the sortorder for the new category and
3921 * @see{fix_course_sortorder} should be called after creating a new course
3922 * category
3924 * Please note that this function does not verify access control.
3926 * @param object $category All of the data required for an entry in the course_categories table
3927 * @return object new course category
3929 function create_course_category($category) {
3930 global $DB;
3932 $category->timemodified = time();
3933 $category->id = $DB->insert_record('course_categories', $category);
3934 $category = $DB->get_record('course_categories', array('id' => $category->id));
3936 // We should mark the context as dirty
3937 $category->context = context_coursecat::instance($category->id);
3938 $category->context->mark_dirty();
3940 return $category;
3944 * Update a course.
3946 * Please note this functions does not verify any access control,
3947 * the calling code is responsible for all validation (usually it is the form definition).
3949 * @param object $data - all the data needed for an entry in the 'course' table
3950 * @param array $editoroptions course description editor options
3951 * @return void
3953 function update_course($data, $editoroptions = NULL) {
3954 global $CFG, $DB;
3956 $data->timemodified = time();
3958 $oldcourse = course_get_format($data->id)->get_course();
3959 $context = context_course::instance($oldcourse->id);
3961 if ($editoroptions) {
3962 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3965 if (!isset($data->category) or empty($data->category)) {
3966 // prevent nulls and 0 in category field
3967 unset($data->category);
3969 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3971 if (!isset($data->visible)) {
3972 // data not from form, add missing visibility info
3973 $data->visible = $oldcourse->visible;
3976 if ($data->visible != $oldcourse->visible) {
3977 // reset the visibleold flag when manually hiding/unhiding course
3978 $data->visibleold = $data->visible;
3979 } else {
3980 if ($movecat) {
3981 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3982 if (empty($newcategory->visible)) {
3983 // make sure when moving into hidden category the course is hidden automatically
3984 $data->visible = 0;
3989 // Update with the new data
3990 $DB->update_record('course', $data);
3991 // make sure the modinfo cache is reset
3992 rebuild_course_cache($data->id);
3994 // update course format options with full course data
3995 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
3997 $course = $DB->get_record('course', array('id'=>$data->id));
3999 if ($movecat) {
4000 $newparent = context_coursecat::instance($course->category);
4001 context_moved($context, $newparent);
4004 fix_course_sortorder();
4006 // Test for and remove blocks which aren't appropriate anymore
4007 blocks_remove_inappropriate($course);
4009 // Save any custom role names.
4010 save_local_role_names($course->id, $data);
4012 // update enrol settings
4013 enrol_course_updated(false, $course, $data);
4015 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
4017 // Trigger events
4018 events_trigger('course_updated', $course);
4020 if ($oldcourse->format !== $course->format) {
4021 // Remove all options stored for the previous format
4022 // We assume that new course format migrated everything it needed watching trigger
4023 // 'course_updated' and in method format_XXX::update_course_format_options()
4024 $DB->delete_records('course_format_options',
4025 array('courseid' => $course->id, 'format' => $oldcourse->format));
4030 * Average number of participants
4031 * @return integer
4033 function average_number_of_participants() {
4034 global $DB, $SITE;
4036 //count total of enrolments for visible course (except front page)
4037 $sql = 'SELECT COUNT(*) FROM (
4038 SELECT DISTINCT ue.userid, e.courseid
4039 FROM {user_enrolments} ue, {enrol} e, {course} c
4040 WHERE ue.enrolid = e.id
4041 AND e.courseid <> :siteid
4042 AND c.id = e.courseid
4043 AND c.visible = 1) total';
4044 $params = array('siteid' => $SITE->id);
4045 $enrolmenttotal = $DB->count_records_sql($sql, $params);
4048 //count total of visible courses (minus front page)
4049 $coursetotal = $DB->count_records('course', array('visible' => 1));
4050 $coursetotal = $coursetotal - 1 ;
4052 //average of enrolment
4053 if (empty($coursetotal)) {
4054 $participantaverage = 0;
4055 } else {
4056 $participantaverage = $enrolmenttotal / $coursetotal;
4059 return $participantaverage;
4063 * Average number of course modules
4064 * @return integer
4066 function average_number_of_courses_modules() {
4067 global $DB, $SITE;
4069 //count total of visible course module (except front page)
4070 $sql = 'SELECT COUNT(*) FROM (
4071 SELECT cm.course, cm.module
4072 FROM {course} c, {course_modules} cm
4073 WHERE c.id = cm.course
4074 AND c.id <> :siteid
4075 AND cm.visible = 1
4076 AND c.visible = 1) total';
4077 $params = array('siteid' => $SITE->id);
4078 $moduletotal = $DB->count_records_sql($sql, $params);
4081 //count total of visible courses (minus front page)
4082 $coursetotal = $DB->count_records('course', array('visible' => 1));
4083 $coursetotal = $coursetotal - 1 ;
4085 //average of course module
4086 if (empty($coursetotal)) {
4087 $coursemoduleaverage = 0;
4088 } else {
4089 $coursemoduleaverage = $moduletotal / $coursetotal;
4092 return $coursemoduleaverage;
4096 * This class pertains to course requests and contains methods associated with
4097 * create, approving, and removing course requests.
4099 * Please note we do not allow embedded images here because there is no context
4100 * to store them with proper access control.
4102 * @copyright 2009 Sam Hemelryk
4103 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4104 * @since Moodle 2.0
4106 * @property-read int $id
4107 * @property-read string $fullname
4108 * @property-read string $shortname
4109 * @property-read string $summary
4110 * @property-read int $summaryformat
4111 * @property-read int $summarytrust
4112 * @property-read string $reason
4113 * @property-read int $requester
4115 class course_request {
4118 * This is the stdClass that stores the properties for the course request
4119 * and is externally accessed through the __get magic method
4120 * @var stdClass
4122 protected $properties;
4125 * An array of options for the summary editor used by course request forms.
4126 * This is initially set by {@link summary_editor_options()}
4127 * @var array
4128 * @static
4130 protected static $summaryeditoroptions;
4133 * Static function to prepare the summary editor for working with a course
4134 * request.
4136 * @static
4137 * @param null|stdClass $data Optional, an object containing the default values
4138 * for the form, these may be modified when preparing the
4139 * editor so this should be called before creating the form
4140 * @return stdClass An object that can be used to set the default values for
4141 * an mforms form
4143 public static function prepare($data=null) {
4144 if ($data === null) {
4145 $data = new stdClass;
4147 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4148 return $data;
4152 * Static function to create a new course request when passed an array of properties
4153 * for it.
4155 * This function also handles saving any files that may have been used in the editor
4157 * @static
4158 * @param stdClass $data
4159 * @return course_request The newly created course request
4161 public static function create($data) {
4162 global $USER, $DB, $CFG;
4163 $data->requester = $USER->id;
4165 // Setting the default category if none set.
4166 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
4167 $data->category = $CFG->defaultrequestcategory;
4170 // Summary is a required field so copy the text over
4171 $data->summary = $data->summary_editor['text'];
4172 $data->summaryformat = $data->summary_editor['format'];
4174 $data->id = $DB->insert_record('course_request', $data);
4176 // Create a new course_request object and return it
4177 $request = new course_request($data);
4179 // Notify the admin if required.
4180 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4182 $a = new stdClass;
4183 $a->link = "$CFG->wwwroot/course/pending.php";
4184 $a->user = fullname($USER);
4185 $subject = get_string('courserequest');
4186 $message = get_string('courserequestnotifyemail', 'admin', $a);
4187 foreach ($users as $user) {
4188 $request->notify($user, $USER, 'courserequested', $subject, $message);
4192 return $request;
4196 * Returns an array of options to use with a summary editor
4198 * @uses course_request::$summaryeditoroptions
4199 * @return array An array of options to use with the editor
4201 public static function summary_editor_options() {
4202 global $CFG;
4203 if (self::$summaryeditoroptions === null) {
4204 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4206 return self::$summaryeditoroptions;
4210 * Loads the properties for this course request object. Id is required and if
4211 * only id is provided then we load the rest of the properties from the database
4213 * @param stdClass|int $properties Either an object containing properties
4214 * or the course_request id to load
4216 public function __construct($properties) {
4217 global $DB;
4218 if (empty($properties->id)) {
4219 if (empty($properties)) {
4220 throw new coding_exception('You must provide a course request id when creating a course_request object');
4222 $id = $properties;
4223 $properties = new stdClass;
4224 $properties->id = (int)$id;
4225 unset($id);
4227 if (empty($properties->requester)) {
4228 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4229 print_error('unknowncourserequest');
4231 } else {
4232 $this->properties = $properties;
4234 $this->properties->collision = null;
4238 * Returns the requested property
4240 * @param string $key
4241 * @return mixed
4243 public function __get($key) {
4244 return $this->properties->$key;
4248 * Override this to ensure empty($request->blah) calls return a reliable answer...
4250 * This is required because we define the __get method
4252 * @param mixed $key
4253 * @return bool True is it not empty, false otherwise
4255 public function __isset($key) {
4256 return (!empty($this->properties->$key));
4260 * Returns the user who requested this course
4262 * Uses a static var to cache the results and cut down the number of db queries
4264 * @staticvar array $requesters An array of cached users
4265 * @return stdClass The user who requested the course
4267 public function get_requester() {
4268 global $DB;
4269 static $requesters= array();
4270 if (!array_key_exists($this->properties->requester, $requesters)) {
4271 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4273 return $requesters[$this->properties->requester];
4277 * Checks that the shortname used by the course does not conflict with any other
4278 * courses that exist
4280 * @param string|null $shortnamemark The string to append to the requests shortname
4281 * should a conflict be found
4282 * @return bool true is there is a conflict, false otherwise
4284 public function check_shortname_collision($shortnamemark = '[*]') {
4285 global $DB;
4287 if ($this->properties->collision !== null) {
4288 return $this->properties->collision;
4291 if (empty($this->properties->shortname)) {
4292 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4293 $this->properties->collision = false;
4294 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4295 if (!empty($shortnamemark)) {
4296 $this->properties->shortname .= ' '.$shortnamemark;
4298 $this->properties->collision = true;
4299 } else {
4300 $this->properties->collision = false;
4302 return $this->properties->collision;
4306 * This function approves the request turning it into a course
4308 * This function converts the course request into a course, at the same time
4309 * transferring any files used in the summary to the new course and then removing
4310 * the course request and the files associated with it.
4312 * @return int The id of the course that was created from this request
4314 public function approve() {
4315 global $CFG, $DB, $USER;
4317 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4319 $courseconfig = get_config('moodlecourse');
4321 // Transfer appropriate settings
4322 $data = clone($this->properties);
4323 unset($data->id);
4324 unset($data->reason);
4325 unset($data->requester);
4327 // If the category is not set, if the current user does not have the rights to change the category, or if the
4328 // category does not exist, we set the default category to the course to be approved.
4329 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
4330 if (empty($data->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
4331 (!$category = get_course_category($data->category))) {
4332 $category = get_course_category($CFG->defaultrequestcategory);
4335 // Set category
4336 $data->category = $category->id;
4337 $data->sortorder = $category->sortorder; // place as the first in category
4339 // Set misc settings
4340 $data->requested = 1;
4342 // Apply course default settings
4343 $data->format = $courseconfig->format;
4344 $data->newsitems = $courseconfig->newsitems;
4345 $data->showgrades = $courseconfig->showgrades;
4346 $data->showreports = $courseconfig->showreports;
4347 $data->maxbytes = $courseconfig->maxbytes;
4348 $data->groupmode = $courseconfig->groupmode;
4349 $data->groupmodeforce = $courseconfig->groupmodeforce;
4350 $data->visible = $courseconfig->visible;
4351 $data->visibleold = $data->visible;
4352 $data->lang = $courseconfig->lang;
4354 $course = create_course($data);
4355 $context = context_course::instance($course->id, MUST_EXIST);
4357 // add enrol instances
4358 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4359 if ($manual = enrol_get_plugin('manual')) {
4360 $manual->add_default_instance($course);
4364 // enrol the requester as teacher if necessary
4365 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4366 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4369 $this->delete();
4371 $a = new stdClass();
4372 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
4373 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4374 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4376 return $course->id;
4380 * Reject a course request
4382 * This function rejects a course request, emailing the requesting user the
4383 * provided notice and then removing the request from the database
4385 * @param string $notice The message to display to the user
4387 public function reject($notice) {
4388 global $USER, $DB;
4389 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4390 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4391 $this->delete();
4395 * Deletes the course request and any associated files
4397 public function delete() {
4398 global $DB;
4399 $DB->delete_records('course_request', array('id' => $this->properties->id));
4403 * Send a message from one user to another using events_trigger
4405 * @param object $touser
4406 * @param object $fromuser
4407 * @param string $name
4408 * @param string $subject
4409 * @param string $message
4411 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4412 $eventdata = new stdClass();
4413 $eventdata->component = 'moodle';
4414 $eventdata->name = $name;
4415 $eventdata->userfrom = $fromuser;
4416 $eventdata->userto = $touser;
4417 $eventdata->subject = $subject;
4418 $eventdata->fullmessage = $message;
4419 $eventdata->fullmessageformat = FORMAT_PLAIN;
4420 $eventdata->fullmessagehtml = '';
4421 $eventdata->smallmessage = '';
4422 $eventdata->notification = 1;
4423 message_send($eventdata);
4428 * Return a list of page types
4429 * @param string $pagetype current page type
4430 * @param stdClass $parentcontext Block's parent context
4431 * @param stdClass $currentcontext Current context of block
4433 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4434 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
4435 if (isset($currentcontext)) {
4436 // if above course context ,display all course fomats
4437 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4438 if ($course->id == SITEID) {
4439 return array('*'=>get_string('page-x', 'pagetype'));
4442 return array('*'=>get_string('page-x', 'pagetype'),
4443 'course-*'=>get_string('page-course-x', 'pagetype'),
4444 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4449 * Determine whether course ajax should be enabled for the specified course
4451 * @param stdClass $course The course to test against
4452 * @return boolean Whether course ajax is enabled or note
4454 function course_ajax_enabled($course) {
4455 global $CFG, $PAGE, $SITE;
4457 // Ajax must be enabled globally
4458 if (!$CFG->enableajax) {
4459 return false;
4462 // The user must be editing for AJAX to be included
4463 if (!$PAGE->user_is_editing()) {
4464 return false;
4467 // Check that the theme suports
4468 if (!$PAGE->theme->enablecourseajax) {
4469 return false;
4472 // Check that the course format supports ajax functionality
4473 // The site 'format' doesn't have information on course format support
4474 if ($SITE->id !== $course->id) {
4475 $courseformatajaxsupport = course_format_ajax_support($course->format);
4476 if (!$courseformatajaxsupport->capable) {
4477 return false;
4481 // All conditions have been met so course ajax should be enabled
4482 return true;
4486 * Include the relevant javascript and language strings for the resource
4487 * toolbox YUI module
4489 * @param integer $id The ID of the course being applied to
4490 * @param array $usedmodules An array containing the names of the modules in use on the page
4491 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4492 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4493 * * resourceurl The URL to post changes to for resource changes
4494 * * sectionurl The URL to post changes to for section changes
4495 * * pageparams Additional parameters to pass through in the post
4496 * @return bool
4498 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4499 global $PAGE, $SITE;
4501 // Ensure that ajax should be included
4502 if (!course_ajax_enabled($course)) {
4503 return false;
4506 if (!$config) {
4507 $config = new stdClass();
4510 // The URL to use for resource changes
4511 if (!isset($config->resourceurl)) {
4512 $config->resourceurl = '/course/rest.php';
4515 // The URL to use for section changes
4516 if (!isset($config->sectionurl)) {
4517 $config->sectionurl = '/course/rest.php';
4520 // Any additional parameters which need to be included on page submission
4521 if (!isset($config->pageparams)) {
4522 $config->pageparams = array();
4525 // Include toolboxes
4526 $PAGE->requires->yui_module('moodle-course-toolboxes',
4527 'M.course.init_resource_toolbox',
4528 array(array(
4529 'courseid' => $course->id,
4530 'ajaxurl' => $config->resourceurl,
4531 'config' => $config,
4534 $PAGE->requires->yui_module('moodle-course-toolboxes',
4535 'M.course.init_section_toolbox',
4536 array(array(
4537 'courseid' => $course->id,
4538 'format' => $course->format,
4539 'ajaxurl' => $config->sectionurl,
4540 'config' => $config,
4544 // Include course dragdrop
4545 if ($course->id != $SITE->id) {
4546 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4547 array(array(
4548 'courseid' => $course->id,
4549 'ajaxurl' => $config->sectionurl,
4550 'config' => $config,
4551 )), null, true);
4553 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4554 array(array(
4555 'courseid' => $course->id,
4556 'ajaxurl' => $config->resourceurl,
4557 'config' => $config,
4558 )), null, true);
4561 // Include blocks dragdrop
4562 $params = array(
4563 'courseid' => $course->id,
4564 'pagetype' => $PAGE->pagetype,
4565 'pagelayout' => $PAGE->pagelayout,
4566 'subpage' => $PAGE->subpage,
4567 'regions' => $PAGE->blocks->get_regions(),
4569 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4571 // Require various strings for the command toolbox
4572 $PAGE->requires->strings_for_js(array(
4573 'moveleft',
4574 'deletechecktype',
4575 'deletechecktypename',
4576 'edittitle',
4577 'edittitleinstructions',
4578 'show',
4579 'hide',
4580 'groupsnone',
4581 'groupsvisible',
4582 'groupsseparate',
4583 'clicktochangeinbrackets',
4584 'markthistopic',
4585 'markedthistopic',
4586 'move',
4587 'movesection',
4588 ), 'moodle');
4590 // Include format-specific strings
4591 if ($course->id != $SITE->id) {
4592 $PAGE->requires->strings_for_js(array(
4593 'showfromothers',
4594 'hidefromothers',
4595 ), 'format_' . $course->format);
4598 // For confirming resource deletion we need the name of the module in question
4599 foreach ($usedmodules as $module => $modname) {
4600 $PAGE->requires->string_for_js('pluginname', $module);
4603 // Load drag and drop upload AJAX.
4604 dndupload_add_to_course($course, $enabledmodules);
4606 // Add the module chooser
4607 $PAGE->requires->yui_module('moodle-course-modchooser',
4608 'M.course.init_chooser',
4609 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
4611 $PAGE->requires->strings_for_js(array(
4612 'addresourceoractivity',
4613 'modchooserenable',
4614 'modchooserdisable',
4615 ), 'moodle');
4617 return true;
4621 * Returns the sorted list of available course formats, filtered by enabled if necessary
4623 * @param bool $enabledonly return only formats that are enabled
4624 * @return array array of sorted format names
4626 function get_sorted_course_formats($enabledonly = false) {
4627 global $CFG;
4628 $formats = get_plugin_list('format');
4630 if (!empty($CFG->format_plugins_sortorder)) {
4631 $order = explode(',', $CFG->format_plugins_sortorder);
4632 $order = array_merge(array_intersect($order, array_keys($formats)),
4633 array_diff(array_keys($formats), $order));
4634 } else {
4635 $order = array_keys($formats);
4637 if (!$enabledonly) {
4638 return $order;
4640 $sortedformats = array();
4641 foreach ($order as $formatname) {
4642 if (!get_config('format_'.$formatname, 'disabled')) {
4643 $sortedformats[] = $formatname;
4646 return $sortedformats;
4650 * The URL to use for the specified course (with section)
4652 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
4653 * @param int|stdClass $section Section object from database or just field course_sections.section
4654 * if omitted the course view page is returned
4655 * @param array $options options for view URL. At the moment core uses:
4656 * 'navigation' (bool) if true and section has no separate page, the function returns null
4657 * 'sr' (int) used by multipage formats to specify to which section to return
4658 * @return moodle_url The url of course
4660 function course_get_url($courseorid, $section = null, $options = array()) {
4661 return course_get_format($courseorid)->get_view_url($section, $options);