MDL-37186 add the ultimate TinyMCE custom parameter setting
[moodle.git] / course / lib.php
blobf2d90db832c542747ba42eb5306c43157100bdda
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core
24 * @subpackage course
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
37 /**
38 * Number of courses to display when summaries are included.
39 * @var int
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1');
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3');
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'calendar':
71 case 'mnet course':
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
74 } else {
75 $url = "/course/$url";
77 break;
78 case 'user':
79 case 'blog':
80 $url = "/$module/$url";
81 break;
82 case 'upload':
83 $url = $url;
84 break;
85 case 'coursetags':
86 $url = '/'.$url;
87 break;
88 case 'library':
89 case '':
90 $url = '/';
91 break;
92 case 'message':
93 $url = "/message/$url";
94 break;
95 case 'notes':
96 $url = "/notes/$url";
97 break;
98 case 'tag':
99 $url = "/tag/$url";
100 break;
101 case 'role':
102 $url = '/'.$url;
103 break;
104 default:
105 $url = "/mod/$module/$url";
106 break;
109 //now let's sanitise urls - there might be some ugly nasties:-(
110 $parts = explode('?', $url);
111 $script = array_shift($parts);
112 if (strpos($script, 'http') === 0) {
113 $script = clean_param($script, PARAM_URL);
114 } else {
115 $script = clean_param($script, PARAM_PATH);
118 $query = '';
119 if ($parts) {
120 $query = implode('', $parts);
121 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
122 $parts = explode('&', $query);
123 $eq = urlencode('=');
124 foreach ($parts as $key=>$part) {
125 $part = urlencode(urldecode($part));
126 $part = str_replace($eq, '=', $part);
127 $parts[$key] = $part;
129 $query = '?'.implode('&amp;', $parts);
132 return $script.$query;
136 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
137 $modname="", $modid=0, $modaction="", $groupid=0) {
138 global $CFG, $DB;
140 // It is assumed that $date is the GMT time of midnight for that day,
141 // and so the next 86400 seconds worth of logs are printed.
143 /// Setup for group handling.
145 // TODO: I don't understand group/context/etc. enough to be able to do
146 // something interesting with it here
147 // What is the context of a remote course?
149 /// If the group mode is separate, and this user does not have editing privileges,
150 /// then only the user's group can be viewed.
151 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
152 // $groupid = get_current_group($course->id);
154 /// If this course doesn't have groups, no groupid can be specified.
155 //else if (!$course->groupmode) {
156 // $groupid = 0;
159 $groupid = 0;
161 $joins = array();
162 $where = '';
164 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
165 FROM {mnet_log} l
166 LEFT JOIN {user} u ON l.userid = u.id
167 WHERE ";
168 $params = array();
170 $where .= "l.hostid = :hostid";
171 $params['hostid'] = $hostid;
173 // TODO: Is 1 really a magic number referring to the sitename?
174 if ($course != SITEID || $modid != 0) {
175 $where .= " AND l.course=:courseid";
176 $params['courseid'] = $course;
179 if ($modname) {
180 $where .= " AND l.module = :modname";
181 $params['modname'] = $modname;
184 if ('site_errors' === $modid) {
185 $where .= " AND ( l.action='error' OR l.action='infected' )";
186 } else if ($modid) {
187 //TODO: This assumes that modids are the same across sites... probably
188 //not true
189 $where .= " AND l.cmid = :modid";
190 $params['modid'] = $modid;
193 if ($modaction) {
194 $firstletter = substr($modaction, 0, 1);
195 if ($firstletter == '-') {
196 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
197 $params['modaction'] = '%'.substr($modaction, 1).'%';
198 } else {
199 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
200 $params['modaction'] = '%'.$modaction.'%';
204 if ($user) {
205 $where .= " AND l.userid = :user";
206 $params['user'] = $user;
209 if ($date) {
210 $enddate = $date + 86400;
211 $where .= " AND l.time > :date AND l.time < :enddate";
212 $params['date'] = $date;
213 $params['enddate'] = $enddate;
216 $result = array();
217 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
218 if(!empty($result['totalcount'])) {
219 $where .= " ORDER BY $order";
220 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
221 } else {
222 $result['logs'] = array();
224 return $result;
227 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
228 $modname="", $modid=0, $modaction="", $groupid=0) {
229 global $DB, $SESSION, $USER;
230 // It is assumed that $date is the GMT time of midnight for that day,
231 // and so the next 86400 seconds worth of logs are printed.
233 /// Setup for group handling.
235 /// If the group mode is separate, and this user does not have editing privileges,
236 /// then only the user's group can be viewed.
237 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
238 if (isset($SESSION->currentgroup[$course->id])) {
239 $groupid = $SESSION->currentgroup[$course->id];
240 } else {
241 $groupid = groups_get_all_groups($course->id, $USER->id);
242 if (is_array($groupid)) {
243 $groupid = array_shift(array_keys($groupid));
244 $SESSION->currentgroup[$course->id] = $groupid;
245 } else {
246 $groupid = 0;
250 /// If this course doesn't have groups, no groupid can be specified.
251 else if (!$course->groupmode) {
252 $groupid = 0;
255 $joins = array();
256 $params = array();
258 if ($course->id != SITEID || $modid != 0) {
259 $joins[] = "l.course = :courseid";
260 $params['courseid'] = $course->id;
263 if ($modname) {
264 $joins[] = "l.module = :modname";
265 $params['modname'] = $modname;
268 if ('site_errors' === $modid) {
269 $joins[] = "( l.action='error' OR l.action='infected' )";
270 } else if ($modid) {
271 $joins[] = "l.cmid = :modid";
272 $params['modid'] = $modid;
275 if ($modaction) {
276 $firstletter = substr($modaction, 0, 1);
277 if ($firstletter == '-') {
278 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
279 $params['modaction'] = '%'.substr($modaction, 1).'%';
280 } else {
281 $joins[] = $DB->sql_like('l.action', ':modaction', false);
282 $params['modaction'] = '%'.$modaction.'%';
287 /// Getting all members of a group.
288 if ($groupid and !$user) {
289 if ($gusers = groups_get_members($groupid)) {
290 $gusers = array_keys($gusers);
291 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
292 } else {
293 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
296 else if ($user) {
297 $joins[] = "l.userid = :userid";
298 $params['userid'] = $user;
301 if ($date) {
302 $enddate = $date + 86400;
303 $joins[] = "l.time > :date AND l.time < :enddate";
304 $params['date'] = $date;
305 $params['enddate'] = $enddate;
308 $selector = implode(' AND ', $joins);
310 $totalcount = 0; // Initialise
311 $result = array();
312 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
313 $result['totalcount'] = $totalcount;
314 return $result;
318 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
319 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
321 global $CFG, $DB, $OUTPUT;
323 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
324 $modname, $modid, $modaction, $groupid)) {
325 echo $OUTPUT->notification("No logs found!");
326 echo $OUTPUT->footer();
327 exit;
330 $courses = array();
332 if ($course->id == SITEID) {
333 $courses[0] = '';
334 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
335 foreach ($ccc as $cc) {
336 $courses[$cc->id] = $cc->shortname;
339 } else {
340 $courses[$course->id] = $course->shortname;
343 $totalcount = $logs['totalcount'];
344 $count=0;
345 $ldcache = array();
346 $tt = getdate(time());
347 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
349 $strftimedatetime = get_string("strftimedatetime");
351 echo "<div class=\"info\">\n";
352 print_string("displayingrecords", "", $totalcount);
353 echo "</div>\n";
355 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
357 $table = new html_table();
358 $table->classes = array('logtable','generalbox');
359 $table->align = array('right', 'left', 'left');
360 $table->head = array(
361 get_string('time'),
362 get_string('ip_address'),
363 get_string('fullnameuser'),
364 get_string('action'),
365 get_string('info')
367 $table->data = array();
369 if ($course->id == SITEID) {
370 array_unshift($table->align, 'left');
371 array_unshift($table->head, get_string('course'));
374 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
375 if (empty($logs['logs'])) {
376 $logs['logs'] = array();
379 foreach ($logs['logs'] as $log) {
381 if (isset($ldcache[$log->module][$log->action])) {
382 $ld = $ldcache[$log->module][$log->action];
383 } else {
384 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
385 $ldcache[$log->module][$log->action] = $ld;
387 if ($ld && is_numeric($log->info)) {
388 // ugly hack to make sure fullname is shown correctly
389 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
390 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
391 } else {
392 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
396 //Filter log->info
397 $log->info = format_string($log->info);
399 // If $log->url has been trimmed short by the db size restriction
400 // code in add_to_log, keep a note so we don't add a link to a broken url
401 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
403 $row = array();
404 if ($course->id == SITEID) {
405 if (empty($log->course)) {
406 $row[] = get_string('site');
407 } else {
408 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
412 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
414 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
415 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
417 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
419 $displayaction="$log->module $log->action";
420 if ($brokenurl) {
421 $row[] = $displayaction;
422 } else {
423 $link = make_log_url($log->module,$log->url);
424 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
426 $row[] = $log->info;
427 $table->data[] = $row;
430 echo html_writer::table($table);
431 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
435 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
436 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
438 global $CFG, $DB, $OUTPUT;
440 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
441 $modname, $modid, $modaction, $groupid)) {
442 echo $OUTPUT->notification("No logs found!");
443 echo $OUTPUT->footer();
444 exit;
447 if ($course->id == SITEID) {
448 $courses[0] = '';
449 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
450 foreach ($ccc as $cc) {
451 $courses[$cc->id] = $cc->shortname;
456 $totalcount = $logs['totalcount'];
457 $count=0;
458 $ldcache = array();
459 $tt = getdate(time());
460 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
462 $strftimedatetime = get_string("strftimedatetime");
464 echo "<div class=\"info\">\n";
465 print_string("displayingrecords", "", $totalcount);
466 echo "</div>\n";
468 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
470 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
471 echo "<tr>";
472 if ($course->id == SITEID) {
473 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
475 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
476 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
477 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
478 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
479 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
480 echo "</tr>\n";
482 if (empty($logs['logs'])) {
483 echo "</table>\n";
484 return;
487 $row = 1;
488 foreach ($logs['logs'] as $log) {
490 $log->info = $log->coursename;
491 $row = ($row + 1) % 2;
493 if (isset($ldcache[$log->module][$log->action])) {
494 $ld = $ldcache[$log->module][$log->action];
495 } else {
496 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
497 $ldcache[$log->module][$log->action] = $ld;
499 if (0 && $ld && !empty($log->info)) {
500 // ugly hack to make sure fullname is shown correctly
501 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
502 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
503 } else {
504 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
508 //Filter log->info
509 $log->info = format_string($log->info);
511 echo '<tr class="r'.$row.'">';
512 if ($course->id == SITEID) {
513 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
514 echo "<td class=\"r$row c0\" >\n";
515 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
516 echo "</td>\n";
518 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
519 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
520 echo "<td class=\"r$row c2\" >\n";
521 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
522 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
523 echo "</td>\n";
524 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
525 echo "<td class=\"r$row c3\" >\n";
526 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
527 echo "</td>\n";
528 echo "<td class=\"r$row c4\">\n";
529 echo $log->action .': '.$log->module;
530 echo "</td>\n";;
531 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
532 echo "</tr>\n";
534 echo "</table>\n";
536 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
540 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
541 $modid, $modaction, $groupid) {
542 global $DB, $CFG;
544 require_once($CFG->libdir . '/csvlib.class.php');
546 $csvexporter = new csv_export_writer('tab');
548 $header = array();
549 $header[] = get_string('course');
550 $header[] = get_string('time');
551 $header[] = get_string('ip_address');
552 $header[] = get_string('fullnameuser');
553 $header[] = get_string('action');
554 $header[] = get_string('info');
556 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
557 $modname, $modid, $modaction, $groupid)) {
558 return false;
561 $courses = array();
563 if ($course->id == SITEID) {
564 $courses[0] = '';
565 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
566 foreach ($ccc as $cc) {
567 $courses[$cc->id] = $cc->shortname;
570 } else {
571 $courses[$course->id] = $course->shortname;
574 $count=0;
575 $ldcache = array();
576 $tt = getdate(time());
577 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
579 $strftimedatetime = get_string("strftimedatetime");
581 $csvexporter->set_filename('logs', '.txt');
582 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
583 $csvexporter->add_data($title);
584 $csvexporter->add_data($header);
586 if (empty($logs['logs'])) {
587 return true;
590 foreach ($logs['logs'] as $log) {
591 if (isset($ldcache[$log->module][$log->action])) {
592 $ld = $ldcache[$log->module][$log->action];
593 } else {
594 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
595 $ldcache[$log->module][$log->action] = $ld;
597 if ($ld && is_numeric($log->info)) {
598 // ugly hack to make sure fullname is shown correctly
599 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
600 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
601 } else {
602 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
606 //Filter log->info
607 $log->info = format_string($log->info);
608 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
610 $coursecontext = context_course::instance($course->id);
611 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
612 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
613 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
614 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
615 $csvexporter->add_data($row);
617 $csvexporter->download_file();
618 return true;
622 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
623 $modid, $modaction, $groupid) {
625 global $CFG, $DB;
627 require_once("$CFG->libdir/excellib.class.php");
629 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
630 $modname, $modid, $modaction, $groupid)) {
631 return false;
634 $courses = array();
636 if ($course->id == SITEID) {
637 $courses[0] = '';
638 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
639 foreach ($ccc as $cc) {
640 $courses[$cc->id] = $cc->shortname;
643 } else {
644 $courses[$course->id] = $course->shortname;
647 $count=0;
648 $ldcache = array();
649 $tt = getdate(time());
650 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
652 $strftimedatetime = get_string("strftimedatetime");
654 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
655 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
656 $filename .= '.xls';
658 $workbook = new MoodleExcelWorkbook('-');
659 $workbook->send($filename);
661 $worksheet = array();
662 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
663 get_string('fullnameuser'), get_string('action'), get_string('info'));
665 // Creating worksheets
666 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
667 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
668 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
669 $worksheet[$wsnumber]->set_column(1, 1, 30);
670 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
671 userdate(time(), $strftimedatetime));
672 $col = 0;
673 foreach ($headers as $item) {
674 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
675 $col++;
679 if (empty($logs['logs'])) {
680 $workbook->close();
681 return true;
684 $formatDate =& $workbook->add_format();
685 $formatDate->set_num_format(get_string('log_excel_date_format'));
687 $row = FIRSTUSEDEXCELROW;
688 $wsnumber = 1;
689 $myxls =& $worksheet[$wsnumber];
690 foreach ($logs['logs'] as $log) {
691 if (isset($ldcache[$log->module][$log->action])) {
692 $ld = $ldcache[$log->module][$log->action];
693 } else {
694 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
695 $ldcache[$log->module][$log->action] = $ld;
697 if ($ld && is_numeric($log->info)) {
698 // ugly hack to make sure fullname is shown correctly
699 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
700 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
701 } else {
702 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
706 // Filter log->info
707 $log->info = format_string($log->info);
708 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
710 if ($nroPages>1) {
711 if ($row > EXCELROWS) {
712 $wsnumber++;
713 $myxls =& $worksheet[$wsnumber];
714 $row = FIRSTUSEDEXCELROW;
718 $coursecontext = context_course::instance($course->id);
720 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
721 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
722 $myxls->write($row, 2, $log->ip, '');
723 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
724 $myxls->write($row, 3, $fullname, '');
725 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
726 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
727 $myxls->write($row, 5, $log->info, '');
729 $row++;
732 $workbook->close();
733 return true;
736 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
737 $modid, $modaction, $groupid) {
739 global $CFG, $DB;
741 require_once("$CFG->libdir/odslib.class.php");
743 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
744 $modname, $modid, $modaction, $groupid)) {
745 return false;
748 $courses = array();
750 if ($course->id == SITEID) {
751 $courses[0] = '';
752 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
753 foreach ($ccc as $cc) {
754 $courses[$cc->id] = $cc->shortname;
757 } else {
758 $courses[$course->id] = $course->shortname;
761 $count=0;
762 $ldcache = array();
763 $tt = getdate(time());
764 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
766 $strftimedatetime = get_string("strftimedatetime");
768 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
769 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
770 $filename .= '.ods';
772 $workbook = new MoodleODSWorkbook('-');
773 $workbook->send($filename);
775 $worksheet = array();
776 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
777 get_string('fullnameuser'), get_string('action'), get_string('info'));
779 // Creating worksheets
780 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
781 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
782 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
783 $worksheet[$wsnumber]->set_column(1, 1, 30);
784 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
785 userdate(time(), $strftimedatetime));
786 $col = 0;
787 foreach ($headers as $item) {
788 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
789 $col++;
793 if (empty($logs['logs'])) {
794 $workbook->close();
795 return true;
798 $formatDate =& $workbook->add_format();
799 $formatDate->set_num_format(get_string('log_excel_date_format'));
801 $row = FIRSTUSEDEXCELROW;
802 $wsnumber = 1;
803 $myxls =& $worksheet[$wsnumber];
804 foreach ($logs['logs'] as $log) {
805 if (isset($ldcache[$log->module][$log->action])) {
806 $ld = $ldcache[$log->module][$log->action];
807 } else {
808 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
809 $ldcache[$log->module][$log->action] = $ld;
811 if ($ld && is_numeric($log->info)) {
812 // ugly hack to make sure fullname is shown correctly
813 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
814 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
815 } else {
816 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
820 // Filter log->info
821 $log->info = format_string($log->info);
822 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
824 if ($nroPages>1) {
825 if ($row > EXCELROWS) {
826 $wsnumber++;
827 $myxls =& $worksheet[$wsnumber];
828 $row = FIRSTUSEDEXCELROW;
832 $coursecontext = context_course::instance($course->id);
834 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
835 $myxls->write_date($row, 1, $log->time);
836 $myxls->write_string($row, 2, $log->ip);
837 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
838 $myxls->write_string($row, 3, $fullname);
839 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
840 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
841 $myxls->write_string($row, 5, $log->info);
843 $row++;
846 $workbook->close();
847 return true;
851 function print_overview($courses, array $remote_courses=array()) {
852 global $CFG, $USER, $DB, $OUTPUT;
854 $htmlarray = array();
855 if ($modules = $DB->get_records('modules')) {
856 foreach ($modules as $mod) {
857 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
858 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
859 $fname = $mod->name.'_print_overview';
860 if (function_exists($fname)) {
861 $fname($courses,$htmlarray);
866 foreach ($courses as $course) {
867 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
868 echo $OUTPUT->box_start('coursebox');
869 $attributes = array('title' => s($fullname));
870 if (empty($course->visible)) {
871 $attributes['class'] = 'dimmed';
873 echo $OUTPUT->heading(html_writer::link(
874 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
875 if (array_key_exists($course->id,$htmlarray)) {
876 foreach ($htmlarray[$course->id] as $modname => $html) {
877 echo $html;
880 echo $OUTPUT->box_end();
883 if (!empty($remote_courses)) {
884 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
886 foreach ($remote_courses as $course) {
887 echo $OUTPUT->box_start('coursebox');
888 $attributes = array('title' => s($course->fullname));
889 echo $OUTPUT->heading(html_writer::link(
890 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
891 format_string($course->shortname),
892 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
893 echo $OUTPUT->box_end();
899 * This function trawls through the logs looking for
900 * anything new since the user's last login
902 function print_recent_activity($course) {
903 // $course is an object
904 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
906 $context = context_course::instance($course->id);
908 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
910 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
912 if (!isguestuser()) {
913 if (!empty($USER->lastcourseaccess[$course->id])) {
914 if ($USER->lastcourseaccess[$course->id] > $timestart) {
915 $timestart = $USER->lastcourseaccess[$course->id];
920 echo '<div class="activitydate">';
921 echo get_string('activitysince', '', userdate($timestart));
922 echo '</div>';
923 echo '<div class="activityhead">';
925 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
927 echo "</div>\n";
929 $content = false;
931 /// Firstly, have there been any new enrolments?
933 $users = get_recent_enrolments($course->id, $timestart);
935 //Accessibility: new users now appear in an <OL> list.
936 if ($users) {
937 echo '<div class="newusers">';
938 echo $OUTPUT->heading(get_string("newusers").':', 3);
939 $content = true;
940 echo "<ol class=\"list\">\n";
941 foreach ($users as $user) {
942 $fullname = fullname($user, $viewfullnames);
943 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
945 echo "</ol>\n</div>\n";
948 /// Next, have there been any modifications to the course structure?
950 $modinfo = get_fast_modinfo($course);
952 $changelist = array();
954 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
955 module = 'course' AND
956 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
957 array($timestart, $course->id), "id ASC");
959 if ($logs) {
960 $actions = array('add mod', 'update mod', 'delete mod');
961 $newgones = array(); // added and later deleted items
962 foreach ($logs as $key => $log) {
963 if (!in_array($log->action, $actions)) {
964 continue;
966 $info = explode(' ', $log->info);
968 // note: in most cases I replaced hardcoding of label with use of
969 // $cm->has_view() but it was not possible to do this here because
970 // we don't necessarily have the $cm for it
971 if ($info[0] == 'label') { // Labels are ignored in recent activity
972 continue;
975 if (count($info) != 2) {
976 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
977 continue;
980 $modname = $info[0];
981 $instanceid = $info[1];
983 if ($log->action == 'delete mod') {
984 // unfortunately we do not know if the mod was visible
985 if (!array_key_exists($log->info, $newgones)) {
986 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
987 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
989 } else {
990 if (!isset($modinfo->instances[$modname][$instanceid])) {
991 if ($log->action == 'add mod') {
992 // do not display added and later deleted activities
993 $newgones[$log->info] = true;
995 continue;
997 $cm = $modinfo->instances[$modname][$instanceid];
998 if (!$cm->uservisible) {
999 continue;
1002 if ($log->action == 'add mod') {
1003 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1004 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1006 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1007 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1008 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
1014 if (!empty($changelist)) {
1015 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1016 $content = true;
1017 foreach ($changelist as $changeinfo => $change) {
1018 echo '<p class="activity">'.$change['text'].'</p>';
1022 /// Now display new things from each module
1024 $usedmodules = array();
1025 foreach($modinfo->cms as $cm) {
1026 if (isset($usedmodules[$cm->modname])) {
1027 continue;
1029 if (!$cm->uservisible) {
1030 continue;
1032 $usedmodules[$cm->modname] = $cm->modname;
1035 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1036 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1037 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1038 $print_recent_activity = $modname.'_print_recent_activity';
1039 if (function_exists($print_recent_activity)) {
1040 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1041 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1043 } else {
1044 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1048 if (! $content) {
1049 echo '<p class="message">'.get_string('nothingnew').'</p>';
1054 * For a given course, returns an array of course activity objects
1055 * Each item in the array contains he following properties:
1057 function get_array_of_activities($courseid) {
1058 // cm - course module id
1059 // mod - name of the module (eg forum)
1060 // section - the number of the section (eg week or topic)
1061 // name - the name of the instance
1062 // visible - is the instance visible or not
1063 // groupingid - grouping id
1064 // groupmembersonly - is this instance visible to group members only
1065 // extra - contains extra string to include in any link
1066 global $CFG, $DB;
1067 if(!empty($CFG->enableavailability)) {
1068 require_once($CFG->libdir.'/conditionlib.php');
1071 $course = $DB->get_record('course', array('id'=>$courseid));
1073 if (empty($course)) {
1074 throw new moodle_exception('courseidnotfound');
1077 $mod = array();
1079 $rawmods = get_course_mods($courseid);
1080 if (empty($rawmods)) {
1081 return $mod; // always return array
1084 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1085 foreach ($sections as $section) {
1086 if (!empty($section->sequence)) {
1087 $sequence = explode(",", $section->sequence);
1088 foreach ($sequence as $seq) {
1089 if (empty($rawmods[$seq])) {
1090 continue;
1092 $mod[$seq] = new stdClass();
1093 $mod[$seq]->id = $rawmods[$seq]->instance;
1094 $mod[$seq]->cm = $rawmods[$seq]->id;
1095 $mod[$seq]->mod = $rawmods[$seq]->modname;
1097 // Oh dear. Inconsistent names left here for backward compatibility.
1098 $mod[$seq]->section = $section->section;
1099 $mod[$seq]->sectionid = $rawmods[$seq]->section;
1101 $mod[$seq]->module = $rawmods[$seq]->module;
1102 $mod[$seq]->added = $rawmods[$seq]->added;
1103 $mod[$seq]->score = $rawmods[$seq]->score;
1104 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1105 $mod[$seq]->visible = $rawmods[$seq]->visible;
1106 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
1107 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1108 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1109 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1110 $mod[$seq]->indent = $rawmods[$seq]->indent;
1111 $mod[$seq]->completion = $rawmods[$seq]->completion;
1112 $mod[$seq]->extra = "";
1113 $mod[$seq]->completiongradeitemnumber =
1114 $rawmods[$seq]->completiongradeitemnumber;
1115 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
1116 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
1117 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1118 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1119 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1120 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
1121 if (!empty($CFG->enableavailability)) {
1122 condition_info::fill_availability_conditions($rawmods[$seq]);
1123 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1124 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1125 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
1128 $modname = $mod[$seq]->mod;
1129 $functionname = $modname."_get_coursemodule_info";
1131 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1132 continue;
1135 include_once("$CFG->dirroot/mod/$modname/lib.php");
1137 if ($hasfunction = function_exists($functionname)) {
1138 if ($info = $functionname($rawmods[$seq])) {
1139 if (!empty($info->icon)) {
1140 $mod[$seq]->icon = $info->icon;
1142 if (!empty($info->iconcomponent)) {
1143 $mod[$seq]->iconcomponent = $info->iconcomponent;
1145 if (!empty($info->name)) {
1146 $mod[$seq]->name = $info->name;
1148 if ($info instanceof cached_cm_info) {
1149 // When using cached_cm_info you can include three new fields
1150 // that aren't available for legacy code
1151 if (!empty($info->content)) {
1152 $mod[$seq]->content = $info->content;
1154 if (!empty($info->extraclasses)) {
1155 $mod[$seq]->extraclasses = $info->extraclasses;
1157 if (!empty($info->iconurl)) {
1158 $mod[$seq]->iconurl = $info->iconurl;
1160 if (!empty($info->onclick)) {
1161 $mod[$seq]->onclick = $info->onclick;
1163 if (!empty($info->customdata)) {
1164 $mod[$seq]->customdata = $info->customdata;
1166 } else {
1167 // When using a stdclass, the (horrible) deprecated ->extra field
1168 // is available for BC
1169 if (!empty($info->extra)) {
1170 $mod[$seq]->extra = $info->extra;
1175 // When there is no modname_get_coursemodule_info function,
1176 // but showdescriptions is enabled, then we use the 'intro'
1177 // and 'introformat' fields in the module table
1178 if (!$hasfunction && $rawmods[$seq]->showdescription) {
1179 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
1180 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
1181 // Set content from intro and introformat. Filters are disabled
1182 // because we filter it with format_text at display time
1183 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
1184 $modvalues, $rawmods[$seq]->id, false);
1186 // To save making another query just below, put name in here
1187 $mod[$seq]->name = $modvalues->name;
1190 if (!isset($mod[$seq]->name)) {
1191 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1194 // Minimise the database size by unsetting default options when they are
1195 // 'empty'. This list corresponds to code in the cm_info constructor.
1196 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
1197 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
1198 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1199 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1200 'completionview', 'completionexpected', 'score', 'showdescription')
1201 as $property) {
1202 if (property_exists($mod[$seq], $property) &&
1203 empty($mod[$seq]->{$property})) {
1204 unset($mod[$seq]->{$property});
1207 // Special case: this value is usually set to null, but may be 0
1208 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1209 is_null($mod[$seq]->completiongradeitemnumber)) {
1210 unset($mod[$seq]->completiongradeitemnumber);
1216 return $mod;
1220 * Returns the localised human-readable names of all used modules
1222 * @param bool $plural if true returns the plural forms of the names
1223 * @return array where key is the module name (component name without 'mod_') and
1224 * the value is the human-readable string. Array sorted alphabetically by value
1226 function get_module_types_names($plural = false) {
1227 static $modnames = null;
1228 global $DB, $CFG;
1229 if ($modnames === null) {
1230 $modnames = array(0 => array(), 1 => array());
1231 if ($allmods = $DB->get_records("modules")) {
1232 foreach ($allmods as $mod) {
1233 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1234 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1235 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1238 collatorlib::asort($modnames[0]);
1239 collatorlib::asort($modnames[1]);
1242 return $modnames[(int)$plural];
1246 * Set highlighted section. Only one section can be highlighted at the time.
1248 * @param int $courseid course id
1249 * @param int $marker highlight section with this number, 0 means remove higlightin
1250 * @return void
1252 function course_set_marker($courseid, $marker) {
1253 global $DB;
1254 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1255 format_base::reset_course_cache($courseid);
1259 * For a given course section, marks it visible or hidden,
1260 * and does the same for every activity in that section
1262 * @param int $courseid course id
1263 * @param int $sectionnumber The section number to adjust
1264 * @param int $visibility The new visibility
1265 * @return array A list of resources which were hidden in the section
1267 function set_section_visible($courseid, $sectionnumber, $visibility) {
1268 global $DB;
1270 $resourcestotoggle = array();
1271 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1272 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1273 if (!empty($section->sequence)) {
1274 $modules = explode(",", $section->sequence);
1275 foreach ($modules as $moduleid) {
1276 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1277 if ($visibility) {
1278 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1279 set_coursemodule_visible($moduleid, $cm->visibleold);
1280 } else {
1281 // We hide the section, so we hide the module but we store the original state in visibleold.
1282 set_coursemodule_visible($moduleid, 0);
1283 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1288 rebuild_course_cache($courseid, true);
1290 // Determine which modules are visible for AJAX update
1291 if (!empty($modules)) {
1292 list($insql, $params) = $DB->get_in_or_equal($modules);
1293 $select = 'id ' . $insql . ' AND visible = ?';
1294 array_push($params, $visibility);
1295 if (!$visibility) {
1296 $select .= ' AND visibleold = 1';
1298 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1301 return $resourcestotoggle;
1305 * Obtains shared data that is used in print_section when displaying a
1306 * course-module entry.
1308 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1310 * This data is also used in other areas of the code.
1311 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1312 * @param object $course Moodle course object
1313 * @return array An array with the following values in this order:
1314 * $content (optional extra content for after link),
1315 * $instancename (text of link)
1317 function get_print_section_cm_text(cm_info $cm, $course) {
1318 global $OUTPUT;
1320 // Get content from modinfo if specified. Content displays either
1321 // in addition to the standard link (below), or replaces it if
1322 // the link is turned off by setting ->url to null.
1323 if (($content = $cm->get_content()) !== '') {
1324 // Improve filter performance by preloading filter setttings for all
1325 // activities on the course (this does nothing if called multiple
1326 // times)
1327 filter_preload_activities($cm->get_modinfo());
1329 // Get module context
1330 $modulecontext = context_module::instance($cm->id);
1331 $labelformatoptions = new stdClass();
1332 $labelformatoptions->noclean = true;
1333 $labelformatoptions->overflowdiv = true;
1334 $labelformatoptions->context = $modulecontext;
1335 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1336 } else {
1337 $content = '';
1340 // Get course context
1341 $coursecontext = context_course::instance($course->id);
1342 $stringoptions = new stdClass;
1343 $stringoptions->context = $coursecontext;
1344 $instancename = format_string($cm->name, true, $stringoptions);
1345 return array($content, $instancename);
1349 * Prints a section full of activity modules
1351 * @param stdClass $course The course
1352 * @param stdClass|section_info $section The section object containing properties id and section
1353 * @param array $mods (argument not used)
1354 * @param array $modnamesused (argument not used)
1355 * @param bool $absolute All links are absolute
1356 * @param string $width Width of the container
1357 * @param bool $hidecompletion Hide completion status
1358 * @param int $sectionreturn The section to return to
1359 * @return void
1361 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1362 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1364 static $initialised;
1366 static $groupbuttons;
1367 static $groupbuttonslink;
1368 static $isediting;
1369 static $ismoving;
1370 static $strmovehere;
1371 static $strmovefull;
1372 static $strunreadpostsone;
1374 if (!isset($initialised)) {
1375 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1376 $groupbuttonslink = (!$course->groupmodeforce);
1377 $isediting = $PAGE->user_is_editing();
1378 $ismoving = $isediting && ismoving($course->id);
1379 if ($ismoving) {
1380 $strmovehere = get_string("movehere");
1381 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1383 $initialised = true;
1386 $modinfo = get_fast_modinfo($course);
1387 $completioninfo = new completion_info($course);
1389 //Accessibility: replace table with list <ul>, but don't output empty list.
1390 if (!empty($modinfo->sections[$section->section])) {
1392 // Fix bug #5027, don't want style=\"width:$width\".
1393 echo "<ul class=\"section img-text\">\n";
1395 foreach ($modinfo->sections[$section->section] as $modnumber) {
1396 $mod = $modinfo->cms[$modnumber];
1398 if ($ismoving and $mod->id == $USER->activitycopy) {
1399 // do not display moving mod
1400 continue;
1403 // We can continue (because it will not be displayed at all)
1404 // if:
1405 // 1) The activity is not visible to users
1406 // and
1407 // 2a) The 'showavailability' option is not set (if that is set,
1408 // we need to display the activity so we can show
1409 // availability info)
1410 // or
1411 // 2b) The 'availableinfo' is empty, i.e. the activity was
1412 // hidden in a way that leaves no info, such as using the
1413 // eye icon.
1414 if (!$mod->uservisible &&
1415 (empty($mod->showavailability) ||
1416 empty($mod->availableinfo))) {
1417 // visibility shortcut
1418 continue;
1421 // In some cases the activity is visible to user, but it is
1422 // dimmed. This is done if viewhiddenactivities is true and if:
1423 // 1. the activity is not visible, or
1424 // 2. the activity has dates set which do not include current, or
1425 // 3. the activity has any other conditions set (regardless of whether
1426 // current user meets them)
1427 $modcontext = context_module::instance($mod->id);
1428 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1429 $accessiblebutdim = false;
1430 $conditionalhidden = false;
1431 if ($canviewhidden) {
1432 $accessiblebutdim = !$mod->visible;
1433 if (!empty($CFG->enableavailability)) {
1434 $conditionalhidden = $mod->availablefrom > time() ||
1435 ($mod->availableuntil && $mod->availableuntil < time()) ||
1436 count($mod->conditionsgrade) > 0 ||
1437 count($mod->conditionscompletion) > 0;
1439 $accessiblebutdim = $conditionalhidden || $accessiblebutdim;
1442 $liclasses = array();
1443 $liclasses[] = 'activity';
1444 $liclasses[] = $mod->modname;
1445 $liclasses[] = 'modtype_'.$mod->modname;
1446 $extraclasses = $mod->get_extra_classes();
1447 if ($extraclasses) {
1448 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1450 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1451 if ($ismoving) {
1452 echo '<a title="'.$strmovefull.'"'.
1453 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1454 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1455 ' alt="'.$strmovehere.'" /></a><br />
1459 $classes = array('mod-indent');
1460 if (!empty($mod->indent)) {
1461 $classes[] = 'mod-indent-'.$mod->indent;
1462 if ($mod->indent > 15) {
1463 $classes[] = 'mod-indent-huge';
1466 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1468 // Get data about this course-module
1469 list($content, $instancename) =
1470 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1472 //Accessibility: for files get description via icon, this is very ugly hack!
1473 $altname = '';
1474 $altname = $mod->modfullname;
1475 // Avoid unnecessary duplication: if e.g. a forum name already
1476 // includes the word forum (or Forum, etc) then it is unhelpful
1477 // to include that in the accessible description that is added.
1478 if (false !== strpos(textlib::strtolower($instancename),
1479 textlib::strtolower($altname))) {
1480 $altname = '';
1482 // File type after name, for alphabetic lists (screen reader).
1483 if ($altname) {
1484 $altname = get_accesshide(' '.$altname);
1487 // Start the div for the activity title, excluding the edit icons.
1488 echo html_writer::start_tag('div', array('class' => 'activityinstance'));
1490 // We may be displaying this just in order to show information
1491 // about visibility, without the actual link
1492 $contentpart = '';
1493 if ($mod->uservisible) {
1494 // Nope - in this case the link is fully working for user
1495 $linkclasses = '';
1496 $textclasses = '';
1497 if ($accessiblebutdim) {
1498 $linkclasses .= ' dimmed';
1499 $textclasses .= ' dimmed_text';
1500 if ($conditionalhidden) {
1501 $linkclasses .= ' conditionalhidden';
1502 $textclasses .= ' conditionalhidden';
1504 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
1505 } else {
1506 $accesstext = '';
1508 if ($linkclasses) {
1509 $linkcss = trim($linkclasses) . ' ';
1510 } else {
1511 $linkcss = '';
1513 if ($textclasses) {
1514 $textcss = trim($textclasses) . ' ';
1515 } else {
1516 $textcss = '';
1519 // Get on-click attribute value if specified
1520 $onclick = $mod->get_on_click();
1522 $groupinglabel = '';
1523 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
1524 $groupings = groups_get_all_groupings($course->id);
1525 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
1526 array('class' => 'groupinglabel'));
1529 if ($url = $mod->get_url()) {
1530 // Display link itself.
1531 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
1532 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext .
1533 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
1534 echo html_writer::link($url, $activitylink, array('class' => $linkcss, 'onclick' => $onclick)) .
1535 $groupinglabel;
1537 // If specified, display extra content after link.
1538 if ($content) {
1539 $contentpart = html_writer::tag('div', $content, array('class' =>
1540 trim('contentafterlink ' . $textclasses)));
1542 } else {
1543 // No link, so display only content.
1544 $contentpart = html_writer::tag('div', $accesstext . $content, array('class' => $textcss));
1547 } else {
1548 $textclasses = $extraclasses;
1549 $textclasses .= ' dimmed_text';
1550 if ($textclasses) {
1551 $textcss = 'class="' . trim($textclasses) . '" ';
1552 } else {
1553 $textcss = '';
1555 $accesstext = '<span class="accesshide">' .
1556 get_string('notavailableyet', 'condition') .
1557 ': </span>';
1559 if ($url = $mod->get_url()) {
1560 // Display greyed-out text of link
1561 echo '<div ' . $textcss . $mod->extra .
1562 ' >' . '<img src="' . $mod->get_icon_url() .
1563 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1564 '</span></div>';
1566 // Do not display content after link when it is greyed out like this.
1567 } else {
1568 // No link, so display only content (also greyed)
1569 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1570 $accesstext . $content . '</div>';
1574 // Module can put text after the link (e.g. forum unread)
1575 echo $mod->get_after_link();
1577 // Closing the tag which contains everything but edit icons. $contentpart should not be part of this.
1578 echo html_writer::end_tag('div');
1580 // If there is content but NO link (eg label), then display the
1581 // content here (BEFORE any icons). In this case cons must be
1582 // displayed after the content so that it makes more sense visually
1583 // and for accessibility reasons, e.g. if you have a one-line label
1584 // it should work similarly (at least in terms of ordering) to an
1585 // activity.
1586 if (empty($url)) {
1587 echo $contentpart;
1590 if ($isediting) {
1591 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1592 if (! $mod->groupmodelink = $groupbuttonslink) {
1593 $mod->groupmode = $course->groupmode;
1596 } else {
1597 $mod->groupmode = false;
1599 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $sectionreturn);
1600 echo $mod->get_after_edit_icons();
1603 // Completion
1604 $completion = $hidecompletion
1605 ? COMPLETION_TRACKING_NONE
1606 : $completioninfo->is_enabled($mod);
1607 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1608 !isguestuser() && $mod->uservisible) {
1609 $completiondata = $completioninfo->get_data($mod,true);
1610 $completionicon = '';
1611 if ($isediting) {
1612 switch ($completion) {
1613 case COMPLETION_TRACKING_MANUAL :
1614 $completionicon = 'manual-enabled'; break;
1615 case COMPLETION_TRACKING_AUTOMATIC :
1616 $completionicon = 'auto-enabled'; break;
1617 default: // wtf
1619 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1620 switch($completiondata->completionstate) {
1621 case COMPLETION_INCOMPLETE:
1622 $completionicon = 'manual-n'; break;
1623 case COMPLETION_COMPLETE:
1624 $completionicon = 'manual-y'; break;
1626 } else { // Automatic
1627 switch($completiondata->completionstate) {
1628 case COMPLETION_INCOMPLETE:
1629 $completionicon = 'auto-n'; break;
1630 case COMPLETION_COMPLETE:
1631 $completionicon = 'auto-y'; break;
1632 case COMPLETION_COMPLETE_PASS:
1633 $completionicon = 'auto-pass'; break;
1634 case COMPLETION_COMPLETE_FAIL:
1635 $completionicon = 'auto-fail'; break;
1638 if ($completionicon) {
1639 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1640 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1641 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1642 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1643 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1644 $newstate =
1645 $completiondata->completionstate==COMPLETION_COMPLETE
1646 ? COMPLETION_INCOMPLETE
1647 : COMPLETION_COMPLETE;
1648 // In manual mode the icon is a toggle form...
1650 // If this completion state is used by the
1651 // conditional activities system, we need to turn
1652 // off the JS.
1653 if (!empty($CFG->enableavailability) &&
1654 condition_info::completion_value_used_as_condition($course, $mod)) {
1655 $extraclass = ' preventjs';
1656 } else {
1657 $extraclass = '';
1659 echo html_writer::start_tag('form', array(
1660 'class' => 'togglecompletion' . $extraclass,
1661 'method' => 'post',
1662 'action' => $CFG->wwwroot . '/course/togglecompletion.php'));
1663 echo html_writer::start_tag('div');
1664 echo html_writer::empty_tag('input', array(
1665 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
1666 echo html_writer::empty_tag('input', array(
1667 'type' => 'hidden', 'name' => 'modulename',
1668 'value' => $mod->name));
1669 echo html_writer::empty_tag('input', array(
1670 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
1671 echo html_writer::empty_tag('input', array(
1672 'type' => 'hidden', 'name' => 'completionstate',
1673 'value' => $newstate));
1674 echo html_writer::empty_tag('input', array(
1675 'type' => 'image', 'src' => $imgsrc, 'alt' => $imgalt, 'title' => $imgtitle));
1676 echo html_writer::end_tag('div');
1677 echo html_writer::end_tag('form');
1678 } else {
1679 // In auto mode, or when editing, the icon is just an image
1680 echo "<span class='autocompletion'>";
1681 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1686 // If there is content AND a link, then display the content here
1687 // (AFTER any icons). Otherwise it was displayed before
1688 if (!empty($url)) {
1689 echo $contentpart;
1692 // Show availability information (for someone who isn't allowed to
1693 // see the activity itself, or for staff)
1694 if (!$mod->uservisible) {
1695 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1696 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1697 // Don't add availability information if user is not editing and activity is hidden.
1698 if ($mod->visible || $PAGE->user_is_editing()) {
1699 $hidinfoclass = '';
1700 if (!$mod->visible) {
1701 $hidinfoclass = 'hide';
1703 $ci = new condition_info($mod);
1704 $fullinfo = $ci->get_full_information();
1705 if($fullinfo) {
1706 echo '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
1707 ? 'userrestriction_visible'
1708 : 'userrestriction_hidden','condition',
1709 $fullinfo).'</div>';
1714 echo html_writer::end_tag('div');
1715 echo html_writer::end_tag('li')."\n";
1718 } elseif ($ismoving) {
1719 echo "<ul class=\"section\">\n";
1722 if ($ismoving) {
1723 echo '<li><a title="'.$strmovefull.'"'.
1724 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1725 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1726 ' alt="'.$strmovehere.'" /></a></li>
1729 if (!empty($modinfo->sections[$section->section]) || $ismoving) {
1730 echo "</ul><!--class='section'-->\n\n";
1735 * Prints the menus to add activities and resources.
1737 * @param stdClass $course The course
1738 * @param int $section relative section number (field course_sections.section)
1739 * @param null|array $modnames An array containing the list of modules and their names
1740 * if omitted will be taken from get_module_types_names()
1741 * @param bool $vertical Vertical orientation
1742 * @param bool $return Return the menus or send them to output
1743 * @param int $sectionreturn The section to link back to
1744 * @return void|string depending on $return
1746 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1747 global $CFG, $OUTPUT;
1749 if ($modnames === null) {
1750 $modnames = get_module_types_names();
1753 // check to see if user can add menus and there are modules to add
1754 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
1755 || empty($modnames)) {
1756 if ($return) {
1757 return '';
1758 } else {
1759 return false;
1763 // Retrieve all modules with associated metadata
1764 $modules = get_module_metadata($course, $modnames, $sectionreturn);
1766 // We'll sort resources and activities into two lists
1767 $resources = array();
1768 $activities = array();
1770 // We need to add the section section to the link for each module
1771 $sectionlink = '&section=' . $section . '&sr=' . $sectionreturn;
1773 foreach ($modules as $module) {
1774 if (isset($module->types)) {
1775 // This module has a subtype
1776 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1777 $subtypes = array();
1778 foreach ($module->types as $subtype) {
1779 $subtypes[$subtype->link . $sectionlink] = $subtype->title;
1782 // Sort module subtypes into the list
1783 if (!empty($module->title)) {
1784 // This grouping has a name
1785 if ($module->archetype == MOD_CLASS_RESOURCE) {
1786 $resources[] = array($module->title=>$subtypes);
1787 } else {
1788 $activities[] = array($module->title=>$subtypes);
1790 } else {
1791 // This grouping does not have a name
1792 if ($module->archetype == MOD_CLASS_RESOURCE) {
1793 $resources = array_merge($resources, $subtypes);
1794 } else {
1795 $activities = array_merge($activities, $subtypes);
1798 } else {
1799 // This module has no subtypes
1800 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
1801 $resources[$module->link . $sectionlink] = $module->title;
1802 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
1803 // System modules cannot be added by user, do not add to dropdown
1804 } else {
1805 $activities[$module->link . $sectionlink] = $module->title;
1810 $straddactivity = get_string('addactivity');
1811 $straddresource = get_string('addresource');
1812 $sectionname = get_section_name($course, $section);
1813 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
1814 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
1816 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
1818 if (!$vertical) {
1819 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
1822 if (!empty($resources)) {
1823 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1824 $select->set_help_icon('resources');
1825 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
1826 $output .= $OUTPUT->render($select);
1829 if (!empty($activities)) {
1830 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1831 $select->set_help_icon('activities');
1832 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
1833 $output .= $OUTPUT->render($select);
1836 if (!$vertical) {
1837 $output .= html_writer::end_tag('div');
1840 $output .= html_writer::end_tag('div');
1842 if (course_ajax_enabled($course)) {
1843 $straddeither = get_string('addresourceoractivity');
1844 // The module chooser link
1845 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
1846 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
1847 $icon = $OUTPUT->pix_icon('t/add', '');
1848 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
1849 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
1850 $modchooser.= html_writer::end_tag('div');
1851 $modchooser.= html_writer::end_tag('div');
1853 // Wrap the normal output in a noscript div
1854 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
1855 if ($usemodchooser) {
1856 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
1857 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
1858 } else {
1859 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
1860 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
1861 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
1863 $output = $modchooser . $output;
1866 if ($return) {
1867 return $output;
1868 } else {
1869 echo $output;
1874 * Retrieve all metadata for the requested modules
1876 * @param object $course The Course
1877 * @param array $modnames An array containing the list of modules and their
1878 * names
1879 * @param int $sectionreturn The section to return to
1880 * @return array A list of stdClass objects containing metadata about each
1881 * module
1883 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1884 global $CFG, $OUTPUT;
1886 // get_module_metadata will be called once per section on the page and courses may show
1887 // different modules to one another
1888 static $modlist = array();
1889 if (!isset($modlist[$course->id])) {
1890 $modlist[$course->id] = array();
1893 $return = array();
1894 $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&sr='.$sectionreturn.'&add=';
1895 foreach($modnames as $modname => $modnamestr) {
1896 if (!course_allowed_module($course, $modname)) {
1897 continue;
1899 if (isset($modlist[$course->id][$modname])) {
1900 // This module is already cached
1901 $return[$modname] = $modlist[$course->id][$modname];
1902 continue;
1905 // Include the module lib
1906 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1907 if (!file_exists($libfile)) {
1908 continue;
1910 include_once($libfile);
1912 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1913 $gettypesfunc = $modname.'_get_types';
1914 if (function_exists($gettypesfunc)) {
1915 if ($types = $gettypesfunc()) {
1916 $group = new stdClass();
1917 $group->name = $modname;
1918 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1919 foreach($types as $type) {
1920 if ($type->typestr === '--') {
1921 continue;
1923 if (strpos($type->typestr, '--') === 0) {
1924 $group->title = str_replace('--', '', $type->typestr);
1925 continue;
1927 // Set the Sub Type metadata
1928 $subtype = new stdClass();
1929 $subtype->title = $type->typestr;
1930 $subtype->type = str_replace('&amp;', '&', $type->type);
1931 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1932 $subtype->archetype = $type->modclass;
1934 // The group archetype should match the subtype archetypes and all subtypes
1935 // should have the same archetype
1936 $group->archetype = $subtype->archetype;
1938 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1939 $subtype->help = get_string('help' . $subtype->name, $modname);
1941 $subtype->link = $urlbase . $subtype->type;
1942 $group->types[] = $subtype;
1944 $modlist[$course->id][$modname] = $group;
1946 } else {
1947 $module = new stdClass();
1948 $module->title = get_string('modulename', $modname);
1949 $module->name = $modname;
1950 $module->link = $urlbase . $modname;
1951 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1952 $sm = get_string_manager();
1953 if ($sm->string_exists('modulename_help', $modname)) {
1954 $module->help = get_string('modulename_help', $modname);
1955 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1956 $link = get_string('modulename_link', $modname);
1957 $linktext = get_string('morehelp');
1958 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1961 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1962 $modlist[$course->id][$modname] = $module;
1964 $return[$modname] = $modlist[$course->id][$modname];
1967 return $return;
1971 * Return the course category context for the category with id $categoryid, except
1972 * that if $categoryid is 0, return the system context.
1974 * @param integer $categoryid a category id or 0.
1975 * @return object the corresponding context
1977 function get_category_or_system_context($categoryid) {
1978 if ($categoryid) {
1979 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1980 } else {
1981 return context_system::instance();
1986 * Gets the child categories of a given courses category. Uses a static cache
1987 * to make repeat calls efficient.
1989 * @param int $parentid the id of a course category.
1990 * @return array all the child course categories.
1992 function get_child_categories($parentid) {
1993 static $allcategories = null;
1995 // only fill in this variable the first time
1996 if (null == $allcategories) {
1997 $allcategories = array();
1999 $categories = get_categories();
2000 foreach ($categories as $category) {
2001 if (empty($allcategories[$category->parent])) {
2002 $allcategories[$category->parent] = array();
2004 $allcategories[$category->parent][] = $category;
2008 if (empty($allcategories[$parentid])) {
2009 return array();
2010 } else {
2011 return $allcategories[$parentid];
2016 * This function recursively travels the categories, building up a nice list
2017 * for display. It also makes an array that list all the parents for each
2018 * category.
2020 * For example, if you have a tree of categories like:
2021 * Miscellaneous (id = 1)
2022 * Subcategory (id = 2)
2023 * Sub-subcategory (id = 4)
2024 * Other category (id = 3)
2025 * Then after calling this function you will have
2026 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2027 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2028 * 3 => 'Other category');
2029 * $parents = array(2 => array(1), 4 => array(1, 2));
2031 * If you specify $requiredcapability, then only categories where the current
2032 * user has that capability will be added to $list, although all categories
2033 * will still be added to $parents, and if you only have $requiredcapability
2034 * in a child category, not the parent, then the child catgegory will still be
2035 * included.
2037 * If you specify the option $excluded, then that category, and all its children,
2038 * are omitted from the tree. This is useful when you are doing something like
2039 * moving categories, where you do not want to allow people to move a category
2040 * to be the child of itself.
2042 * @param array $list For output, accumulates an array categoryid => full category path name
2043 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2044 * @param string/array $requiredcapability if given, only categories where the current
2045 * user has this capability will be added to $list. Can also be an array of capabilities,
2046 * in which case they are all required.
2047 * @param integer $excludeid Omit this category and its children from the lists built.
2048 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
2049 * @param string $path For internal use, as part of recursive calls.
2051 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2052 $excludeid = 0, $category = NULL, $path = "") {
2054 // initialize the arrays if needed
2055 if (!is_array($list)) {
2056 $list = array();
2058 if (!is_array($parents)) {
2059 $parents = array();
2062 if (empty($category)) {
2063 // Start at the top level.
2064 $category = new stdClass;
2065 $category->id = 0;
2066 } else {
2067 // This is the excluded category, don't include it.
2068 if ($excludeid > 0 && $excludeid == $category->id) {
2069 return;
2072 $context = context_coursecat::instance($category->id);
2073 $categoryname = format_string($category->name, true, array('context' => $context));
2075 // Update $path.
2076 if ($path) {
2077 $path = $path.' / '.$categoryname;
2078 } else {
2079 $path = $categoryname;
2082 // Add this category to $list, if the permissions check out.
2083 if (empty($requiredcapability)) {
2084 $list[$category->id] = $path;
2086 } else {
2087 $requiredcapability = (array)$requiredcapability;
2088 if (has_all_capabilities($requiredcapability, $context)) {
2089 $list[$category->id] = $path;
2094 // Add all the children recursively, while updating the parents array.
2095 if ($categories = get_child_categories($category->id)) {
2096 foreach ($categories as $cat) {
2097 if (!empty($category->id)) {
2098 if (isset($parents[$category->id])) {
2099 $parents[$cat->id] = $parents[$category->id];
2101 $parents[$cat->id][] = $category->id;
2103 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2109 * This function generates a structured array of courses and categories.
2111 * The depth of categories is limited by $CFG->maxcategorydepth however there
2112 * is no limit on the number of courses!
2114 * Suitable for use with the course renderers course_category_tree method:
2115 * $renderer = $PAGE->get_renderer('core','course');
2116 * echo $renderer->course_category_tree(get_course_category_tree());
2118 * @global moodle_database $DB
2119 * @param int $id
2120 * @param int $depth
2122 function get_course_category_tree($id = 0, $depth = 0) {
2123 global $DB, $CFG;
2124 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system::instance());
2125 $categories = get_child_categories($id);
2126 $categoryids = array();
2127 foreach ($categories as $key => &$category) {
2128 if (!$category->visible && !$viewhiddencats) {
2129 unset($categories[$key]);
2130 continue;
2132 $categoryids[$category->id] = $category;
2133 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2134 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2135 foreach ($subcategories as $subid=>$subcat) {
2136 $categoryids[$subid] = $subcat;
2138 $category->courses = array();
2142 if ($depth > 0) {
2143 // This is a recursive call so return the required array
2144 return array($categories, $categoryids);
2147 if (empty($categoryids)) {
2148 // No categories available (probably all hidden).
2149 return array();
2152 // The depth is 0 this function has just been called so we can finish it off
2154 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2155 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2156 $sql = "SELECT
2157 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2158 $ccselect
2159 FROM {course} c
2160 $ccjoin
2161 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2162 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2163 // loop throught them
2164 foreach ($courses as $course) {
2165 if ($course->id == SITEID) {
2166 continue;
2168 context_instance_preload($course);
2169 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2170 $categoryids[$course->category]->courses[$course->id] = $course;
2174 return $categories;
2178 * Recursive function to print out all the categories in a nice format
2179 * with or without courses included
2181 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2182 global $CFG;
2184 // maxcategorydepth == 0 meant no limit
2185 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2186 return;
2189 if (!$displaylist) {
2190 make_categories_list($displaylist, $parentslist);
2193 if ($category) {
2194 if ($category->visible or has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
2195 print_category_info($category, $depth, $showcourses);
2196 } else {
2197 return; // Don't bother printing children of invisible categories
2200 } else {
2201 $category = new stdClass();
2202 $category->id = "0";
2205 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2206 $countcats = count($categories);
2207 $count = 0;
2208 $first = true;
2209 $last = false;
2210 foreach ($categories as $cat) {
2211 $count++;
2212 if ($count == $countcats) {
2213 $last = true;
2215 $up = $first ? false : true;
2216 $down = $last ? false : true;
2217 $first = false;
2219 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2225 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2227 function make_categories_options() {
2228 make_categories_list($cats,$parents);
2229 foreach ($cats as $key => $value) {
2230 if (array_key_exists($key,$parents)) {
2231 if ($indent = count($parents[$key])) {
2232 for ($i = 0; $i < $indent; $i++) {
2233 $cats[$key] = '&nbsp;'.$cats[$key];
2238 return $cats;
2242 * Prints the category info in indented fashion
2243 * This function is only used by print_whole_category_list() above
2245 function print_category_info($category, $depth=0, $showcourses = false) {
2246 global $CFG, $DB, $OUTPUT;
2248 $strsummary = get_string('summary');
2250 $catlinkcss = null;
2251 if (!$category->visible) {
2252 $catlinkcss = array('class'=>'dimmed');
2254 static $coursecount = null;
2255 if (null === $coursecount) {
2256 // only need to check this once
2257 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2260 if ($showcourses and $coursecount) {
2261 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2262 } else {
2263 $catimage = "&nbsp;";
2266 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2267 $context = context_coursecat::instance($category->id);
2268 $fullname = format_string($category->name, true, array('context' => $context));
2270 if ($showcourses and $coursecount) {
2271 echo '<div class="categorylist clearfix">';
2272 $cat = '';
2273 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2274 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2275 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2277 $html = '';
2278 if ($depth > 0) {
2279 for ($i=0; $i< $depth; $i++) {
2280 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2281 $cat = '';
2283 } else {
2284 $html = $cat;
2286 echo html_writer::tag('div', $html, array('class'=>'category'));
2287 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2289 // does the depth exceed maxcategorydepth
2290 // maxcategorydepth == 0 or unset meant no limit
2291 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2292 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2293 foreach ($courses as $course) {
2294 $linkcss = null;
2295 if (!$course->visible) {
2296 $linkcss = array('class'=>'dimmed');
2299 $coursename = get_course_display_name_for_list($course);
2300 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2302 // print enrol info
2303 $courseicon = '';
2304 if ($icons = enrol_get_course_info_icons($course)) {
2305 foreach ($icons as $pix_icon) {
2306 $courseicon = $OUTPUT->render($pix_icon);
2310 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2312 if ($course->summary) {
2313 $link = new moodle_url('/course/info.php?id='.$course->id);
2314 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2315 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2316 array('title'=>$strsummary));
2318 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2321 $html = '';
2322 for ($i=0; $i <= $depth; $i++) {
2323 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2324 $coursecontent = '';
2326 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2329 echo '</div>';
2330 } else {
2331 echo '<div class="categorylist">';
2332 $html = '';
2333 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2334 if (count($courses) > 0) {
2335 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2338 if ($depth > 0) {
2339 for ($i=0; $i< $depth; $i++) {
2340 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2341 $cat = '';
2343 } else {
2344 $html = $cat;
2347 echo html_writer::tag('div', $html, array('class'=>'category'));
2348 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2349 echo '</div>';
2354 * Print the buttons relating to course requests.
2356 * @param object $systemcontext the system context.
2358 function print_course_request_buttons($systemcontext) {
2359 global $CFG, $DB, $OUTPUT;
2360 if (empty($CFG->enablecourserequests)) {
2361 return;
2363 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2364 /// Print a button to request a new course
2365 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2367 /// Print a button to manage pending requests
2368 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2369 $disabled = !$DB->record_exists('course_request', array());
2370 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2375 * Does the user have permission to edit things in this category?
2377 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2378 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2380 function can_edit_in_category($categoryid = 0) {
2381 $context = get_category_or_system_context($categoryid);
2382 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2386 * Prints the turn editing on/off button on course/index.php or course/category.php.
2388 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2389 * @return string HTML of the editing button, or empty string, if this user is not allowed
2390 * to see it.
2392 function update_category_button($categoryid = 0) {
2393 global $CFG, $PAGE, $OUTPUT;
2395 // Check permissions.
2396 if (!can_edit_in_category($categoryid)) {
2397 return '';
2400 // Work out the appropriate action.
2401 if ($PAGE->user_is_editing()) {
2402 $label = get_string('turneditingoff');
2403 $edit = 'off';
2404 } else {
2405 $label = get_string('turneditingon');
2406 $edit = 'on';
2409 // Generate the button HTML.
2410 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2411 if ($categoryid) {
2412 $options['id'] = $categoryid;
2413 $page = 'category.php';
2414 } else {
2415 $page = 'index.php';
2417 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2421 * Category is 0 (for all courses) or an object
2423 function print_courses($category) {
2424 global $CFG, $OUTPUT;
2426 if (!is_object($category) && $category==0) {
2427 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2428 if (is_array($categories) && count($categories) == 1) {
2429 $category = array_shift($categories);
2430 $courses = get_courses_wmanagers($category->id,
2431 'c.sortorder ASC',
2432 array('summary','summaryformat'));
2433 } else {
2434 $courses = get_courses_wmanagers('all',
2435 'c.sortorder ASC',
2436 array('summary','summaryformat'));
2438 unset($categories);
2439 } else {
2440 $courses = get_courses_wmanagers($category->id,
2441 'c.sortorder ASC',
2442 array('summary','summaryformat'));
2445 if ($courses) {
2446 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2447 foreach ($courses as $course) {
2448 $coursecontext = context_course::instance($course->id);
2449 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2450 echo html_writer::start_tag('li');
2451 print_course($course);
2452 echo html_writer::end_tag('li');
2455 echo html_writer::end_tag('ul');
2456 } else {
2457 echo $OUTPUT->heading(get_string("nocoursesyet"));
2458 $context = context_system::instance();
2459 if (has_capability('moodle/course:create', $context)) {
2460 $options = array();
2461 if (!empty($category->id)) {
2462 $options['category'] = $category->id;
2463 } else {
2464 $options['category'] = $CFG->defaultrequestcategory;
2466 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2467 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2468 echo html_writer::end_tag('div');
2474 * Print a description of a course, suitable for browsing in a list.
2476 * @param object $course the course object.
2477 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2479 function print_course($course, $highlightterms = '') {
2480 global $CFG, $USER, $DB, $OUTPUT;
2482 $context = context_course::instance($course->id);
2484 // Rewrite file URLs so that they are correct
2485 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2487 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2488 echo html_writer::start_tag('div', array('class'=>'info'));
2489 echo html_writer::start_tag('h3', array('class'=>'name'));
2491 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2493 $coursename = get_course_display_name_for_list($course);
2494 $linktext = highlight($highlightterms, format_string($coursename));
2495 $linkparams = array('title'=>get_string('entercourse'));
2496 if (empty($course->visible)) {
2497 $linkparams['class'] = 'dimmed';
2499 echo html_writer::link($linkhref, $linktext, $linkparams);
2500 echo html_writer::end_tag('h3');
2502 /// first find all roles that are supposed to be displayed
2503 if (!empty($CFG->coursecontact)) {
2504 $managerroles = explode(',', $CFG->coursecontact);
2505 $rusers = array();
2507 if (!isset($course->managers)) {
2508 list($sort, $sortparams) = users_order_by_sql('u');
2509 $rusers = get_role_users($managerroles, $context, true,
2510 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
2511 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
2512 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
2513 } else {
2514 // use the managers array if we have it for perf reasosn
2515 // populate the datastructure like output of get_role_users();
2516 foreach ($course->managers as $manager) {
2517 $user = clone($manager->user);
2518 $user->roleid = $manager->roleid;
2519 $user->rolename = $manager->rolename;
2520 $user->roleshortname = $manager->roleshortname;
2521 $user->rolecoursealias = $manager->rolecoursealias;
2522 $rusers[$user->id] = $user;
2526 $namesarray = array();
2527 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2528 foreach ($rusers as $ra) {
2529 if (isset($namesarray[$ra->id])) {
2530 // only display a user once with the higest sortorder role
2531 continue;
2534 $role = new stdClass();
2535 $role->id = $ra->roleid;
2536 $role->name = $ra->rolename;
2537 $role->shortname = $ra->roleshortname;
2538 $role->coursealias = $ra->rolecoursealias;
2539 $rolename = role_get_name($role, $context, ROLENAME_ALIAS);
2541 $fullname = fullname($ra, $canviewfullnames);
2542 $namesarray[$ra->id] = $rolename.': '.
2543 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2546 if (!empty($namesarray)) {
2547 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2548 foreach ($namesarray as $name) {
2549 echo html_writer::tag('li', $name);
2551 echo html_writer::end_tag('ul');
2554 echo html_writer::end_tag('div'); // End of info div
2556 echo html_writer::start_tag('div', array('class'=>'summary'));
2557 $options = new stdClass();
2558 $options->noclean = true;
2559 $options->para = false;
2560 $options->overflowdiv = true;
2561 if (!isset($course->summaryformat)) {
2562 $course->summaryformat = FORMAT_MOODLE;
2564 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2565 if ($icons = enrol_get_course_info_icons($course)) {
2566 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2567 foreach ($icons as $icon) {
2568 echo $OUTPUT->render($icon);
2570 echo html_writer::end_tag('div'); // End of enrolmenticons div
2572 echo html_writer::end_tag('div'); // End of summary div
2573 echo html_writer::end_tag('div'); // End of coursebox div
2577 * Prints custom user information on the home page.
2578 * Over time this can include all sorts of information
2580 function print_my_moodle() {
2581 global $USER, $CFG, $DB, $OUTPUT;
2583 if (!isloggedin() or isguestuser()) {
2584 print_error('nopermissions', '', '', 'See My Moodle');
2587 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2588 $rhosts = array();
2589 $rcourses = array();
2590 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2591 $rcourses = get_my_remotecourses($USER->id);
2592 $rhosts = get_my_remotehosts();
2595 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2597 if (!empty($courses)) {
2598 echo '<ul class="unlist">';
2599 foreach ($courses as $course) {
2600 if ($course->id == SITEID) {
2601 continue;
2603 echo '<li>';
2604 print_course($course);
2605 echo "</li>\n";
2607 echo "</ul>\n";
2610 // MNET
2611 if (!empty($rcourses)) {
2612 // at the IDP, we know of all the remote courses
2613 foreach ($rcourses as $course) {
2614 print_remote_course($course, "100%");
2616 } elseif (!empty($rhosts)) {
2617 // non-IDP, we know of all the remote servers, but not courses
2618 foreach ($rhosts as $host) {
2619 print_remote_host($host, "100%");
2622 unset($course);
2623 unset($host);
2625 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2626 echo "<table width=\"100%\"><tr><td align=\"center\">";
2627 print_course_search("", false, "short");
2628 echo "</td><td align=\"center\">";
2629 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2630 echo "</td></tr></table>\n";
2633 } else {
2634 if ($DB->count_records("course_categories") > 1) {
2635 echo $OUTPUT->box_start("categorybox");
2636 print_whole_category_list();
2637 echo $OUTPUT->box_end();
2638 } else {
2639 print_courses(0);
2645 function print_course_search($value="", $return=false, $format="plain") {
2646 global $CFG;
2647 static $count = 0;
2649 $count++;
2651 $id = 'coursesearch';
2653 if ($count > 1) {
2654 $id .= $count;
2657 $strsearchcourses= get_string("searchcourses");
2659 if ($format == 'plain') {
2660 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2661 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2662 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2663 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2664 $output .= '<input type="submit" value="'.get_string('go').'" />';
2665 $output .= '</fieldset></form>';
2666 } else if ($format == 'short') {
2667 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2668 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2669 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2670 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2671 $output .= '<input type="submit" value="'.get_string('go').'" />';
2672 $output .= '</fieldset></form>';
2673 } else if ($format == 'navbar') {
2674 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2675 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2676 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2677 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2678 $output .= '<input type="submit" value="'.get_string('go').'" />';
2679 $output .= '</fieldset></form>';
2682 if ($return) {
2683 return $output;
2685 echo $output;
2688 function print_remote_course($course, $width="100%") {
2689 global $CFG, $USER;
2691 $linkcss = '';
2693 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2695 echo '<div class="coursebox remotecoursebox clearfix">';
2696 echo '<div class="info">';
2697 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2698 $linkcss.' href="'.$url.'">'
2699 . format_string($course->fullname) .'</a><br />'
2700 . format_string($course->hostname) . ' : '
2701 . format_string($course->cat_name) . ' : '
2702 . format_string($course->shortname). '</div>';
2703 echo '</div><div class="summary">';
2704 $options = new stdClass();
2705 $options->noclean = true;
2706 $options->para = false;
2707 $options->overflowdiv = true;
2708 echo format_text($course->summary, $course->summaryformat, $options);
2709 echo '</div>';
2710 echo '</div>';
2713 function print_remote_host($host, $width="100%") {
2714 global $OUTPUT;
2716 $linkcss = '';
2718 echo '<div class="coursebox clearfix">';
2719 echo '<div class="info">';
2720 echo '<div class="name">';
2721 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2722 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2723 . s($host['name']).'</a> - ';
2724 echo $host['count'] . ' ' . get_string('courses');
2725 echo '</div>';
2726 echo '</div>';
2727 echo '</div>';
2731 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2733 function add_course_module($mod) {
2734 global $DB;
2736 $mod->added = time();
2737 unset($mod->id);
2739 $cmid = $DB->insert_record("course_modules", $mod);
2740 rebuild_course_cache($mod->course, true);
2741 return $cmid;
2745 * Creates missing course section(s) and rebuilds course cache
2747 * @param int|stdClass $courseorid course id or course object
2748 * @param int|array $sections list of relative section numbers to create
2749 * @return bool if there were any sections created
2751 function course_create_sections_if_missing($courseorid, $sections) {
2752 global $DB;
2753 if (!is_array($sections)) {
2754 $sections = array($sections);
2756 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2757 if (is_object($courseorid)) {
2758 $courseorid = $courseorid->id;
2760 $coursechanged = false;
2761 foreach ($sections as $sectionnum) {
2762 if (!in_array($sectionnum, $existing)) {
2763 $cw = new stdClass();
2764 $cw->course = $courseorid;
2765 $cw->section = $sectionnum;
2766 $cw->summary = '';
2767 $cw->summaryformat = FORMAT_HTML;
2768 $cw->sequence = '';
2769 $id = $DB->insert_record("course_sections", $cw);
2770 $coursechanged = true;
2773 if ($coursechanged) {
2774 rebuild_course_cache($courseorid, true);
2776 return $coursechanged;
2780 * Adds an existing module to the section
2782 * Updates both tables {course_sections} and {course_modules}
2784 * @param int|stdClass $courseorid course id or course object
2785 * @param int $cmid id of the module already existing in course_modules table
2786 * @param int $sectionnum relative number of the section (field course_sections.section)
2787 * If section does not exist it will be created
2788 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2789 * before which the module needs to be included. Null for inserting in the
2790 * end of the section
2791 * @return int The course_sections ID where the module is inserted
2793 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2794 global $DB, $COURSE;
2795 if (is_object($beforemod)) {
2796 $beforemod = $beforemod->id;
2798 if (is_object($courseorid)) {
2799 $courseid = $courseorid->id;
2800 } else {
2801 $courseid = $courseorid;
2803 course_create_sections_if_missing($courseorid, $sectionnum);
2804 // Do not try to use modinfo here, there is no guarantee it is valid!
2805 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
2806 $modarray = explode(",", trim($section->sequence));
2807 if (empty($section->sequence)) {
2808 $newsequence = "$cmid";
2809 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2810 $insertarray = array($cmid, $beforemod);
2811 array_splice($modarray, $key[0], 1, $insertarray);
2812 $newsequence = implode(",", $modarray);
2813 } else {
2814 $newsequence = "$section->sequence,$cmid";
2816 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
2817 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
2818 if (is_object($courseorid)) {
2819 rebuild_course_cache($courseorid->id, true);
2820 } else {
2821 rebuild_course_cache($courseorid, true);
2823 return $section->id; // Return course_sections ID that was used.
2826 function set_coursemodule_groupmode($id, $groupmode) {
2827 global $DB;
2828 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
2829 if ($cm->groupmode != $groupmode) {
2830 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
2831 rebuild_course_cache($cm->course, true);
2833 return ($cm->groupmode != $groupmode);
2836 function set_coursemodule_idnumber($id, $idnumber) {
2837 global $DB;
2838 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
2839 if ($cm->idnumber != $idnumber) {
2840 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
2841 rebuild_course_cache($cm->course, true);
2843 return ($cm->idnumber != $idnumber);
2847 * Set the visibility of a module and inherent properties.
2849 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2850 * has been moved to {@link set_section_visible()} which was the only place from which
2851 * the parameter was used.
2853 * @param int $id of the module
2854 * @param int $visible state of the module
2855 * @return bool false when the module was not found, true otherwise
2857 function set_coursemodule_visible($id, $visible) {
2858 global $DB, $CFG;
2859 require_once($CFG->libdir.'/gradelib.php');
2861 // Trigger developer's attention when using the previously removed argument.
2862 if (func_num_args() > 2) {
2863 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2864 has been removed.', DEBUG_DEVELOPER);
2867 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2868 return false;
2870 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2871 return false;
2873 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2874 foreach($events as $event) {
2875 if ($visible) {
2876 show_event($event);
2877 } else {
2878 hide_event($event);
2883 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2884 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2885 if ($grade_items) {
2886 foreach ($grade_items as $grade_item) {
2887 $grade_item->set_hidden(!$visible);
2891 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2892 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2893 $cminfo = new stdClass();
2894 $cminfo->id = $id;
2895 $cminfo->visible = $visible;
2896 $cminfo->visibleold = $visible;
2897 $DB->update_record('course_modules', $cminfo);
2899 rebuild_course_cache($cm->course, true);
2900 return true;
2904 * Delete a course module and any associated data at the course level (events)
2905 * Until 1.5 this function simply marked a deleted flag ... now it
2906 * deletes it completely.
2909 function delete_course_module($id) {
2910 global $CFG, $DB;
2911 require_once($CFG->libdir.'/gradelib.php');
2912 require_once($CFG->dirroot.'/blog/lib.php');
2914 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2915 return true;
2917 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2918 //delete events from calendar
2919 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2920 foreach($events as $event) {
2921 delete_event($event->id);
2924 //delete grade items, outcome items and grades attached to modules
2925 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2926 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2927 foreach ($grade_items as $grade_item) {
2928 $grade_item->delete('moddelete');
2931 // Delete completion and availability data; it is better to do this even if the
2932 // features are not turned on, in case they were turned on previously (these will be
2933 // very quick on an empty table)
2934 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2935 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2936 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
2937 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2938 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2940 delete_context(CONTEXT_MODULE, $cm->id);
2941 $DB->delete_records('course_modules', array('id'=>$cm->id));
2942 rebuild_course_cache($cm->course, true);
2943 return true;
2946 function delete_mod_from_section($modid, $sectionid) {
2947 global $DB;
2949 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2951 $modarray = explode(",", $section->sequence);
2953 if ($key = array_keys ($modarray, $modid)) {
2954 array_splice($modarray, $key[0], 1);
2955 $newsequence = implode(",", $modarray);
2956 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2957 rebuild_course_cache($section->course, true);
2958 return true;
2959 } else {
2960 return false;
2964 return false;
2968 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2970 * @param object $course course object
2971 * @param int $section Section number (not id!!!)
2972 * @param int $move (-1 or 1)
2973 * @return boolean true if section moved successfully
2974 * @todo MDL-33379 remove this function in 2.5
2976 function move_section($course, $section, $move) {
2977 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
2979 /// Moves a whole course section up and down within the course
2980 global $USER;
2982 if (!$move) {
2983 return true;
2986 $sectiondest = $section + $move;
2988 // compartibility with course formats using field 'numsections'
2989 $courseformatoptions = course_get_format($course)->get_format_options();
2990 if (array_key_exists('numsections', $courseformatoptions) &&
2991 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2992 return false;
2995 $retval = move_section_to($course, $section, $sectiondest);
2996 return $retval;
3000 * Moves a section within a course, from a position to another.
3001 * Be very careful: $section and $destination refer to section number,
3002 * not id!.
3004 * @param object $course
3005 * @param int $section Section number (not id!!!)
3006 * @param int $destination
3007 * @return boolean Result
3009 function move_section_to($course, $section, $destination) {
3010 /// Moves a whole course section up and down within the course
3011 global $USER, $DB;
3013 if (!$destination && $destination != 0) {
3014 return true;
3017 // compartibility with course formats using field 'numsections'
3018 $courseformatoptions = course_get_format($course)->get_format_options();
3019 if ((array_key_exists('numsections', $courseformatoptions) &&
3020 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3021 return false;
3024 // Get all sections for this course and re-order them (2 of them should now share the same section number)
3025 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
3026 'section ASC, id ASC', 'id, section')) {
3027 return false;
3030 $movedsections = reorder_sections($sections, $section, $destination);
3032 // Update all sections. Do this in 2 steps to avoid breaking database
3033 // uniqueness constraint
3034 $transaction = $DB->start_delegated_transaction();
3035 foreach ($movedsections as $id => $position) {
3036 if ($sections[$id] !== $position) {
3037 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
3040 foreach ($movedsections as $id => $position) {
3041 if ($sections[$id] !== $position) {
3042 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
3046 // If we move the highlighted section itself, then just highlight the destination.
3047 // Adjust the higlighted section location if we move something over it either direction.
3048 if ($section == $course->marker) {
3049 course_set_marker($course->id, $destination);
3050 } elseif ($section > $course->marker && $course->marker >= $destination) {
3051 course_set_marker($course->id, $course->marker+1);
3052 } elseif ($section < $course->marker && $course->marker <= $destination) {
3053 course_set_marker($course->id, $course->marker-1);
3056 $transaction->allow_commit();
3057 rebuild_course_cache($course->id, true);
3058 return true;
3062 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
3063 * an original position number and a target position number, rebuilds the array so that the
3064 * move is made without any duplication of section positions.
3065 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
3066 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
3068 * @param array $sections
3069 * @param int $origin_position
3070 * @param int $target_position
3071 * @return array
3073 function reorder_sections($sections, $origin_position, $target_position) {
3074 if (!is_array($sections)) {
3075 return false;
3078 // We can't move section position 0
3079 if ($origin_position < 1) {
3080 echo "We can't move section position 0";
3081 return false;
3084 // Locate origin section in sections array
3085 if (!$origin_key = array_search($origin_position, $sections)) {
3086 echo "searched position not in sections array";
3087 return false; // searched position not in sections array
3090 // Extract origin section
3091 $origin_section = $sections[$origin_key];
3092 unset($sections[$origin_key]);
3094 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3095 $found = false;
3096 $append_array = array();
3097 foreach ($sections as $id => $position) {
3098 if ($found) {
3099 $append_array[$id] = $position;
3100 unset($sections[$id]);
3102 if ($position == $target_position) {
3103 if ($target_position < $origin_position) {
3104 $append_array[$id] = $position;
3105 unset($sections[$id]);
3107 $found = true;
3111 // Append moved section
3112 $sections[$origin_key] = $origin_section;
3114 // Append rest of array (if applicable)
3115 if (!empty($append_array)) {
3116 foreach ($append_array as $id => $position) {
3117 $sections[$id] = $position;
3121 // Renumber positions
3122 $position = 0;
3123 foreach ($sections as $id => $p) {
3124 $sections[$id] = $position;
3125 $position++;
3128 return $sections;
3133 * Move the module object $mod to the specified $section
3134 * If $beforemod exists then that is the module
3135 * before which $modid should be inserted
3136 * All parameters are objects
3138 function moveto_module($mod, $section, $beforemod=NULL) {
3139 global $OUTPUT;
3141 /// Remove original module from original section
3142 if (! delete_mod_from_section($mod->id, $mod->section)) {
3143 echo $OUTPUT->notification("Could not delete module from existing section");
3146 // if moving to a hidden section then hide module
3147 if (!$section->visible && $mod->visible) {
3148 set_coursemodule_visible($mod->id, 0);
3151 /// Add the module into the new section
3152 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
3153 return true;
3157 * Produces the editing buttons for a module
3159 * @global core_renderer $OUTPUT
3160 * @staticvar type $str
3161 * @param stdClass $mod The module to produce editing buttons for
3162 * @param bool $absolute_ignored ignored - all links are absolute
3163 * @param bool $moveselect If true a move seleciton process is used (default true)
3164 * @param int $indent The current indenting
3165 * @param int $section The section to link back to
3166 * @return string XHTML for the editing buttons
3168 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
3169 global $CFG, $OUTPUT, $COURSE;
3171 static $str;
3173 $coursecontext = context_course::instance($mod->course);
3174 $modcontext = context_module::instance($mod->id);
3176 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3177 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3179 // no permission to edit anything
3180 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3181 return false;
3184 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3186 if (!isset($str)) {
3187 $str = new stdClass;
3188 $str->assign = get_string("assignroles", 'role');
3189 $str->delete = get_string("delete");
3190 $str->move = get_string("move");
3191 $str->moveup = get_string("moveup");
3192 $str->movedown = get_string("movedown");
3193 $str->moveright = get_string("moveright");
3194 $str->moveleft = get_string("moveleft");
3195 $str->update = get_string("update");
3196 $str->duplicate = get_string("duplicate");
3197 $str->hide = get_string("hide");
3198 $str->show = get_string("show");
3199 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3200 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3201 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3202 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3203 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3204 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3205 $str->edittitle = get_string('edittitle', 'moodle');
3208 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3210 if ($section !== null) {
3211 $baseurl->param('sr', $section);
3213 $actions = array();
3215 // AJAX edit title
3216 if ($mod->modname !== 'label' && $hasmanageactivities && course_ajax_enabled($COURSE)) {
3217 $actions[] = new action_link(
3218 new moodle_url($baseurl, array('update' => $mod->id)),
3219 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3220 null,
3221 array('class' => 'editing_title', 'title' => $str->edittitle)
3225 // leftright
3226 if ($hasmanageactivities) {
3227 if (right_to_left()) { // Exchange arrows on RTL
3228 $rightarrow = 't/left';
3229 $leftarrow = 't/right';
3230 } else {
3231 $rightarrow = 't/right';
3232 $leftarrow = 't/left';
3235 if ($indent > 0) {
3236 $actions[] = new action_link(
3237 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3238 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3239 null,
3240 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3243 if ($indent >= 0) {
3244 $actions[] = new action_link(
3245 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3246 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3247 null,
3248 array('class' => 'editing_moveright', 'title' => $str->moveright)
3253 // move
3254 if ($hasmanageactivities) {
3255 if ($moveselect) {
3256 $actions[] = new action_link(
3257 new moodle_url($baseurl, array('copy' => $mod->id)),
3258 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3259 null,
3260 array('class' => 'editing_move', 'title' => $str->move)
3262 } else {
3263 $actions[] = new action_link(
3264 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3265 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3266 null,
3267 array('class' => 'editing_moveup', 'title' => $str->moveup)
3269 $actions[] = new action_link(
3270 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3271 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3272 null,
3273 array('class' => 'editing_movedown', 'title' => $str->movedown)
3278 // Update
3279 if ($hasmanageactivities) {
3280 $actions[] = new action_link(
3281 new moodle_url($baseurl, array('update' => $mod->id)),
3282 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3283 null,
3284 array('class' => 'editing_update', 'title' => $str->update)
3288 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3289 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3290 $actions[] = new action_link(
3291 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3292 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3293 null,
3294 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3298 // Delete
3299 if ($hasmanageactivities) {
3300 $actions[] = new action_link(
3301 new moodle_url($baseurl, array('delete' => $mod->id)),
3302 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3303 null,
3304 array('class' => 'editing_delete', 'title' => $str->delete)
3308 // hideshow
3309 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3310 if ($mod->visible) {
3311 $actions[] = new action_link(
3312 new moodle_url($baseurl, array('hide' => $mod->id)),
3313 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3314 null,
3315 array('class' => 'editing_hide', 'title' => $str->hide)
3317 } else {
3318 $actions[] = new action_link(
3319 new moodle_url($baseurl, array('show' => $mod->id)),
3320 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3321 null,
3322 array('class' => 'editing_show', 'title' => $str->show)
3327 // groupmode
3328 if ($hasmanageactivities and $mod->groupmode !== false) {
3329 if ($mod->groupmode == SEPARATEGROUPS) {
3330 $groupmode = 0;
3331 $grouptitle = $str->groupsseparate;
3332 $forcedgrouptitle = $str->forcedgroupsseparate;
3333 $groupclass = 'editing_groupsseparate';
3334 $groupimage = 't/groups';
3335 } else if ($mod->groupmode == VISIBLEGROUPS) {
3336 $groupmode = 1;
3337 $grouptitle = $str->groupsvisible;
3338 $forcedgrouptitle = $str->forcedgroupsvisible;
3339 $groupclass = 'editing_groupsvisible';
3340 $groupimage = 't/groupv';
3341 } else {
3342 $groupmode = 2;
3343 $grouptitle = $str->groupsnone;
3344 $forcedgrouptitle = $str->forcedgroupsnone;
3345 $groupclass = 'editing_groupsnone';
3346 $groupimage = 't/groupn';
3348 if ($mod->groupmodelink) {
3349 $actions[] = new action_link(
3350 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3351 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3352 null,
3353 array('class' => $groupclass, 'title' => $grouptitle)
3355 } else {
3356 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3360 // Assign
3361 if (has_capability('moodle/role:assign', $modcontext)){
3362 $actions[] = new action_link(
3363 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3364 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3365 null,
3366 array('class' => 'editing_assign', 'title' => $str->assign)
3370 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
3371 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
3372 // the course page HTML will allow this to be removed.
3373 $output = ' ' . html_writer::start_tag('span', array('class' => 'commands'));
3374 foreach ($actions as $action) {
3375 if ($action instanceof renderable) {
3376 $output .= $OUTPUT->render($action);
3377 } else {
3378 $output .= $action;
3381 $output .= html_writer::end_tag('span');
3382 return $output;
3386 * given a course object with shortname & fullname, this function will
3387 * truncate the the number of chars allowed and add ... if it was too long
3389 function course_format_name ($course,$max=100) {
3391 $context = context_course::instance($course->id);
3392 $shortname = format_string($course->shortname, true, array('context' => $context));
3393 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3394 $str = $shortname.': '. $fullname;
3395 if (textlib::strlen($str) <= $max) {
3396 return $str;
3398 else {
3399 return textlib::substr($str,0,$max-3).'...';
3404 * Is the user allowed to add this type of module to this course?
3405 * @param object $course the course settings. Only $course->id is used.
3406 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
3407 * @return bool whether the current user is allowed to add this type of module to this course.
3409 function course_allowed_module($course, $modname) {
3410 if (is_numeric($modname)) {
3411 throw new coding_exception('Function course_allowed_module no longer
3412 supports numeric module ids. Please update your code to pass the module name.');
3415 $capability = 'mod/' . $modname . ':addinstance';
3416 if (!get_capability_info($capability)) {
3417 // Debug warning that the capability does not exist, but no more than once per page.
3418 static $warned = array();
3419 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
3420 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
3421 debugging('The module ' . $modname . ' does not define the standard capability ' .
3422 $capability , DEBUG_DEVELOPER);
3423 $warned[$modname] = 1;
3426 // If the capability does not exist, the module can always be added.
3427 return true;
3430 $coursecontext = context_course::instance($course->id);
3431 return has_capability($capability, $coursecontext);
3435 * Recursively delete category including all subcategories and courses.
3436 * @param stdClass $category
3437 * @param boolean $showfeedback display some notices
3438 * @return array return deleted courses
3440 function category_delete_full($category, $showfeedback=true) {
3441 global $CFG, $DB;
3442 require_once($CFG->libdir.'/gradelib.php');
3443 require_once($CFG->libdir.'/questionlib.php');
3444 require_once($CFG->dirroot.'/cohort/lib.php');
3446 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3447 foreach ($children as $childcat) {
3448 category_delete_full($childcat, $showfeedback);
3452 $deletedcourses = array();
3453 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3454 foreach ($courses as $course) {
3455 if (!delete_course($course, false)) {
3456 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3458 $deletedcourses[] = $course;
3462 // move or delete cohorts in this context
3463 cohort_delete_category($category);
3465 // now delete anything that may depend on course category context
3466 grade_course_category_delete($category->id, 0, $showfeedback);
3467 if (!question_delete_course_category($category, 0, $showfeedback)) {
3468 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3471 // finally delete the category and it's context
3472 $DB->delete_records('course_categories', array('id'=>$category->id));
3473 delete_context(CONTEXT_COURSECAT, $category->id);
3475 events_trigger('course_category_deleted', $category);
3477 return $deletedcourses;
3481 * Delete category, but move contents to another category.
3482 * @param object $ccategory
3483 * @param int $newparentid category id
3484 * @return bool status
3486 function category_delete_move($category, $newparentid, $showfeedback=true) {
3487 global $CFG, $DB, $OUTPUT;
3488 require_once($CFG->libdir.'/gradelib.php');
3489 require_once($CFG->libdir.'/questionlib.php');
3490 require_once($CFG->dirroot.'/cohort/lib.php');
3492 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3493 return false;
3496 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3497 foreach ($children as $childcat) {
3498 move_category($childcat, $newparentcat);
3502 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3503 if (!move_courses(array_keys($courses), $newparentid)) {
3504 if ($showfeedback) {
3505 echo $OUTPUT->notification("Error moving courses");
3507 return false;
3509 if ($showfeedback) {
3510 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3514 // move or delete cohorts in this context
3515 cohort_delete_category($category);
3517 // now delete anything that may depend on course category context
3518 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3519 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3520 if ($showfeedback) {
3521 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3523 return false;
3526 // finally delete the category and it's context
3527 $DB->delete_records('course_categories', array('id'=>$category->id));
3528 delete_context(CONTEXT_COURSECAT, $category->id);
3530 events_trigger('course_category_deleted', $category);
3532 if ($showfeedback) {
3533 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3535 return true;
3539 * Efficiently moves many courses around while maintaining
3540 * sortorder in order.
3542 * @param array $courseids is an array of course ids
3543 * @param int $categoryid
3544 * @return bool success
3546 function move_courses($courseids, $categoryid) {
3547 global $CFG, $DB, $OUTPUT;
3549 if (empty($courseids)) {
3550 // nothing to do
3551 return;
3554 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3555 return false;
3558 $courseids = array_reverse($courseids);
3559 $newparent = context_coursecat::instance($category->id);
3560 $i = 1;
3562 foreach ($courseids as $courseid) {
3563 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3564 $course = new stdClass();
3565 $course->id = $courseid;
3566 $course->category = $category->id;
3567 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3568 if ($category->visible == 0) {
3569 // hide the course when moving into hidden category,
3570 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3571 $course->visible = 0;
3574 $DB->update_record('course', $course);
3576 $context = context_course::instance($course->id);
3577 context_moved($context, $newparent);
3580 fix_course_sortorder();
3582 return true;
3586 * Hide course category and child course and subcategories
3587 * @param stdClass $category
3588 * @return void
3590 function course_category_hide($category) {
3591 global $DB;
3593 $category->visible = 0;
3594 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3595 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3596 $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
3597 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3598 // get all child categories and hide too
3599 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3600 foreach ($subcats as $cat) {
3601 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3602 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3603 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3604 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3610 * Show course category and child course and subcategories
3611 * @param stdClass $category
3612 * @return void
3614 function course_category_show($category) {
3615 global $DB;
3617 $category->visible = 1;
3618 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3619 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3620 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3621 // get all child categories and unhide too
3622 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3623 foreach ($subcats as $cat) {
3624 if ($cat->visibleold) {
3625 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3627 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3633 * Efficiently moves a category - NOTE that this can have
3634 * a huge impact access-control-wise...
3636 function move_category($category, $newparentcat) {
3637 global $CFG, $DB;
3639 $context = context_coursecat::instance($category->id);
3641 $hidecat = false;
3642 if (empty($newparentcat->id)) {
3643 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3645 $newparent = context_system::instance();
3647 } else {
3648 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3649 $newparent = context_coursecat::instance($newparentcat->id);
3651 if (!$newparentcat->visible and $category->visible) {
3652 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3653 $hidecat = true;
3657 context_moved($context, $newparent);
3659 // now make it last in new category
3660 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3662 // and fix the sortorders
3663 fix_course_sortorder();
3665 if ($hidecat) {
3666 course_category_hide($category);
3671 * Returns the display name of the given section that the course prefers
3673 * Implementation of this function is provided by course format
3674 * @see format_base::get_section_name()
3676 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
3677 * @param int|stdClass $section Section object from database or just field course_sections.section
3678 * @return string Display name that the course format prefers, e.g. "Week 2"
3680 function get_section_name($courseorid, $section) {
3681 return course_get_format($courseorid)->get_section_name($section);
3685 * Tells if current course format uses sections
3687 * @param string $format Course format ID e.g. 'weeks' $course->format
3688 * @return bool
3690 function course_format_uses_sections($format) {
3691 $course = new stdClass();
3692 $course->format = $format;
3693 return course_get_format($course)->uses_sections();
3697 * Returns the information about the ajax support in the given source format
3699 * The returned object's property (boolean)capable indicates that
3700 * the course format supports Moodle course ajax features.
3701 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3703 * @param string $format
3704 * @return stdClass
3706 function course_format_ajax_support($format) {
3707 $course = new stdClass();
3708 $course->format = $format;
3709 return course_get_format($course)->supports_ajax();
3713 * Can the current user delete this course?
3714 * Course creators have exception,
3715 * 1 day after the creation they can sill delete the course.
3716 * @param int $courseid
3717 * @return boolean
3719 function can_delete_course($courseid) {
3720 global $USER, $DB;
3722 $context = context_course::instance($courseid);
3724 if (has_capability('moodle/course:delete', $context)) {
3725 return true;
3728 // hack: now try to find out if creator created this course recently (1 day)
3729 if (!has_capability('moodle/course:create', $context)) {
3730 return false;
3733 $since = time() - 60*60*24;
3735 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3736 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3738 return $DB->record_exists_select('log', $select, $params);
3742 * Save the Your name for 'Some role' strings.
3744 * @param integer $courseid the id of this course.
3745 * @param array $data the data that came from the course settings form.
3747 function save_local_role_names($courseid, $data) {
3748 global $DB;
3749 $context = context_course::instance($courseid);
3751 foreach ($data as $fieldname => $value) {
3752 if (strpos($fieldname, 'role_') !== 0) {
3753 continue;
3755 list($ignored, $roleid) = explode('_', $fieldname);
3757 // make up our mind whether we want to delete, update or insert
3758 if (!$value) {
3759 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3761 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3762 $rolename->name = $value;
3763 $DB->update_record('role_names', $rolename);
3765 } else {
3766 $rolename = new stdClass;
3767 $rolename->contextid = $context->id;
3768 $rolename->roleid = $roleid;
3769 $rolename->name = $value;
3770 $DB->insert_record('role_names', $rolename);
3776 * Create a course and either return a $course object
3778 * Please note this functions does not verify any access control,
3779 * the calling code is responsible for all validation (usually it is the form definition).
3781 * @param array $editoroptions course description editor options
3782 * @param object $data - all the data needed for an entry in the 'course' table
3783 * @return object new course instance
3785 function create_course($data, $editoroptions = NULL) {
3786 global $CFG, $DB;
3788 //check the categoryid - must be given for all new courses
3789 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3791 //check if the shortname already exist
3792 if (!empty($data->shortname)) {
3793 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3794 throw new moodle_exception('shortnametaken');
3798 //check if the id number already exist
3799 if (!empty($data->idnumber)) {
3800 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3801 throw new moodle_exception('idnumbertaken');
3805 $data->timecreated = time();
3806 $data->timemodified = $data->timecreated;
3808 // place at beginning of any category
3809 $data->sortorder = 0;
3811 if ($editoroptions) {
3812 // summary text is updated later, we need context to store the files first
3813 $data->summary = '';
3814 $data->summary_format = FORMAT_HTML;
3817 if (!isset($data->visible)) {
3818 // data not from form, add missing visibility info
3819 $data->visible = $category->visible;
3821 $data->visibleold = $data->visible;
3823 $newcourseid = $DB->insert_record('course', $data);
3824 $context = context_course::instance($newcourseid, MUST_EXIST);
3826 if ($editoroptions) {
3827 // Save the files used in the summary editor and store
3828 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3829 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3830 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3833 // update course format options
3834 course_get_format($newcourseid)->update_course_format_options($data);
3836 $course = course_get_format($newcourseid)->get_course();
3838 // Setup the blocks
3839 blocks_add_default_course_blocks($course);
3841 // Create a default section.
3842 course_create_sections_if_missing($course, 0);
3844 fix_course_sortorder();
3846 // new context created - better mark it as dirty
3847 mark_context_dirty($context->path);
3849 // Save any custom role names.
3850 save_local_role_names($course->id, (array)$data);
3852 // set up enrolments
3853 enrol_course_updated(true, $course, $data);
3855 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3857 // Trigger events
3858 events_trigger('course_created', $course);
3860 return $course;
3864 * Create a new course category and marks the context as dirty
3866 * This function does not set the sortorder for the new category and
3867 * @see{fix_course_sortorder} should be called after creating a new course
3868 * category
3870 * Please note that this function does not verify access control.
3872 * @param object $category All of the data required for an entry in the course_categories table
3873 * @return object new course category
3875 function create_course_category($category) {
3876 global $DB;
3878 $category->timemodified = time();
3879 $category->id = $DB->insert_record('course_categories', $category);
3880 $category = $DB->get_record('course_categories', array('id' => $category->id));
3882 // We should mark the context as dirty
3883 $category->context = context_coursecat::instance($category->id);
3884 $category->context->mark_dirty();
3886 return $category;
3890 * Update a course.
3892 * Please note this functions does not verify any access control,
3893 * the calling code is responsible for all validation (usually it is the form definition).
3895 * @param object $data - all the data needed for an entry in the 'course' table
3896 * @param array $editoroptions course description editor options
3897 * @return void
3899 function update_course($data, $editoroptions = NULL) {
3900 global $CFG, $DB;
3902 $data->timemodified = time();
3904 $oldcourse = course_get_format($data->id)->get_course();
3905 $context = context_course::instance($oldcourse->id);
3907 if ($editoroptions) {
3908 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3911 if (!isset($data->category) or empty($data->category)) {
3912 // prevent nulls and 0 in category field
3913 unset($data->category);
3915 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3917 if (!isset($data->visible)) {
3918 // data not from form, add missing visibility info
3919 $data->visible = $oldcourse->visible;
3922 if ($data->visible != $oldcourse->visible) {
3923 // reset the visibleold flag when manually hiding/unhiding course
3924 $data->visibleold = $data->visible;
3925 } else {
3926 if ($movecat) {
3927 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3928 if (empty($newcategory->visible)) {
3929 // make sure when moving into hidden category the course is hidden automatically
3930 $data->visible = 0;
3935 // Update with the new data
3936 $DB->update_record('course', $data);
3937 // make sure the modinfo cache is reset
3938 rebuild_course_cache($data->id);
3940 // update course format options with full course data
3941 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
3943 $course = $DB->get_record('course', array('id'=>$data->id));
3945 if ($movecat) {
3946 $newparent = context_coursecat::instance($course->category);
3947 context_moved($context, $newparent);
3950 fix_course_sortorder();
3952 // Test for and remove blocks which aren't appropriate anymore
3953 blocks_remove_inappropriate($course);
3955 // Save any custom role names.
3956 save_local_role_names($course->id, $data);
3958 // update enrol settings
3959 enrol_course_updated(false, $course, $data);
3961 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3963 // Trigger events
3964 events_trigger('course_updated', $course);
3966 if ($oldcourse->format !== $course->format) {
3967 // Remove all options stored for the previous format
3968 // We assume that new course format migrated everything it needed watching trigger
3969 // 'course_updated' and in method format_XXX::update_course_format_options()
3970 $DB->delete_records('course_format_options',
3971 array('courseid' => $course->id, 'format' => $oldcourse->format));
3976 * Average number of participants
3977 * @return integer
3979 function average_number_of_participants() {
3980 global $DB, $SITE;
3982 //count total of enrolments for visible course (except front page)
3983 $sql = 'SELECT COUNT(*) FROM (
3984 SELECT DISTINCT ue.userid, e.courseid
3985 FROM {user_enrolments} ue, {enrol} e, {course} c
3986 WHERE ue.enrolid = e.id
3987 AND e.courseid <> :siteid
3988 AND c.id = e.courseid
3989 AND c.visible = 1) total';
3990 $params = array('siteid' => $SITE->id);
3991 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3994 //count total of visible courses (minus front page)
3995 $coursetotal = $DB->count_records('course', array('visible' => 1));
3996 $coursetotal = $coursetotal - 1 ;
3998 //average of enrolment
3999 if (empty($coursetotal)) {
4000 $participantaverage = 0;
4001 } else {
4002 $participantaverage = $enrolmenttotal / $coursetotal;
4005 return $participantaverage;
4009 * Average number of course modules
4010 * @return integer
4012 function average_number_of_courses_modules() {
4013 global $DB, $SITE;
4015 //count total of visible course module (except front page)
4016 $sql = 'SELECT COUNT(*) FROM (
4017 SELECT cm.course, cm.module
4018 FROM {course} c, {course_modules} cm
4019 WHERE c.id = cm.course
4020 AND c.id <> :siteid
4021 AND cm.visible = 1
4022 AND c.visible = 1) total';
4023 $params = array('siteid' => $SITE->id);
4024 $moduletotal = $DB->count_records_sql($sql, $params);
4027 //count total of visible courses (minus front page)
4028 $coursetotal = $DB->count_records('course', array('visible' => 1));
4029 $coursetotal = $coursetotal - 1 ;
4031 //average of course module
4032 if (empty($coursetotal)) {
4033 $coursemoduleaverage = 0;
4034 } else {
4035 $coursemoduleaverage = $moduletotal / $coursetotal;
4038 return $coursemoduleaverage;
4042 * This class pertains to course requests and contains methods associated with
4043 * create, approving, and removing course requests.
4045 * Please note we do not allow embedded images here because there is no context
4046 * to store them with proper access control.
4048 * @copyright 2009 Sam Hemelryk
4049 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4050 * @since Moodle 2.0
4052 * @property-read int $id
4053 * @property-read string $fullname
4054 * @property-read string $shortname
4055 * @property-read string $summary
4056 * @property-read int $summaryformat
4057 * @property-read int $summarytrust
4058 * @property-read string $reason
4059 * @property-read int $requester
4061 class course_request {
4064 * This is the stdClass that stores the properties for the course request
4065 * and is externally accessed through the __get magic method
4066 * @var stdClass
4068 protected $properties;
4071 * An array of options for the summary editor used by course request forms.
4072 * This is initially set by {@link summary_editor_options()}
4073 * @var array
4074 * @static
4076 protected static $summaryeditoroptions;
4079 * Static function to prepare the summary editor for working with a course
4080 * request.
4082 * @static
4083 * @param null|stdClass $data Optional, an object containing the default values
4084 * for the form, these may be modified when preparing the
4085 * editor so this should be called before creating the form
4086 * @return stdClass An object that can be used to set the default values for
4087 * an mforms form
4089 public static function prepare($data=null) {
4090 if ($data === null) {
4091 $data = new stdClass;
4093 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4094 return $data;
4098 * Static function to create a new course request when passed an array of properties
4099 * for it.
4101 * This function also handles saving any files that may have been used in the editor
4103 * @static
4104 * @param stdClass $data
4105 * @return course_request The newly created course request
4107 public static function create($data) {
4108 global $USER, $DB, $CFG;
4109 $data->requester = $USER->id;
4111 // Setting the default category if none set.
4112 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
4113 $data->category = $CFG->defaultrequestcategory;
4116 // Summary is a required field so copy the text over
4117 $data->summary = $data->summary_editor['text'];
4118 $data->summaryformat = $data->summary_editor['format'];
4120 $data->id = $DB->insert_record('course_request', $data);
4122 // Create a new course_request object and return it
4123 $request = new course_request($data);
4125 // Notify the admin if required.
4126 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4128 $a = new stdClass;
4129 $a->link = "$CFG->wwwroot/course/pending.php";
4130 $a->user = fullname($USER);
4131 $subject = get_string('courserequest');
4132 $message = get_string('courserequestnotifyemail', 'admin', $a);
4133 foreach ($users as $user) {
4134 $request->notify($user, $USER, 'courserequested', $subject, $message);
4138 return $request;
4142 * Returns an array of options to use with a summary editor
4144 * @uses course_request::$summaryeditoroptions
4145 * @return array An array of options to use with the editor
4147 public static function summary_editor_options() {
4148 global $CFG;
4149 if (self::$summaryeditoroptions === null) {
4150 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4152 return self::$summaryeditoroptions;
4156 * Loads the properties for this course request object. Id is required and if
4157 * only id is provided then we load the rest of the properties from the database
4159 * @param stdClass|int $properties Either an object containing properties
4160 * or the course_request id to load
4162 public function __construct($properties) {
4163 global $DB;
4164 if (empty($properties->id)) {
4165 if (empty($properties)) {
4166 throw new coding_exception('You must provide a course request id when creating a course_request object');
4168 $id = $properties;
4169 $properties = new stdClass;
4170 $properties->id = (int)$id;
4171 unset($id);
4173 if (empty($properties->requester)) {
4174 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4175 print_error('unknowncourserequest');
4177 } else {
4178 $this->properties = $properties;
4180 $this->properties->collision = null;
4184 * Returns the requested property
4186 * @param string $key
4187 * @return mixed
4189 public function __get($key) {
4190 return $this->properties->$key;
4194 * Override this to ensure empty($request->blah) calls return a reliable answer...
4196 * This is required because we define the __get method
4198 * @param mixed $key
4199 * @return bool True is it not empty, false otherwise
4201 public function __isset($key) {
4202 return (!empty($this->properties->$key));
4206 * Returns the user who requested this course
4208 * Uses a static var to cache the results and cut down the number of db queries
4210 * @staticvar array $requesters An array of cached users
4211 * @return stdClass The user who requested the course
4213 public function get_requester() {
4214 global $DB;
4215 static $requesters= array();
4216 if (!array_key_exists($this->properties->requester, $requesters)) {
4217 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4219 return $requesters[$this->properties->requester];
4223 * Checks that the shortname used by the course does not conflict with any other
4224 * courses that exist
4226 * @param string|null $shortnamemark The string to append to the requests shortname
4227 * should a conflict be found
4228 * @return bool true is there is a conflict, false otherwise
4230 public function check_shortname_collision($shortnamemark = '[*]') {
4231 global $DB;
4233 if ($this->properties->collision !== null) {
4234 return $this->properties->collision;
4237 if (empty($this->properties->shortname)) {
4238 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4239 $this->properties->collision = false;
4240 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4241 if (!empty($shortnamemark)) {
4242 $this->properties->shortname .= ' '.$shortnamemark;
4244 $this->properties->collision = true;
4245 } else {
4246 $this->properties->collision = false;
4248 return $this->properties->collision;
4252 * This function approves the request turning it into a course
4254 * This function converts the course request into a course, at the same time
4255 * transferring any files used in the summary to the new course and then removing
4256 * the course request and the files associated with it.
4258 * @return int The id of the course that was created from this request
4260 public function approve() {
4261 global $CFG, $DB, $USER;
4263 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4265 $courseconfig = get_config('moodlecourse');
4267 // Transfer appropriate settings
4268 $data = clone($this->properties);
4269 unset($data->id);
4270 unset($data->reason);
4271 unset($data->requester);
4273 // If the category is not set, if the current user does not have the rights to change the category, or if the
4274 // category does not exist, we set the default category to the course to be approved.
4275 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
4276 if (empty($data->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
4277 (!$category = get_course_category($data->category))) {
4278 $category = get_course_category($CFG->defaultrequestcategory);
4281 // Set category
4282 $data->category = $category->id;
4283 $data->sortorder = $category->sortorder; // place as the first in category
4285 // Set misc settings
4286 $data->requested = 1;
4288 // Apply course default settings
4289 $data->format = $courseconfig->format;
4290 $data->newsitems = $courseconfig->newsitems;
4291 $data->showgrades = $courseconfig->showgrades;
4292 $data->showreports = $courseconfig->showreports;
4293 $data->maxbytes = $courseconfig->maxbytes;
4294 $data->groupmode = $courseconfig->groupmode;
4295 $data->groupmodeforce = $courseconfig->groupmodeforce;
4296 $data->visible = $courseconfig->visible;
4297 $data->visibleold = $data->visible;
4298 $data->lang = $courseconfig->lang;
4300 $course = create_course($data);
4301 $context = context_course::instance($course->id, MUST_EXIST);
4303 // add enrol instances
4304 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4305 if ($manual = enrol_get_plugin('manual')) {
4306 $manual->add_default_instance($course);
4310 // enrol the requester as teacher if necessary
4311 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4312 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4315 $this->delete();
4317 $a = new stdClass();
4318 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
4319 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4320 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4322 return $course->id;
4326 * Reject a course request
4328 * This function rejects a course request, emailing the requesting user the
4329 * provided notice and then removing the request from the database
4331 * @param string $notice The message to display to the user
4333 public function reject($notice) {
4334 global $USER, $DB;
4335 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4336 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4337 $this->delete();
4341 * Deletes the course request and any associated files
4343 public function delete() {
4344 global $DB;
4345 $DB->delete_records('course_request', array('id' => $this->properties->id));
4349 * Send a message from one user to another using events_trigger
4351 * @param object $touser
4352 * @param object $fromuser
4353 * @param string $name
4354 * @param string $subject
4355 * @param string $message
4357 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4358 $eventdata = new stdClass();
4359 $eventdata->component = 'moodle';
4360 $eventdata->name = $name;
4361 $eventdata->userfrom = $fromuser;
4362 $eventdata->userto = $touser;
4363 $eventdata->subject = $subject;
4364 $eventdata->fullmessage = $message;
4365 $eventdata->fullmessageformat = FORMAT_PLAIN;
4366 $eventdata->fullmessagehtml = '';
4367 $eventdata->smallmessage = '';
4368 $eventdata->notification = 1;
4369 message_send($eventdata);
4374 * Return a list of page types
4375 * @param string $pagetype current page type
4376 * @param stdClass $parentcontext Block's parent context
4377 * @param stdClass $currentcontext Current context of block
4379 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4380 // if above course context ,display all course fomats
4381 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4382 if ($course->id == SITEID) {
4383 return array('*'=>get_string('page-x', 'pagetype'));
4384 } else {
4385 return array('*'=>get_string('page-x', 'pagetype'),
4386 'course-*'=>get_string('page-course-x', 'pagetype'),
4387 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
4393 * Determine whether course ajax should be enabled for the specified course
4395 * @param stdClass $course The course to test against
4396 * @return boolean Whether course ajax is enabled or note
4398 function course_ajax_enabled($course) {
4399 global $CFG, $PAGE, $SITE;
4401 // Ajax must be enabled globally
4402 if (!$CFG->enableajax) {
4403 return false;
4406 // The user must be editing for AJAX to be included
4407 if (!$PAGE->user_is_editing()) {
4408 return false;
4411 // Check that the theme suports
4412 if (!$PAGE->theme->enablecourseajax) {
4413 return false;
4416 // Check that the course format supports ajax functionality
4417 // The site 'format' doesn't have information on course format support
4418 if ($SITE->id !== $course->id) {
4419 $courseformatajaxsupport = course_format_ajax_support($course->format);
4420 if (!$courseformatajaxsupport->capable) {
4421 return false;
4425 // All conditions have been met so course ajax should be enabled
4426 return true;
4430 * Include the relevant javascript and language strings for the resource
4431 * toolbox YUI module
4433 * @param integer $id The ID of the course being applied to
4434 * @param array $usedmodules An array containing the names of the modules in use on the page
4435 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
4436 * @param stdClass $config An object containing configuration parameters for ajax modules including:
4437 * * resourceurl The URL to post changes to for resource changes
4438 * * sectionurl The URL to post changes to for section changes
4439 * * pageparams Additional parameters to pass through in the post
4440 * @return bool
4442 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
4443 global $PAGE, $SITE;
4445 // Ensure that ajax should be included
4446 if (!course_ajax_enabled($course)) {
4447 return false;
4450 if (!$config) {
4451 $config = new stdClass();
4454 // The URL to use for resource changes
4455 if (!isset($config->resourceurl)) {
4456 $config->resourceurl = '/course/rest.php';
4459 // The URL to use for section changes
4460 if (!isset($config->sectionurl)) {
4461 $config->sectionurl = '/course/rest.php';
4464 // Any additional parameters which need to be included on page submission
4465 if (!isset($config->pageparams)) {
4466 $config->pageparams = array();
4469 // Include toolboxes
4470 $PAGE->requires->yui_module('moodle-course-toolboxes',
4471 'M.course.init_resource_toolbox',
4472 array(array(
4473 'courseid' => $course->id,
4474 'ajaxurl' => $config->resourceurl,
4475 'config' => $config,
4478 $PAGE->requires->yui_module('moodle-course-toolboxes',
4479 'M.course.init_section_toolbox',
4480 array(array(
4481 'courseid' => $course->id,
4482 'format' => $course->format,
4483 'ajaxurl' => $config->sectionurl,
4484 'config' => $config,
4488 // Include course dragdrop
4489 if ($course->id != $SITE->id) {
4490 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
4491 array(array(
4492 'courseid' => $course->id,
4493 'ajaxurl' => $config->sectionurl,
4494 'config' => $config,
4495 )), null, true);
4497 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
4498 array(array(
4499 'courseid' => $course->id,
4500 'ajaxurl' => $config->resourceurl,
4501 'config' => $config,
4502 )), null, true);
4505 // Include blocks dragdrop
4506 $params = array(
4507 'courseid' => $course->id,
4508 'pagetype' => $PAGE->pagetype,
4509 'pagelayout' => $PAGE->pagelayout,
4510 'subpage' => $PAGE->subpage,
4511 'regions' => $PAGE->blocks->get_regions(),
4513 $PAGE->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
4515 // Require various strings for the command toolbox
4516 $PAGE->requires->strings_for_js(array(
4517 'moveleft',
4518 'deletechecktype',
4519 'deletechecktypename',
4520 'edittitle',
4521 'edittitleinstructions',
4522 'show',
4523 'hide',
4524 'groupsnone',
4525 'groupsvisible',
4526 'groupsseparate',
4527 'clicktochangeinbrackets',
4528 'markthistopic',
4529 'markedthistopic',
4530 'move',
4531 'movesection',
4532 ), 'moodle');
4534 // Include format-specific strings
4535 if ($course->id != $SITE->id) {
4536 $PAGE->requires->strings_for_js(array(
4537 'showfromothers',
4538 'hidefromothers',
4539 ), 'format_' . $course->format);
4542 // For confirming resource deletion we need the name of the module in question
4543 foreach ($usedmodules as $module => $modname) {
4544 $PAGE->requires->string_for_js('pluginname', $module);
4547 // Load drag and drop upload AJAX.
4548 dndupload_add_to_course($course, $enabledmodules);
4550 // Add the module chooser
4551 $PAGE->requires->yui_module('moodle-course-modchooser',
4552 'M.course.init_chooser',
4553 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
4555 $PAGE->requires->strings_for_js(array(
4556 'addresourceoractivity',
4557 'modchooserenable',
4558 'modchooserdisable',
4559 ), 'moodle');
4561 return true;
4565 * Returns the sorted list of available course formats, filtered by enabled if necessary
4567 * @param bool $enabledonly return only formats that are enabled
4568 * @return array array of sorted format names
4570 function get_sorted_course_formats($enabledonly = false) {
4571 global $CFG;
4572 $formats = get_plugin_list('format');
4574 if (!empty($CFG->format_plugins_sortorder)) {
4575 $order = explode(',', $CFG->format_plugins_sortorder);
4576 $order = array_merge(array_intersect($order, array_keys($formats)),
4577 array_diff(array_keys($formats), $order));
4578 } else {
4579 $order = array_keys($formats);
4581 if (!$enabledonly) {
4582 return $order;
4584 $sortedformats = array();
4585 foreach ($order as $formatname) {
4586 if (!get_config('format_'.$formatname, 'disabled')) {
4587 $sortedformats[] = $formatname;
4590 return $sortedformats;
4594 * The URL to use for the specified course (with section)
4596 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
4597 * @param int|stdClass $section Section object from database or just field course_sections.section
4598 * if omitted the course view page is returned
4599 * @param array $options options for view URL. At the moment core uses:
4600 * 'navigation' (bool) if true and section has no separate page, the function returns null
4601 * 'sr' (int) used by multipage formats to specify to which section to return
4602 * @return moodle_url The url of course
4604 function course_get_url($courseorid, $section = null, $options = array()) {
4605 return course_get_format($courseorid)->get_view_url($section, $options);