3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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
38 * Number of courses to display when summaries are included.
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) {
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
73 if (strpos($url, '../') === 0) {
74 $url = ltrim($url, '.');
76 $url = "/course/$url";
81 $url = "/$module/$url";
94 $url = "/message/$url";
106 $url = "/mod/$module/$url";
110 //now let's sanitise urls - there might be some ugly nasties:-(
111 $parts = explode('?', $url);
112 $script = array_shift($parts);
113 if (strpos($script, 'http') === 0) {
114 $script = clean_param($script, PARAM_URL
);
116 $script = clean_param($script, PARAM_PATH
);
121 $query = implode('', $parts);
122 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
123 $parts = explode('&', $query);
124 $eq = urlencode('=');
125 foreach ($parts as $key=>$part) {
126 $part = urlencode(urldecode($part));
127 $part = str_replace($eq, '=', $part);
128 $parts[$key] = $part;
130 $query = '?'.implode('&', $parts);
133 return $script.$query;
137 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
138 $modname="", $modid=0, $modaction="", $groupid=0) {
141 // It is assumed that $date is the GMT time of midnight for that day,
142 // and so the next 86400 seconds worth of logs are printed.
144 /// Setup for group handling.
146 // TODO: I don't understand group/context/etc. enough to be able to do
147 // something interesting with it here
148 // What is the context of a remote course?
150 /// If the group mode is separate, and this user does not have editing privileges,
151 /// then only the user's group can be viewed.
152 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
153 // $groupid = get_current_group($course->id);
155 /// If this course doesn't have groups, no groupid can be specified.
156 //else if (!$course->groupmode) {
165 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
167 LEFT JOIN {user} u ON l.userid = u.id
171 $where .= "l.hostid = :hostid";
172 $params['hostid'] = $hostid;
174 // TODO: Is 1 really a magic number referring to the sitename?
175 if ($course != SITEID ||
$modid != 0) {
176 $where .= " AND l.course=:courseid";
177 $params['courseid'] = $course;
181 $where .= " AND l.module = :modname";
182 $params['modname'] = $modname;
185 if ('site_errors' === $modid) {
186 $where .= " AND ( l.action='error' OR l.action='infected' )";
188 //TODO: This assumes that modids are the same across sites... probably
190 $where .= " AND l.cmid = :modid";
191 $params['modid'] = $modid;
195 $firstletter = substr($modaction, 0, 1);
196 if ($firstletter == '-') {
197 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
198 $params['modaction'] = '%'.substr($modaction, 1).'%';
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
201 $params['modaction'] = '%'.$modaction.'%';
206 $where .= " AND l.userid = :user";
207 $params['user'] = $user;
211 $enddate = $date +
86400;
212 $where .= " AND l.time > :date AND l.time < :enddate";
213 $params['date'] = $date;
214 $params['enddate'] = $enddate;
218 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
219 if(!empty($result['totalcount'])) {
220 $where .= " ORDER BY $order";
221 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
223 $result['logs'] = array();
228 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
229 $modname="", $modid=0, $modaction="", $groupid=0) {
230 global $DB, $SESSION, $USER;
231 // It is assumed that $date is the GMT time of midnight for that day,
232 // and so the next 86400 seconds worth of logs are printed.
234 /// Setup for group handling.
236 /// If the group mode is separate, and this user does not have editing privileges,
237 /// then only the user's group can be viewed.
238 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', context_course
::instance($course->id
))) {
239 if (isset($SESSION->currentgroup
[$course->id
])) {
240 $groupid = $SESSION->currentgroup
[$course->id
];
242 $groupid = groups_get_all_groups($course->id
, $USER->id
);
243 if (is_array($groupid)) {
244 $groupid = array_shift(array_keys($groupid));
245 $SESSION->currentgroup
[$course->id
] = $groupid;
251 /// If this course doesn't have groups, no groupid can be specified.
252 else if (!$course->groupmode
) {
259 if ($course->id
!= SITEID ||
$modid != 0) {
260 $joins[] = "l.course = :courseid";
261 $params['courseid'] = $course->id
;
265 $joins[] = "l.module = :modname";
266 $params['modname'] = $modname;
269 if ('site_errors' === $modid) {
270 $joins[] = "( l.action='error' OR l.action='infected' )";
272 $joins[] = "l.cmid = :modid";
273 $params['modid'] = $modid;
277 $firstletter = substr($modaction, 0, 1);
278 if ($firstletter == '-') {
279 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
280 $params['modaction'] = '%'.substr($modaction, 1).'%';
282 $joins[] = $DB->sql_like('l.action', ':modaction', false);
283 $params['modaction'] = '%'.$modaction.'%';
288 /// Getting all members of a group.
289 if ($groupid and !$user) {
290 if ($gusers = groups_get_members($groupid)) {
291 $gusers = array_keys($gusers);
292 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
294 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
298 $joins[] = "l.userid = :userid";
299 $params['userid'] = $user;
303 $enddate = $date +
86400;
304 $joins[] = "l.time > :date AND l.time < :enddate";
305 $params['date'] = $date;
306 $params['enddate'] = $enddate;
309 $selector = implode(' AND ', $joins);
311 $totalcount = 0; // Initialise
313 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
314 $result['totalcount'] = $totalcount;
319 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
320 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
322 global $CFG, $DB, $OUTPUT;
324 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
325 $modname, $modid, $modaction, $groupid)) {
326 echo $OUTPUT->notification("No logs found!");
327 echo $OUTPUT->footer();
333 if ($course->id
== SITEID
) {
335 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
336 foreach ($ccc as $cc) {
337 $courses[$cc->id
] = $cc->shortname
;
341 $courses[$course->id
] = $course->shortname
;
344 $totalcount = $logs['totalcount'];
347 $tt = getdate(time());
348 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
350 $strftimedatetime = get_string("strftimedatetime");
352 echo "<div class=\"info\">\n";
353 print_string("displayingrecords", "", $totalcount);
356 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
358 $table = new html_table();
359 $table->classes
= array('logtable','generaltable');
360 $table->align
= array('right', 'left', 'left');
361 $table->head
= array(
363 get_string('ip_address'),
364 get_string('fullnameuser'),
365 get_string('action'),
368 $table->data
= array();
370 if ($course->id
== SITEID
) {
371 array_unshift($table->align
, 'left');
372 array_unshift($table->head
, get_string('course'));
375 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
376 if (empty($logs['logs'])) {
377 $logs['logs'] = array();
380 foreach ($logs['logs'] as $log) {
382 if (isset($ldcache[$log->module
][$log->action
])) {
383 $ld = $ldcache[$log->module
][$log->action
];
385 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
386 $ldcache[$log->module
][$log->action
] = $ld;
388 if ($ld && is_numeric($log->info
)) {
389 // ugly hack to make sure fullname is shown correctly
390 if ($ld->mtable
== 'user' && $ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname')) {
391 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
393 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
398 $log->info
= format_string($log->info
);
400 // If $log->url has been trimmed short by the db size restriction
401 // code in add_to_log, keep a note so we don't add a link to a broken url
402 $brokenurl=(textlib
::strlen($log->url
)==100 && textlib
::substr($log->url
,97)=='...');
405 if ($course->id
== SITEID
) {
406 if (empty($log->course
)) {
407 $row[] = get_string('site');
409 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>";
413 $row[] = userdate($log->time
, '%a').' '.userdate($log->time
, $strftimedatetime);
415 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
416 $row[] = $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
418 $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
))));
420 $displayaction="$log->module $log->action";
422 $row[] = $displayaction;
424 $link = make_log_url($log->module
,$log->url
);
425 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
428 $table->data
[] = $row;
431 echo html_writer
::table($table);
432 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
436 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
437 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
439 global $CFG, $DB, $OUTPUT;
441 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
442 $modname, $modid, $modaction, $groupid)) {
443 echo $OUTPUT->notification("No logs found!");
444 echo $OUTPUT->footer();
448 if ($course->id
== SITEID
) {
450 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
451 foreach ($ccc as $cc) {
452 $courses[$cc->id
] = $cc->shortname
;
457 $totalcount = $logs['totalcount'];
460 $tt = getdate(time());
461 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
463 $strftimedatetime = get_string("strftimedatetime");
465 echo "<div class=\"info\">\n";
466 print_string("displayingrecords", "", $totalcount);
469 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
471 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
473 if ($course->id
== SITEID
) {
474 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
476 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
477 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
478 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
479 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
480 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
483 if (empty($logs['logs'])) {
489 foreach ($logs['logs'] as $log) {
491 $log->info
= $log->coursename
;
492 $row = ($row +
1) %
2;
494 if (isset($ldcache[$log->module
][$log->action
])) {
495 $ld = $ldcache[$log->module
][$log->action
];
497 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
498 $ldcache[$log->module
][$log->action
] = $ld;
500 if (0 && $ld && !empty($log->info
)) {
501 // ugly hack to make sure fullname is shown correctly
502 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
503 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
505 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
510 $log->info
= format_string($log->info
);
512 echo '<tr class="r'.$row.'">';
513 if ($course->id
== SITEID
) {
514 $courseshortname = format_string($courses[$log->course
], true, array('context' => context_course
::instance(SITEID
)));
515 echo "<td class=\"r$row c0\" >\n";
516 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
519 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
520 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
521 echo "<td class=\"r$row c2\" >\n";
522 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
523 echo $OUTPUT->action_link($link, $log->ip
, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
525 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course
::instance($course->id
)));
526 echo "<td class=\"r$row c3\" >\n";
527 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
529 echo "<td class=\"r$row c4\">\n";
530 echo $log->action
.': '.$log->module
;
532 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
537 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
541 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
542 $modid, $modaction, $groupid) {
545 require_once($CFG->libdir
. '/csvlib.class.php');
547 $csvexporter = new csv_export_writer('tab');
550 $header[] = get_string('course');
551 $header[] = get_string('time');
552 $header[] = get_string('ip_address');
553 $header[] = get_string('fullnameuser');
554 $header[] = get_string('action');
555 $header[] = get_string('info');
557 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
558 $modname, $modid, $modaction, $groupid)) {
564 if ($course->id
== SITEID
) {
566 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
567 foreach ($ccc as $cc) {
568 $courses[$cc->id
] = $cc->shortname
;
572 $courses[$course->id
] = $course->shortname
;
577 $tt = getdate(time());
578 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
580 $strftimedatetime = get_string("strftimedatetime");
582 $csvexporter->set_filename('logs', '.txt');
583 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
584 $csvexporter->add_data($title);
585 $csvexporter->add_data($header);
587 if (empty($logs['logs'])) {
591 foreach ($logs['logs'] as $log) {
592 if (isset($ldcache[$log->module
][$log->action
])) {
593 $ld = $ldcache[$log->module
][$log->action
];
595 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
596 $ldcache[$log->module
][$log->action
] = $ld;
598 if ($ld && is_numeric($log->info
)) {
599 // ugly hack to make sure fullname is shown correctly
600 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
601 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
603 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
608 $log->info
= format_string($log->info
);
609 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
611 $coursecontext = context_course
::instance($course->id
);
612 $firstField = format_string($courses[$log->course
], true, array('context' => $coursecontext));
613 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
614 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
615 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
.' ('.$actionurl.')', $log->info
);
616 $csvexporter->add_data($row);
618 $csvexporter->download_file();
623 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
624 $modid, $modaction, $groupid) {
628 require_once("$CFG->libdir/excellib.class.php");
630 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
631 $modname, $modid, $modaction, $groupid)) {
637 if ($course->id
== SITEID
) {
639 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
640 foreach ($ccc as $cc) {
641 $courses[$cc->id
] = $cc->shortname
;
645 $courses[$course->id
] = $course->shortname
;
650 $tt = getdate(time());
651 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
653 $strftimedatetime = get_string("strftimedatetime");
655 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
656 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
659 $workbook = new MoodleExcelWorkbook('-');
660 $workbook->send($filename);
662 $worksheet = array();
663 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
664 get_string('fullnameuser'), get_string('action'), get_string('info'));
666 // Creating worksheets
667 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
668 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
669 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
670 $worksheet[$wsnumber]->set_column(1, 1, 30);
671 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
672 userdate(time(), $strftimedatetime));
674 foreach ($headers as $item) {
675 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
680 if (empty($logs['logs'])) {
685 $formatDate =& $workbook->add_format();
686 $formatDate->set_num_format(get_string('log_excel_date_format'));
688 $row = FIRSTUSEDEXCELROW
;
690 $myxls =& $worksheet[$wsnumber];
691 foreach ($logs['logs'] as $log) {
692 if (isset($ldcache[$log->module
][$log->action
])) {
693 $ld = $ldcache[$log->module
][$log->action
];
695 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
696 $ldcache[$log->module
][$log->action
] = $ld;
698 if ($ld && is_numeric($log->info
)) {
699 // ugly hack to make sure fullname is shown correctly
700 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
701 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
703 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
708 $log->info
= format_string($log->info
);
709 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
712 if ($row > EXCELROWS
) {
714 $myxls =& $worksheet[$wsnumber];
715 $row = FIRSTUSEDEXCELROW
;
719 $coursecontext = context_course
::instance($course->id
);
721 $myxls->write($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)), '');
722 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
723 $myxls->write($row, 2, $log->ip
, '');
724 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
725 $myxls->write($row, 3, $fullname, '');
726 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
727 $myxls->write($row, 4, $log->module
.' '.$log->action
.' ('.$actionurl.')', '');
728 $myxls->write($row, 5, $log->info
, '');
737 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
738 $modid, $modaction, $groupid) {
742 require_once("$CFG->libdir/odslib.class.php");
744 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
745 $modname, $modid, $modaction, $groupid)) {
751 if ($course->id
== SITEID
) {
753 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
754 foreach ($ccc as $cc) {
755 $courses[$cc->id
] = $cc->shortname
;
759 $courses[$course->id
] = $course->shortname
;
764 $tt = getdate(time());
765 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
767 $strftimedatetime = get_string("strftimedatetime");
769 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
770 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
773 $workbook = new MoodleODSWorkbook('-');
774 $workbook->send($filename);
776 $worksheet = array();
777 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
778 get_string('fullnameuser'), get_string('action'), get_string('info'));
780 // Creating worksheets
781 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
782 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
783 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
784 $worksheet[$wsnumber]->set_column(1, 1, 30);
785 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
786 userdate(time(), $strftimedatetime));
788 foreach ($headers as $item) {
789 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
794 if (empty($logs['logs'])) {
799 $formatDate =& $workbook->add_format();
800 $formatDate->set_num_format(get_string('log_excel_date_format'));
802 $row = FIRSTUSEDEXCELROW
;
804 $myxls =& $worksheet[$wsnumber];
805 foreach ($logs['logs'] as $log) {
806 if (isset($ldcache[$log->module
][$log->action
])) {
807 $ld = $ldcache[$log->module
][$log->action
];
809 $ld = $DB->get_record('log_display', array('module'=>$log->module
, 'action'=>$log->action
));
810 $ldcache[$log->module
][$log->action
] = $ld;
812 if ($ld && is_numeric($log->info
)) {
813 // ugly hack to make sure fullname is shown correctly
814 if (($ld->mtable
== 'user') and ($ld->field
== $DB->sql_concat('firstname', "' '" , 'lastname'))) {
815 $log->info
= fullname($DB->get_record($ld->mtable
, array('id'=>$log->info
)), true);
817 $log->info
= $DB->get_field($ld->mtable
, $ld->field
, array('id'=>$log->info
));
822 $log->info
= format_string($log->info
);
823 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
826 if ($row > EXCELROWS
) {
828 $myxls =& $worksheet[$wsnumber];
829 $row = FIRSTUSEDEXCELROW
;
833 $coursecontext = context_course
::instance($course->id
);
835 $myxls->write_string($row, 0, format_string($courses[$log->course
], true, array('context' => $coursecontext)));
836 $myxls->write_date($row, 1, $log->time
);
837 $myxls->write_string($row, 2, $log->ip
);
838 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
839 $myxls->write_string($row, 3, $fullname);
840 $actionurl = $CFG->wwwroot
. make_log_url($log->module
,$log->url
);
841 $myxls->write_string($row, 4, $log->module
.' '.$log->action
.' ('.$actionurl.')');
842 $myxls->write_string($row, 5, $log->info
);
852 * For a given course, returns an array of course activity objects
853 * Each item in the array contains he following properties:
855 function get_array_of_activities($courseid) {
856 // cm - course module id
857 // mod - name of the module (eg forum)
858 // section - the number of the section (eg week or topic)
859 // name - the name of the instance
860 // visible - is the instance visible or not
861 // groupingid - grouping id
862 // groupmembersonly - is this instance visible to group members only
863 // extra - contains extra string to include in any link
865 if(!empty($CFG->enableavailability
)) {
866 require_once($CFG->libdir
.'/conditionlib.php');
869 $course = $DB->get_record('course', array('id'=>$courseid));
871 if (empty($course)) {
872 throw new moodle_exception('courseidnotfound');
877 $rawmods = get_course_mods($courseid);
878 if (empty($rawmods)) {
879 return $mod; // always return array
882 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
883 foreach ($sections as $section) {
884 if (!empty($section->sequence
)) {
885 $sequence = explode(",", $section->sequence
);
886 foreach ($sequence as $seq) {
887 if (empty($rawmods[$seq])) {
890 $mod[$seq] = new stdClass();
891 $mod[$seq]->id
= $rawmods[$seq]->instance
;
892 $mod[$seq]->cm
= $rawmods[$seq]->id
;
893 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
895 // Oh dear. Inconsistent names left here for backward compatibility.
896 $mod[$seq]->section
= $section->section
;
897 $mod[$seq]->sectionid
= $rawmods[$seq]->section
;
899 $mod[$seq]->module
= $rawmods[$seq]->module
;
900 $mod[$seq]->added
= $rawmods[$seq]->added
;
901 $mod[$seq]->score
= $rawmods[$seq]->score
;
902 $mod[$seq]->idnumber
= $rawmods[$seq]->idnumber
;
903 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
904 $mod[$seq]->visibleold
= $rawmods[$seq]->visibleold
;
905 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
906 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
907 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
908 $mod[$seq]->indent
= $rawmods[$seq]->indent
;
909 $mod[$seq]->completion
= $rawmods[$seq]->completion
;
910 $mod[$seq]->extra
= "";
911 $mod[$seq]->completiongradeitemnumber
=
912 $rawmods[$seq]->completiongradeitemnumber
;
913 $mod[$seq]->completionview
= $rawmods[$seq]->completionview
;
914 $mod[$seq]->completionexpected
= $rawmods[$seq]->completionexpected
;
915 $mod[$seq]->availablefrom
= $rawmods[$seq]->availablefrom
;
916 $mod[$seq]->availableuntil
= $rawmods[$seq]->availableuntil
;
917 $mod[$seq]->showavailability
= $rawmods[$seq]->showavailability
;
918 $mod[$seq]->showdescription
= $rawmods[$seq]->showdescription
;
919 if (!empty($CFG->enableavailability
)) {
920 condition_info
::fill_availability_conditions($rawmods[$seq]);
921 $mod[$seq]->conditionscompletion
= $rawmods[$seq]->conditionscompletion
;
922 $mod[$seq]->conditionsgrade
= $rawmods[$seq]->conditionsgrade
;
923 $mod[$seq]->conditionsfield
= $rawmods[$seq]->conditionsfield
;
926 $modname = $mod[$seq]->mod
;
927 $functionname = $modname."_get_coursemodule_info";
929 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
933 include_once("$CFG->dirroot/mod/$modname/lib.php");
935 if ($hasfunction = function_exists($functionname)) {
936 if ($info = $functionname($rawmods[$seq])) {
937 if (!empty($info->icon
)) {
938 $mod[$seq]->icon
= $info->icon
;
940 if (!empty($info->iconcomponent
)) {
941 $mod[$seq]->iconcomponent
= $info->iconcomponent
;
943 if (!empty($info->name
)) {
944 $mod[$seq]->name
= $info->name
;
946 if ($info instanceof cached_cm_info
) {
947 // When using cached_cm_info you can include three new fields
948 // that aren't available for legacy code
949 if (!empty($info->content
)) {
950 $mod[$seq]->content
= $info->content
;
952 if (!empty($info->extraclasses
)) {
953 $mod[$seq]->extraclasses
= $info->extraclasses
;
955 if (!empty($info->iconurl
)) {
956 $mod[$seq]->iconurl
= $info->iconurl
;
958 if (!empty($info->onclick
)) {
959 $mod[$seq]->onclick
= $info->onclick
;
961 if (!empty($info->customdata
)) {
962 $mod[$seq]->customdata
= $info->customdata
;
965 // When using a stdclass, the (horrible) deprecated ->extra field
966 // is available for BC
967 if (!empty($info->extra
)) {
968 $mod[$seq]->extra
= $info->extra
;
973 // When there is no modname_get_coursemodule_info function,
974 // but showdescriptions is enabled, then we use the 'intro'
975 // and 'introformat' fields in the module table
976 if (!$hasfunction && $rawmods[$seq]->showdescription
) {
977 if ($modvalues = $DB->get_record($rawmods[$seq]->modname
,
978 array('id' => $rawmods[$seq]->instance
), 'name, intro, introformat')) {
979 // Set content from intro and introformat. Filters are disabled
980 // because we filter it with format_text at display time
981 $mod[$seq]->content
= format_module_intro($rawmods[$seq]->modname
,
982 $modvalues, $rawmods[$seq]->id
, false);
984 // To save making another query just below, put name in here
985 $mod[$seq]->name
= $modvalues->name
;
988 if (!isset($mod[$seq]->name
)) {
989 $mod[$seq]->name
= $DB->get_field($rawmods[$seq]->modname
, "name", array("id"=>$rawmods[$seq]->instance
));
992 // Minimise the database size by unsetting default options when they are
993 // 'empty'. This list corresponds to code in the cm_info constructor.
994 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
995 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
996 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
997 'availableuntil', 'conditionscompletion', 'conditionsgrade',
998 'completionview', 'completionexpected', 'score', 'showdescription')
1000 if (property_exists($mod[$seq], $property) &&
1001 empty($mod[$seq]->{$property})) {
1002 unset($mod[$seq]->{$property});
1005 // Special case: this value is usually set to null, but may be 0
1006 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1007 is_null($mod[$seq]->completiongradeitemnumber
)) {
1008 unset($mod[$seq]->completiongradeitemnumber
);
1018 * Returns the localised human-readable names of all used modules
1020 * @param bool $plural if true returns the plural forms of the names
1021 * @return array where key is the module name (component name without 'mod_') and
1022 * the value is the human-readable string. Array sorted alphabetically by value
1024 function get_module_types_names($plural = false) {
1025 static $modnames = null;
1027 if ($modnames === null) {
1028 $modnames = array(0 => array(), 1 => array());
1029 if ($allmods = $DB->get_records("modules")) {
1030 foreach ($allmods as $mod) {
1031 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible
) {
1032 $modnames[0][$mod->name
] = get_string("modulename", "$mod->name");
1033 $modnames[1][$mod->name
] = get_string("modulenameplural", "$mod->name");
1036 collatorlib
::asort($modnames[0]);
1037 collatorlib
::asort($modnames[1]);
1040 return $modnames[(int)$plural];
1044 * Set highlighted section. Only one section can be highlighted at the time.
1046 * @param int $courseid course id
1047 * @param int $marker highlight section with this number, 0 means remove higlightin
1050 function course_set_marker($courseid, $marker) {
1052 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1053 format_base
::reset_course_cache($courseid);
1057 * For a given course section, marks it visible or hidden,
1058 * and does the same for every activity in that section
1060 * @param int $courseid course id
1061 * @param int $sectionnumber The section number to adjust
1062 * @param int $visibility The new visibility
1063 * @return array A list of resources which were hidden in the section
1065 function set_section_visible($courseid, $sectionnumber, $visibility) {
1068 $resourcestotoggle = array();
1069 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1070 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id
));
1071 if (!empty($section->sequence
)) {
1072 $modules = explode(",", $section->sequence
);
1073 foreach ($modules as $moduleid) {
1074 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1076 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1077 set_coursemodule_visible($moduleid, $cm->visibleold
);
1079 // We hide the section, so we hide the module but we store the original state in visibleold.
1080 set_coursemodule_visible($moduleid, 0);
1081 $DB->set_field('course_modules', 'visibleold', $cm->visible
, array('id' => $moduleid));
1086 rebuild_course_cache($courseid, true);
1088 // Determine which modules are visible for AJAX update
1089 if (!empty($modules)) {
1090 list($insql, $params) = $DB->get_in_or_equal($modules);
1091 $select = 'id ' . $insql . ' AND visible = ?';
1092 array_push($params, $visibility);
1094 $select .= ' AND visibleold = 1';
1096 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1099 return $resourcestotoggle;
1103 * Retrieve all metadata for the requested modules
1105 * @param object $course The Course
1106 * @param array $modnames An array containing the list of modules and their
1108 * @param int $sectionreturn The section to return to
1109 * @return array A list of stdClass objects containing metadata about each
1112 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1113 global $CFG, $OUTPUT;
1115 // get_module_metadata will be called once per section on the page and courses may show
1116 // different modules to one another
1117 static $modlist = array();
1118 if (!isset($modlist[$course->id
])) {
1119 $modlist[$course->id
] = array();
1123 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id
, 'sesskey' => sesskey()));
1124 if ($sectionreturn !== null) {
1125 $urlbase->param('sr', $sectionreturn);
1127 foreach($modnames as $modname => $modnamestr) {
1128 if (!course_allowed_module($course, $modname)) {
1131 if (isset($modlist[$course->id
][$modname])) {
1132 // This module is already cached
1133 $return[$modname] = $modlist[$course->id
][$modname];
1137 // Include the module lib
1138 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1139 if (!file_exists($libfile)) {
1142 include_once($libfile);
1144 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1145 $gettypesfunc = $modname.'_get_types';
1146 if (function_exists($gettypesfunc)) {
1147 $types = $gettypesfunc();
1148 if (is_array($types) && count($types) > 0) {
1149 $group = new stdClass();
1150 $group->name
= $modname;
1151 $group->icon
= $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1152 foreach($types as $type) {
1153 if ($type->typestr
=== '--') {
1156 if (strpos($type->typestr
, '--') === 0) {
1157 $group->title
= str_replace('--', '', $type->typestr
);
1160 // Set the Sub Type metadata
1161 $subtype = new stdClass();
1162 $subtype->title
= $type->typestr
;
1163 $subtype->type
= str_replace('&', '&', $type->type
);
1164 $subtype->name
= preg_replace('/.*type=/', '', $subtype->type
);
1165 $subtype->archetype
= $type->modclass
;
1167 // The group archetype should match the subtype archetypes and all subtypes
1168 // should have the same archetype
1169 $group->archetype
= $subtype->archetype
;
1171 if (get_string_manager()->string_exists('help' . $subtype->name
, $modname)) {
1172 $subtype->help
= get_string('help' . $subtype->name
, $modname);
1174 $subtype->link
= new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name
));
1175 $group->types
[] = $subtype;
1177 $modlist[$course->id
][$modname] = $group;
1180 $module = new stdClass();
1181 $module->title
= $modnamestr;
1182 $module->name
= $modname;
1183 $module->link
= new moodle_url($urlbase, array('add' => $modname));
1184 $module->icon
= $OUTPUT->pix_icon('icon', '', $module->name
, array('class' => 'icon'));
1185 $sm = get_string_manager();
1186 if ($sm->string_exists('modulename_help', $modname)) {
1187 $module->help
= get_string('modulename_help', $modname);
1188 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1189 $link = get_string('modulename_link', $modname);
1190 $linktext = get_string('morehelp');
1191 $module->help
.= html_writer
::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1194 $module->archetype
= plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1195 $modlist[$course->id
][$modname] = $module;
1197 if (isset($modlist[$course->id
][$modname])) {
1198 $return[$modname] = $modlist[$course->id
][$modname];
1200 debugging("Invalid module metadata configuration for {$modname}");
1208 * Return the course category context for the category with id $categoryid, except
1209 * that if $categoryid is 0, return the system context.
1211 * @param integer $categoryid a category id or 0.
1212 * @return object the corresponding context
1214 function get_category_or_system_context($categoryid) {
1216 return context_coursecat
::instance($categoryid, IGNORE_MISSING
);
1218 return context_system
::instance();
1223 * Gets the child categories of a given courses category. Uses a static cache
1224 * to make repeat calls efficient.
1226 * @param int $parentid the id of a course category.
1227 * @return array all the child course categories.
1229 function get_child_categories($parentid) {
1230 static $allcategories = null;
1232 // only fill in this variable the first time
1233 if (null == $allcategories) {
1234 $allcategories = array();
1236 $categories = get_categories();
1237 foreach ($categories as $category) {
1238 if (empty($allcategories[$category->parent
])) {
1239 $allcategories[$category->parent
] = array();
1241 $allcategories[$category->parent
][] = $category;
1245 if (empty($allcategories[$parentid])) {
1248 return $allcategories[$parentid];
1253 * This function recursively travels the categories, building up a nice list
1254 * for display. It also makes an array that list all the parents for each
1257 * For example, if you have a tree of categories like:
1258 * Miscellaneous (id = 1)
1259 * Subcategory (id = 2)
1260 * Sub-subcategory (id = 4)
1261 * Other category (id = 3)
1262 * Then after calling this function you will have
1263 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1264 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1265 * 3 => 'Other category');
1266 * $parents = array(2 => array(1), 4 => array(1, 2));
1268 * If you specify $requiredcapability, then only categories where the current
1269 * user has that capability will be added to $list, although all categories
1270 * will still be added to $parents, and if you only have $requiredcapability
1271 * in a child category, not the parent, then the child catgegory will still be
1274 * If you specify the option $excluded, then that category, and all its children,
1275 * are omitted from the tree. This is useful when you are doing something like
1276 * moving categories, where you do not want to allow people to move a category
1277 * to be the child of itself.
1279 * @param array $list For output, accumulates an array categoryid => full category path name
1280 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1281 * @param string/array $requiredcapability if given, only categories where the current
1282 * user has this capability will be added to $list. Can also be an array of capabilities,
1283 * in which case they are all required.
1284 * @param integer $excludeid Omit this category and its children from the lists built.
1285 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1286 * @param string $path For internal use, as part of recursive calls.
1288 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1289 $excludeid = 0, $category = NULL, $path = "") {
1291 // initialize the arrays if needed
1292 if (!is_array($list)) {
1295 if (!is_array($parents)) {
1299 if (empty($category)) {
1300 // Start at the top level.
1301 $category = new stdClass
;
1304 // This is the excluded category, don't include it.
1305 if ($excludeid > 0 && $excludeid == $category->id
) {
1309 $context = context_coursecat
::instance($category->id
);
1310 $categoryname = format_string($category->name
, true, array('context' => $context));
1314 $path = $path.' / '.$categoryname;
1316 $path = $categoryname;
1319 // Add this category to $list, if the permissions check out.
1320 if (empty($requiredcapability)) {
1321 $list[$category->id
] = $path;
1324 $requiredcapability = (array)$requiredcapability;
1325 if (has_all_capabilities($requiredcapability, $context)) {
1326 $list[$category->id
] = $path;
1331 // Add all the children recursively, while updating the parents array.
1332 if ($categories = get_child_categories($category->id
)) {
1333 foreach ($categories as $cat) {
1334 if (!empty($category->id
)) {
1335 if (isset($parents[$category->id
])) {
1336 $parents[$cat->id
] = $parents[$category->id
];
1338 $parents[$cat->id
][] = $category->id
;
1340 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
1346 * This function generates a structured array of courses and categories.
1348 * The depth of categories is limited by $CFG->maxcategorydepth however there
1349 * is no limit on the number of courses!
1351 * Suitable for use with the course renderers course_category_tree method:
1352 * $renderer = $PAGE->get_renderer('core','course');
1353 * echo $renderer->course_category_tree(get_course_category_tree());
1355 * @global moodle_database $DB
1359 function get_course_category_tree($id = 0, $depth = 0) {
1361 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system
::instance());
1362 $categories = get_child_categories($id);
1363 $categoryids = array();
1364 foreach ($categories as $key => &$category) {
1365 if (!$category->visible
&& !$viewhiddencats) {
1366 unset($categories[$key]);
1369 $categoryids[$category->id
] = $category;
1370 if (empty($CFG->maxcategorydepth
) ||
$depth <= $CFG->maxcategorydepth
) {
1371 list($category->categories
, $subcategories) = get_course_category_tree($category->id
, $depth+
1);
1372 foreach ($subcategories as $subid=>$subcat) {
1373 $categoryids[$subid] = $subcat;
1375 $category->courses
= array();
1380 // This is a recursive call so return the required array
1381 return array($categories, $categoryids);
1384 if (empty($categoryids)) {
1385 // No categories available (probably all hidden).
1389 // The depth is 0 this function has just been called so we can finish it off
1391 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1392 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
1394 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
1398 WHERE c.category $catsql ORDER BY c.sortorder ASC";
1399 if ($courses = $DB->get_records_sql($sql, $catparams)) {
1400 // loop throught them
1401 foreach ($courses as $course) {
1402 if ($course->id
== SITEID
) {
1405 context_instance_preload($course);
1406 if (!empty($course->visible
) ||
has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1407 $categoryids[$course->category
]->courses
[$course->id
] = $course;
1415 * Recursive function to print out all the categories in a nice format
1416 * with or without courses included
1418 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1421 // maxcategorydepth == 0 meant no limit
1422 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
1426 if (!$displaylist) {
1427 make_categories_list($displaylist, $parentslist);
1430 if (!$categorycourses) {
1432 $categorycourses = get_category_courses_array($category->id
);
1434 $categorycourses = get_category_courses_array();
1439 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', context_system
::instance())) {
1440 print_category_info($category, $depth, $showcourses, $categorycourses[$category->id
]);
1442 return; // Don't bother printing children of invisible categories
1446 $category = new stdClass();
1447 $category->id
= "0";
1450 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
1451 $countcats = count($categories);
1455 foreach ($categories as $cat) {
1457 if ($count == $countcats) {
1460 $up = $first ?
false : true;
1461 $down = $last ?
false : true;
1464 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses, $categorycourses);
1470 * Gets an array whose keys are category ids and whose values are arrays of courses in the corresponding category.
1472 * @param int $categoryid
1475 function get_category_courses_array($categoryid = 0) {
1476 $tree = get_course_category_tree($categoryid);
1477 $flattened = array();
1478 foreach ($tree as $category) {
1479 get_category_courses_array_recursively($flattened, $category);
1485 * Recursive function to help flatten the course category tree.
1487 * Do not call this function directly, instead calll its parent function {@link get_category_courses_array}
1489 * @param array &$flattened An array passed by reference in which to store courses for each category.
1490 * @param stdClass $category The category to get courses for.
1492 function get_category_courses_array_recursively(array &$flattened, $category) {
1493 $flattened[$category->id
] = $category->courses
;
1494 foreach ($category->categories
as $childcategory) {
1495 get_category_courses_array_recursively($flattened, $childcategory);
1500 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
1502 function make_categories_options() {
1503 make_categories_list($cats,$parents);
1504 foreach ($cats as $key => $value) {
1505 if (array_key_exists($key,$parents)) {
1506 if ($indent = count($parents[$key])) {
1507 for ($i = 0; $i < $indent; $i++
) {
1508 $cats[$key] = ' '.$cats[$key];
1517 * Prints the category information.
1519 * This function is only used by print_whole_category_list() above
1521 * @param stdClass $category
1522 * @param int $depth The depth of the category.
1523 * @param bool $showcourses If set to true course information will also be printed.
1524 * @param array|null $courses An array of courses belonging to the category, or null if you don't have it yet.
1526 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1527 global $CFG, $DB, $OUTPUT;
1529 $strsummary = get_string('summary');
1532 if (!$category->visible
) {
1533 $catlinkcss = array('class'=>'dimmed');
1535 static $coursecount = null;
1536 if (null === $coursecount) {
1537 // only need to check this once
1538 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT
;
1541 if ($showcourses and $coursecount) {
1542 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
1544 $catimage = " ";
1547 if (is_null($courses)) {
1548 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
1550 $context = context_coursecat
::instance($category->id
);
1551 $fullname = format_string($category->name
, true, array('context' => $context));
1553 if ($showcourses and $coursecount) {
1554 echo '<div class="categorylist clearfix">';
1556 $cat .= html_writer
::tag('div', $catimage, array('class'=>'image'));
1557 $catlink = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
1558 $cat .= html_writer
::tag('div', $catlink, array('class'=>'name'));
1562 for ($i=0; $i< $depth; $i++
) {
1563 $html = html_writer
::tag('div', $html . $cat, array('class'=>'indentation'));
1569 echo html_writer
::tag('div', $html, array('class'=>'category'));
1570 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
1572 // does the depth exceed maxcategorydepth
1573 // maxcategorydepth == 0 or unset meant no limit
1574 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
1575 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
1576 foreach ($courses as $course) {
1578 if (!$course->visible
) {
1579 $linkcss = array('class'=>'dimmed');
1582 $coursename = get_course_display_name_for_list($course);
1583 $courselink = html_writer
::link(new moodle_url('/course/view.php', array('id'=>$course->id
)), format_string($coursename), $linkcss);
1587 if ($icons = enrol_get_course_info_icons($course)) {
1588 foreach ($icons as $pix_icon) {
1589 $courseicon = $OUTPUT->render($pix_icon);
1593 $coursecontent = html_writer
::tag('div', $courseicon.$courselink, array('class'=>'name'));
1595 if ($course->summary
) {
1596 $link = new moodle_url('/course/info.php?id='.$course->id
);
1597 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
1598 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
1599 array('title'=>$strsummary));
1601 $coursecontent .= html_writer
::tag('div', $actionlink, array('class'=>'info'));
1605 for ($i=0; $i <= $depth; $i++
) {
1606 $html = html_writer
::tag('div', $html . $coursecontent , array('class'=>'indentation'));
1607 $coursecontent = '';
1609 echo html_writer
::tag('div', $html, array('class'=>'course clearfloat'));
1614 echo '<div class="categorylist">';
1616 $cat = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
1617 if (count($courses) > 0) {
1618 $cat .= html_writer
::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
1622 for ($i=0; $i< $depth; $i++
) {
1623 $html = html_writer
::tag('div', $html .$cat, array('class'=>'indentation'));
1630 echo html_writer
::tag('div', $html, array('class'=>'category'));
1631 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
1637 * Print the buttons relating to course requests.
1639 * @param object $systemcontext the system context.
1641 function print_course_request_buttons($systemcontext) {
1642 global $CFG, $DB, $OUTPUT;
1643 if (empty($CFG->enablecourserequests
)) {
1646 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
1647 /// Print a button to request a new course
1648 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
1650 /// Print a button to manage pending requests
1651 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
1652 $disabled = !$DB->record_exists('course_request', array());
1653 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
1658 * Does the user have permission to edit things in this category?
1660 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1661 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1663 function can_edit_in_category($categoryid = 0) {
1664 $context = get_category_or_system_context($categoryid);
1665 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1669 * Print courses in category. If category is 0 then all courses are printed.
1670 * @param int|stdClass $category category object or id.
1671 * @return bool true if courses found and printed, else false.
1673 function print_courses($category) {
1674 global $CFG, $OUTPUT;
1676 if (!is_object($category) && $category==0) {
1677 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1678 if (is_array($categories) && count($categories) == 1) {
1679 $category = array_shift($categories);
1680 $courses = get_courses_wmanagers($category->id
,
1682 array('summary','summaryformat'));
1684 $courses = get_courses_wmanagers('all',
1686 array('summary','summaryformat'));
1690 $courses = get_courses_wmanagers($category->id
,
1692 array('summary','summaryformat'));
1696 echo html_writer
::start_tag('ul', array('class'=>'unlist'));
1697 foreach ($courses as $course) {
1698 $coursecontext = context_course
::instance($course->id
);
1699 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
1700 echo html_writer
::start_tag('li');
1701 print_course($course);
1702 echo html_writer
::end_tag('li');
1705 echo html_writer
::end_tag('ul');
1707 echo $OUTPUT->heading(get_string("nocoursesyet"));
1708 $context = context_system
::instance();
1709 if (has_capability('moodle/course:create', $context)) {
1711 if (!empty($category->id
)) {
1712 $options['category'] = $category->id
;
1714 $options['category'] = $CFG->defaultrequestcategory
;
1716 echo html_writer
::start_tag('div', array('class'=>'addcoursebutton'));
1717 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
1718 echo html_writer
::end_tag('div');
1726 * Print a description of a course, suitable for browsing in a list.
1728 * @param object $course the course object.
1729 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
1731 function print_course($course, $highlightterms = '') {
1732 global $CFG, $USER, $DB, $OUTPUT;
1734 $context = context_course
::instance($course->id
);
1736 // Rewrite file URLs so that they are correct
1737 $course->summary
= file_rewrite_pluginfile_urls($course->summary
, 'pluginfile.php', $context->id
, 'course', 'summary', NULL);
1739 echo html_writer
::start_tag('div', array('class'=>'coursebox clearfix'));
1740 echo html_writer
::start_tag('div', array('class'=>'info'));
1741 echo html_writer
::start_tag('h3', array('class'=>'name'));
1743 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id
));
1745 $coursename = get_course_display_name_for_list($course);
1746 $linktext = highlight($highlightterms, format_string($coursename));
1747 $linkparams = array('title'=>get_string('entercourse'));
1748 if (empty($course->visible
)) {
1749 $linkparams['class'] = 'dimmed';
1751 echo html_writer
::link($linkhref, $linktext, $linkparams);
1752 echo html_writer
::end_tag('h3');
1754 /// first find all roles that are supposed to be displayed
1755 if (!empty($CFG->coursecontact
)) {
1756 $managerroles = explode(',', $CFG->coursecontact
);
1759 if (!isset($course->managers
)) {
1760 list($sort, $sortparams) = users_order_by_sql('u');
1761 $rusers = get_role_users($managerroles, $context, true,
1762 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
1763 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
1764 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
1766 // use the managers array if we have it for perf reasosn
1767 // populate the datastructure like output of get_role_users();
1768 foreach ($course->managers
as $manager) {
1769 $user = clone($manager->user
);
1770 $user->roleid
= $manager->roleid
;
1771 $user->rolename
= $manager->rolename
;
1772 $user->roleshortname
= $manager->roleshortname
;
1773 $user->rolecoursealias
= $manager->rolecoursealias
;
1774 $rusers[$user->id
] = $user;
1778 $namesarray = array();
1779 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1780 foreach ($rusers as $ra) {
1781 if (isset($namesarray[$ra->id
])) {
1782 // only display a user once with the higest sortorder role
1786 $role = new stdClass();
1787 $role->id
= $ra->roleid
;
1788 $role->name
= $ra->rolename
;
1789 $role->shortname
= $ra->roleshortname
;
1790 $role->coursealias
= $ra->rolecoursealias
;
1791 $rolename = role_get_name($role, $context, ROLENAME_ALIAS
);
1793 $fullname = fullname($ra, $canviewfullnames);
1794 $namesarray[$ra->id
] = $rolename.': '.
1795 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$ra->id
, 'course'=>SITEID
)), $fullname);
1798 if (!empty($namesarray)) {
1799 echo html_writer
::start_tag('ul', array('class'=>'teachers'));
1800 foreach ($namesarray as $name) {
1801 echo html_writer
::tag('li', $name);
1803 echo html_writer
::end_tag('ul');
1806 echo html_writer
::end_tag('div'); // End of info div
1808 echo html_writer
::start_tag('div', array('class'=>'summary'));
1809 $options = new stdClass();
1810 $options->noclean
= true;
1811 $options->para
= false;
1812 $options->overflowdiv
= true;
1813 if (!isset($course->summaryformat
)) {
1814 $course->summaryformat
= FORMAT_MOODLE
;
1816 echo highlight($highlightterms, format_text($course->summary
, $course->summaryformat
, $options, $course->id
));
1817 if ($icons = enrol_get_course_info_icons($course)) {
1818 echo html_writer
::start_tag('div', array('class'=>'enrolmenticons'));
1819 foreach ($icons as $icon) {
1820 $icon->attributes
["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
1821 echo $OUTPUT->render($icon);
1823 echo html_writer
::end_tag('div'); // End of enrolmenticons div
1825 echo html_writer
::end_tag('div'); // End of summary div
1826 echo html_writer
::end_tag('div'); // End of coursebox div
1830 * Prints custom user information on the home page.
1831 * Over time this can include all sorts of information
1833 function print_my_moodle() {
1834 global $USER, $CFG, $DB, $OUTPUT;
1836 if (!isloggedin() or isguestuser()) {
1837 print_error('nopermissions', '', '', 'See My Moodle');
1840 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
1842 $rcourses = array();
1843 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
1844 $rcourses = get_my_remotecourses($USER->id
);
1845 $rhosts = get_my_remotehosts();
1848 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
1850 if (!empty($courses)) {
1851 echo '<ul class="unlist">';
1852 foreach ($courses as $course) {
1853 if ($course->id
== SITEID
) {
1857 print_course($course);
1864 if (!empty($rcourses)) {
1865 // at the IDP, we know of all the remote courses
1866 foreach ($rcourses as $course) {
1867 print_remote_course($course, "100%");
1869 } elseif (!empty($rhosts)) {
1870 // non-IDP, we know of all the remote servers, but not courses
1871 foreach ($rhosts as $host) {
1872 print_remote_host($host, "100%");
1878 if ($DB->count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
1879 echo "<table width=\"100%\"><tr><td align=\"center\">";
1880 print_course_search("", false, "short");
1881 echo "</td><td align=\"center\">";
1882 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
1883 echo "</td></tr></table>\n";
1887 if ($DB->count_records("course_categories") > 1) {
1888 echo $OUTPUT->box_start("categorybox");
1889 print_whole_category_list();
1890 echo $OUTPUT->box_end();
1898 function print_course_search($value="", $return=false, $format="plain") {
1904 $id = 'coursesearch';
1910 $strsearchcourses= get_string("searchcourses");
1912 if ($format == 'plain') {
1913 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1914 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1915 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1916 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
1917 $output .= '<input type="submit" value="'.get_string('go').'" />';
1918 $output .= '</fieldset></form>';
1919 } else if ($format == 'short') {
1920 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1921 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1922 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
1923 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" value="'.s($value).'" />';
1924 $output .= '<input type="submit" value="'.get_string('go').'" />';
1925 $output .= '</fieldset></form>';
1926 } else if ($format == 'navbar') {
1927 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1928 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1929 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
1930 $output .= '<input type="text" id="navsearchbox" size="20" name="search" value="'.s($value).'" />';
1931 $output .= '<input type="submit" value="'.get_string('go').'" />';
1932 $output .= '</fieldset></form>';
1941 function print_remote_course($course, $width="100%") {
1946 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
1948 echo '<div class="coursebox remotecoursebox clearfix">';
1949 echo '<div class="info">';
1950 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1951 $linkcss.' href="'.$url.'">'
1952 . format_string($course->fullname
) .'</a><br />'
1953 . format_string($course->hostname
) . ' : '
1954 . format_string($course->cat_name
) . ' : '
1955 . format_string($course->shortname
). '</div>';
1956 echo '</div><div class="summary">';
1957 $options = new stdClass();
1958 $options->noclean
= true;
1959 $options->para
= false;
1960 $options->overflowdiv
= true;
1961 echo format_text($course->summary
, $course->summaryformat
, $options);
1966 function print_remote_host($host, $width="100%") {
1971 echo '<div class="coursebox clearfix">';
1972 echo '<div class="info">';
1973 echo '<div class="name">';
1974 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
1975 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
1976 . s($host['name']).'</a> - ';
1977 echo $host['count'] . ' ' . get_string('courses');
1984 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1986 function add_course_module($mod) {
1989 $mod->added
= time();
1992 $cmid = $DB->insert_record("course_modules", $mod);
1993 rebuild_course_cache($mod->course
, true);
1998 * Creates missing course section(s) and rebuilds course cache
2000 * @param int|stdClass $courseorid course id or course object
2001 * @param int|array $sections list of relative section numbers to create
2002 * @return bool if there were any sections created
2004 function course_create_sections_if_missing($courseorid, $sections) {
2006 if (!is_array($sections)) {
2007 $sections = array($sections);
2009 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2010 if (is_object($courseorid)) {
2011 $courseorid = $courseorid->id
;
2013 $coursechanged = false;
2014 foreach ($sections as $sectionnum) {
2015 if (!in_array($sectionnum, $existing)) {
2016 $cw = new stdClass();
2017 $cw->course
= $courseorid;
2018 $cw->section
= $sectionnum;
2020 $cw->summaryformat
= FORMAT_HTML
;
2022 $id = $DB->insert_record("course_sections", $cw);
2023 $coursechanged = true;
2026 if ($coursechanged) {
2027 rebuild_course_cache($courseorid, true);
2029 return $coursechanged;
2033 * Adds an existing module to the section
2035 * Updates both tables {course_sections} and {course_modules}
2037 * @param int|stdClass $courseorid course id or course object
2038 * @param int $cmid id of the module already existing in course_modules table
2039 * @param int $sectionnum relative number of the section (field course_sections.section)
2040 * If section does not exist it will be created
2041 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2042 * before which the module needs to be included. Null for inserting in the
2043 * end of the section
2044 * @return int The course_sections ID where the module is inserted
2046 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2047 global $DB, $COURSE;
2048 if (is_object($beforemod)) {
2049 $beforemod = $beforemod->id
;
2051 if (is_object($courseorid)) {
2052 $courseid = $courseorid->id
;
2054 $courseid = $courseorid;
2056 course_create_sections_if_missing($courseorid, $sectionnum);
2057 // Do not try to use modinfo here, there is no guarantee it is valid!
2058 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST
);
2059 $modarray = explode(",", trim($section->sequence
));
2060 if (empty($section->sequence
)) {
2061 $newsequence = "$cmid";
2062 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2063 $insertarray = array($cmid, $beforemod);
2064 array_splice($modarray, $key[0], 1, $insertarray);
2065 $newsequence = implode(",", $modarray);
2067 $newsequence = "$section->sequence,$cmid";
2069 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id
));
2070 $DB->set_field('course_modules', 'section', $section->id
, array('id' => $cmid));
2071 if (is_object($courseorid)) {
2072 rebuild_course_cache($courseorid->id
, true);
2074 rebuild_course_cache($courseorid, true);
2076 return $section->id
; // Return course_sections ID that was used.
2079 function set_coursemodule_groupmode($id, $groupmode) {
2081 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST
);
2082 if ($cm->groupmode
!= $groupmode) {
2083 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id
));
2084 rebuild_course_cache($cm->course
, true);
2086 return ($cm->groupmode
!= $groupmode);
2089 function set_coursemodule_idnumber($id, $idnumber) {
2091 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST
);
2092 if ($cm->idnumber
!= $idnumber) {
2093 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id
));
2094 rebuild_course_cache($cm->course
, true);
2096 return ($cm->idnumber
!= $idnumber);
2100 * Set the visibility of a module and inherent properties.
2102 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2103 * has been moved to {@link set_section_visible()} which was the only place from which
2104 * the parameter was used.
2106 * @param int $id of the module
2107 * @param int $visible state of the module
2108 * @return bool false when the module was not found, true otherwise
2110 function set_coursemodule_visible($id, $visible) {
2112 require_once($CFG->libdir
.'/gradelib.php');
2114 // Trigger developer's attention when using the previously removed argument.
2115 if (func_num_args() > 2) {
2116 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2117 has been removed.', DEBUG_DEVELOPER
);
2120 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2124 // Create events and propagate visibility to associated grade items if the value has changed.
2125 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
2126 if ($cm->visible
== $visible) {
2130 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
2133 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2134 foreach($events as $event) {
2143 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2144 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
2146 foreach ($grade_items as $grade_item) {
2147 $grade_item->set_hidden(!$visible);
2151 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2152 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2153 $cminfo = new stdClass();
2155 $cminfo->visible
= $visible;
2156 $cminfo->visibleold
= $visible;
2157 $DB->update_record('course_modules', $cminfo);
2159 rebuild_course_cache($cm->course
, true);
2164 * This function will handles the whole deletion process of a module. This includes calling
2165 * the modules delete_instance function, deleting files, events, grades, conditional data,
2166 * the data in the course_module and course_sections table and adding a module deletion
2169 * @param int $cmid the course module id
2172 function course_delete_module($cmid) {
2173 global $CFG, $DB, $USER;
2175 require_once($CFG->libdir
.'/gradelib.php');
2176 require_once($CFG->dirroot
.'/blog/lib.php');
2178 // Get the course module.
2179 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
2183 // Get the module context.
2184 $modcontext = context_module
::instance($cm->id
);
2186 // Get the course module name.
2187 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
2189 // Get the file location of the delete_instance function for this module.
2190 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
2192 // Include the file required to call the delete_instance function for this module.
2193 if (file_exists($modlib)) {
2194 require_once($modlib);
2196 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
2197 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
2200 $deleteinstancefunction = $modulename . '_delete_instance';
2202 // Ensure the delete_instance function exists for this module.
2203 if (!function_exists($deleteinstancefunction)) {
2204 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
2205 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
2208 // Call the delete_instance function, if it returns false throw an exception.
2209 if (!$deleteinstancefunction($cm->instance
)) {
2210 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
2211 "Cannot delete the module $modulename (instance).");
2214 // Remove all module files in case modules forget to do that.
2215 $fs = get_file_storage();
2216 $fs->delete_area_files($modcontext->id
);
2218 // Delete events from calendar.
2219 if ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename))) {
2220 foreach($events as $event) {
2221 delete_event($event->id
);
2225 // Delete grade items, outcome items and grades attached to modules.
2226 if ($grade_items = grade_item
::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
2227 'iteminstance' => $cm->instance
, 'courseid' => $cm->course
))) {
2228 foreach ($grade_items as $grade_item) {
2229 $grade_item->delete('moddelete');
2233 // Delete completion and availability data; it is better to do this even if the
2234 // features are not turned on, in case they were turned on previously (these will be
2235 // very quick on an empty table).
2236 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
2237 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
2238 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id
));
2239 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
2240 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
2242 // Delete the context.
2243 delete_context(CONTEXT_MODULE
, $cm->id
);
2245 // Delete the module from the course_modules table.
2246 $DB->delete_records('course_modules', array('id' => $cm->id
));
2248 // Delete module from that section.
2249 if (!delete_mod_from_section($cm->id
, $cm->section
)) {
2250 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
2251 "Cannot delete the module $modulename (instance) from section.");
2254 // Trigger a mod_deleted event with information about this module.
2255 $eventdata = new stdClass();
2256 $eventdata->modulename
= $modulename;
2257 $eventdata->cmid
= $cm->id
;
2258 $eventdata->courseid
= $cm->course
;
2259 $eventdata->userid
= $USER->id
;
2260 events_trigger('mod_deleted', $eventdata);
2262 add_to_log($cm->course
, 'course', "delete mod",
2263 "view.php?id=$cm->course",
2264 "$modulename $cm->instance", $cm->id
);
2266 rebuild_course_cache($cm->course
, true);
2269 function delete_mod_from_section($modid, $sectionid) {
2272 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2274 $modarray = explode(",", $section->sequence
);
2276 if ($key = array_keys ($modarray, $modid)) {
2277 array_splice($modarray, $key[0], 1);
2278 $newsequence = implode(",", $modarray);
2279 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2280 rebuild_course_cache($section->course
, true);
2291 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2293 * @param object $course course object
2294 * @param int $section Section number (not id!!!)
2295 * @param int $move (-1 or 1)
2296 * @return boolean true if section moved successfully
2297 * @todo MDL-33379 remove this function in 2.5
2299 function move_section($course, $section, $move) {
2300 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER
);
2302 /// Moves a whole course section up and down within the course
2309 $sectiondest = $section +
$move;
2311 // compartibility with course formats using field 'numsections'
2312 $courseformatoptions = course_get_format($course)->get_format_options();
2313 if (array_key_exists('numsections', $courseformatoptions) &&
2314 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2318 $retval = move_section_to($course, $section, $sectiondest);
2323 * Moves a section within a course, from a position to another.
2324 * Be very careful: $section and $destination refer to section number,
2327 * @param object $course
2328 * @param int $section Section number (not id!!!)
2329 * @param int $destination
2330 * @return boolean Result
2332 function move_section_to($course, $section, $destination) {
2333 /// Moves a whole course section up and down within the course
2336 if (!$destination && $destination != 0) {
2340 // compartibility with course formats using field 'numsections'
2341 $courseformatoptions = course_get_format($course)->get_format_options();
2342 if ((array_key_exists('numsections', $courseformatoptions) &&
2343 ($destination > $courseformatoptions['numsections'])) ||
($destination < 1)) {
2347 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2348 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
2349 'section ASC, id ASC', 'id, section')) {
2353 $movedsections = reorder_sections($sections, $section, $destination);
2355 // Update all sections. Do this in 2 steps to avoid breaking database
2356 // uniqueness constraint
2357 $transaction = $DB->start_delegated_transaction();
2358 foreach ($movedsections as $id => $position) {
2359 if ($sections[$id] !== $position) {
2360 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2363 foreach ($movedsections as $id => $position) {
2364 if ($sections[$id] !== $position) {
2365 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2369 // If we move the highlighted section itself, then just highlight the destination.
2370 // Adjust the higlighted section location if we move something over it either direction.
2371 if ($section == $course->marker
) {
2372 course_set_marker($course->id
, $destination);
2373 } elseif ($section > $course->marker
&& $course->marker
>= $destination) {
2374 course_set_marker($course->id
, $course->marker+
1);
2375 } elseif ($section < $course->marker
&& $course->marker
<= $destination) {
2376 course_set_marker($course->id
, $course->marker
-1);
2379 $transaction->allow_commit();
2380 rebuild_course_cache($course->id
, true);
2385 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2386 * an original position number and a target position number, rebuilds the array so that the
2387 * move is made without any duplication of section positions.
2388 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2389 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2391 * @param array $sections
2392 * @param int $origin_position
2393 * @param int $target_position
2396 function reorder_sections($sections, $origin_position, $target_position) {
2397 if (!is_array($sections)) {
2401 // We can't move section position 0
2402 if ($origin_position < 1) {
2403 echo "We can't move section position 0";
2407 // Locate origin section in sections array
2408 if (!$origin_key = array_search($origin_position, $sections)) {
2409 echo "searched position not in sections array";
2410 return false; // searched position not in sections array
2413 // Extract origin section
2414 $origin_section = $sections[$origin_key];
2415 unset($sections[$origin_key]);
2417 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2419 $append_array = array();
2420 foreach ($sections as $id => $position) {
2422 $append_array[$id] = $position;
2423 unset($sections[$id]);
2425 if ($position == $target_position) {
2426 if ($target_position < $origin_position) {
2427 $append_array[$id] = $position;
2428 unset($sections[$id]);
2434 // Append moved section
2435 $sections[$origin_key] = $origin_section;
2437 // Append rest of array (if applicable)
2438 if (!empty($append_array)) {
2439 foreach ($append_array as $id => $position) {
2440 $sections[$id] = $position;
2444 // Renumber positions
2446 foreach ($sections as $id => $p) {
2447 $sections[$id] = $position;
2456 * Move the module object $mod to the specified $section
2457 * If $beforemod exists then that is the module
2458 * before which $modid should be inserted
2459 * All parameters are objects
2461 function moveto_module($mod, $section, $beforemod=NULL) {
2462 global $OUTPUT, $DB;
2464 /// Remove original module from original section
2465 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2466 echo $OUTPUT->notification("Could not delete module from existing section");
2469 // if moving to a hidden section then hide module
2470 if (!$section->visible
&& $mod->visible
) {
2471 // Set this in the object because it is sent as a response to ajax calls.
2473 set_coursemodule_visible($mod->id
, 0);
2474 // Set visibleold to 1 so module will be visible when section is made visible.
2475 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id
));
2477 if ($section->visible
&& !$mod->visible
) {
2478 set_coursemodule_visible($mod->id
, $mod->visibleold
);
2479 // Set this in the object because it is sent as a response to ajax calls.
2480 $mod->visible
= $mod->visibleold
;
2483 /// Add the module into the new section
2484 course_add_cm_to_section($section->course
, $mod->id
, $section->section
, $beforemod);
2489 * Returns the list of all editing actions that current user can perform on the module
2491 * @param cm_info $mod The module to produce editing buttons for
2492 * @param int $indent The current indenting (default -1 means no move left-right actions)
2493 * @param int $sr The section to link back to (used for creating the links)
2494 * @return array array of action_link or pix_icon objects
2496 function course_get_cm_edit_actions(cm_info
$mod, $indent = -1, $sr = null) {
2497 global $COURSE, $SITE;
2501 $coursecontext = context_course
::instance($mod->course
);
2502 $modcontext = context_module
::instance($mod->id
);
2504 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
2505 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
2507 // no permission to edit anything
2508 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
2512 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2515 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
2516 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
2517 $str->assign
= get_string('assignroles', 'role');
2518 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
2519 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
2520 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
2521 $str->forcedgroupsnone
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
2522 $str->forcedgroupsseparate
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
2523 $str->forcedgroupsvisible
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
2526 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2529 $baseurl->param('sr', $sr);
2534 if ($mod->has_view() && $hasmanageactivities &&
2535 (($mod->course
== $COURSE->id
&& course_ajax_enabled($COURSE)) ||
2536 ($mod->course
== SITEID
&& course_ajax_enabled($SITE)))) {
2537 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2538 $actions['title'] = new action_link(
2539 new moodle_url($baseurl, array('update' => $mod->id
)),
2540 new pix_icon('t/editstring', $str->edittitle
, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2542 array('class' => 'editing_title', 'title' => $str->edittitle
)
2547 if ($hasmanageactivities) {
2548 if (right_to_left()) { // Exchange arrows on RTL
2549 $rightarrow = 't/left';
2550 $leftarrow = 't/right';
2552 $rightarrow = 't/right';
2553 $leftarrow = 't/left';
2557 $actions['moveleft'] = new action_link(
2558 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '-1')),
2559 new pix_icon($leftarrow, $str->moveleft
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2561 array('class' => 'editing_moveleft', 'title' => $str->moveleft
)
2565 $actions['moveright'] = new action_link(
2566 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '1')),
2567 new pix_icon($rightarrow, $str->moveright
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2569 array('class' => 'editing_moveright', 'title' => $str->moveright
)
2575 if ($hasmanageactivities) {
2576 $actions['move'] = new action_link(
2577 new moodle_url($baseurl, array('copy' => $mod->id
)),
2578 new pix_icon('t/move', $str->move
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2580 array('class' => 'editing_move', 'title' => $str->move
)
2585 if ($hasmanageactivities) {
2586 $actions['update'] = new action_link(
2587 new moodle_url($baseurl, array('update' => $mod->id
)),
2588 new pix_icon('t/edit', $str->update
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2590 array('class' => 'editing_update', 'title' => $str->update
)
2594 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2595 // note that restoring on front page is never allowed
2596 if ($mod->course
!= SITEID
&& has_all_capabilities($dupecaps, $coursecontext) &&
2597 plugin_supports('mod', $mod->modname
, FEATURE_BACKUP_MOODLE2
)) {
2598 $actions['duplicate'] = new action_link(
2599 new moodle_url($baseurl, array('duplicate' => $mod->id
)),
2600 new pix_icon('t/copy', $str->duplicate
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2602 array('class' => 'editing_duplicate', 'title' => $str->duplicate
)
2607 if ($hasmanageactivities) {
2608 $actions['delete'] = new action_link(
2609 new moodle_url($baseurl, array('delete' => $mod->id
)),
2610 new pix_icon('t/delete', $str->delete
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2612 array('class' => 'editing_delete', 'title' => $str->delete
)
2617 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2618 if ($mod->visible
) {
2619 $actions['hide'] = new action_link(
2620 new moodle_url($baseurl, array('hide' => $mod->id
)),
2621 new pix_icon('t/hide', $str->hide
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2623 array('class' => 'editing_hide', 'title' => $str->hide
)
2626 $actions['show'] = new action_link(
2627 new moodle_url($baseurl, array('show' => $mod->id
)),
2628 new pix_icon('t/show', $str->show
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2630 array('class' => 'editing_show', 'title' => $str->show
)
2636 if ($hasmanageactivities and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
2637 if ($mod->coursegroupmodeforce
) {
2638 $modgroupmode = $mod->coursegroupmode
;
2640 $modgroupmode = $mod->groupmode
;
2642 if ($modgroupmode == SEPARATEGROUPS
) {
2643 $groupmode = NOGROUPS
;
2644 $grouptitle = $str->groupsseparate
;
2645 $forcedgrouptitle = $str->forcedgroupsseparate
;
2646 $actionname = 'groupsseparate';
2647 $groupimage = 't/groups';
2648 } else if ($modgroupmode == VISIBLEGROUPS
) {
2649 $groupmode = SEPARATEGROUPS
;
2650 $grouptitle = $str->groupsvisible
;
2651 $forcedgrouptitle = $str->forcedgroupsvisible
;
2652 $actionname = 'groupsvisible';
2653 $groupimage = 't/groupv';
2655 $groupmode = VISIBLEGROUPS
;
2656 $grouptitle = $str->groupsnone
;
2657 $forcedgrouptitle = $str->forcedgroupsnone
;
2658 $actionname = 'groupsnone';
2659 $groupimage = 't/groupn';
2661 if (!$mod->coursegroupmodeforce
) {
2662 $actions[$actionname] = new action_link(
2663 new moodle_url($baseurl, array('id' => $mod->id
, 'groupmode' => $groupmode)),
2664 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2666 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
2669 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
2674 if (has_capability('moodle/role:assign', $modcontext)){
2675 $actions['assign'] = new action_link(
2676 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id
)),
2677 new pix_icon('t/assignroles', $str->assign
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2679 array('class' => 'editing_assign', 'title' => $str->assign
)
2687 * given a course object with shortname & fullname, this function will
2688 * truncate the the number of chars allowed and add ... if it was too long
2690 function course_format_name ($course,$max=100) {
2692 $context = context_course
::instance($course->id
);
2693 $shortname = format_string($course->shortname
, true, array('context' => $context));
2694 $fullname = format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
2695 $str = $shortname.': '. $fullname;
2696 if (textlib
::strlen($str) <= $max) {
2700 return textlib
::substr($str,0,$max-3).'...';
2705 * Is the user allowed to add this type of module to this course?
2706 * @param object $course the course settings. Only $course->id is used.
2707 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2708 * @return bool whether the current user is allowed to add this type of module to this course.
2710 function course_allowed_module($course, $modname) {
2711 if (is_numeric($modname)) {
2712 throw new coding_exception('Function course_allowed_module no longer
2713 supports numeric module ids. Please update your code to pass the module name.');
2716 $capability = 'mod/' . $modname . ':addinstance';
2717 if (!get_capability_info($capability)) {
2718 // Debug warning that the capability does not exist, but no more than once per page.
2719 static $warned = array();
2720 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
2721 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM
) {
2722 debugging('The module ' . $modname . ' does not define the standard capability ' .
2723 $capability , DEBUG_DEVELOPER
);
2724 $warned[$modname] = 1;
2727 // If the capability does not exist, the module can always be added.
2731 $coursecontext = context_course
::instance($course->id
);
2732 return has_capability($capability, $coursecontext);
2736 * Recursively delete category including all subcategories and courses.
2737 * @param stdClass $category
2738 * @param boolean $showfeedback display some notices
2739 * @return array return deleted courses
2741 function category_delete_full($category, $showfeedback=true) {
2743 require_once($CFG->libdir
.'/gradelib.php');
2744 require_once($CFG->libdir
.'/questionlib.php');
2745 require_once($CFG->dirroot
.'/cohort/lib.php');
2747 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
2748 foreach ($children as $childcat) {
2749 category_delete_full($childcat, $showfeedback);
2753 $deletedcourses = array();
2754 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC')) {
2755 foreach ($courses as $course) {
2756 if (!delete_course($course, false)) {
2757 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname
);
2759 $deletedcourses[] = $course;
2763 // move or delete cohorts in this context
2764 cohort_delete_category($category);
2766 // now delete anything that may depend on course category context
2767 grade_course_category_delete($category->id
, 0, $showfeedback);
2768 if (!question_delete_course_category($category, 0, $showfeedback)) {
2769 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name
);
2772 // finally delete the category and it's context
2773 $DB->delete_records('course_categories', array('id'=>$category->id
));
2774 delete_context(CONTEXT_COURSECAT
, $category->id
);
2775 add_to_log(SITEID
, "category", "delete", "index.php", "$category->name (ID $category->id)");
2777 events_trigger('course_category_deleted', $category);
2779 return $deletedcourses;
2783 * Delete category, but move contents to another category.
2784 * @param object $ccategory
2785 * @param int $newparentid category id
2786 * @return bool status
2788 function category_delete_move($category, $newparentid, $showfeedback=true) {
2789 global $CFG, $DB, $OUTPUT;
2790 require_once($CFG->libdir
.'/gradelib.php');
2791 require_once($CFG->libdir
.'/questionlib.php');
2792 require_once($CFG->dirroot
.'/cohort/lib.php');
2794 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
2798 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
2799 foreach ($children as $childcat) {
2800 move_category($childcat, $newparentcat);
2804 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC', 'id')) {
2805 if (!move_courses(array_keys($courses), $newparentid)) {
2806 if ($showfeedback) {
2807 echo $OUTPUT->notification("Error moving courses");
2811 if ($showfeedback) {
2812 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
2816 // move or delete cohorts in this context
2817 cohort_delete_category($category);
2819 // now delete anything that may depend on course category context
2820 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
2821 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
2822 if ($showfeedback) {
2823 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2828 // finally delete the category and it's context
2829 $DB->delete_records('course_categories', array('id'=>$category->id
));
2830 delete_context(CONTEXT_COURSECAT
, $category->id
);
2831 add_to_log(SITEID
, "category", "delete", "index.php", "$category->name (ID $category->id)");
2833 events_trigger('course_category_deleted', $category);
2835 if ($showfeedback) {
2836 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
2842 * Efficiently moves many courses around while maintaining
2843 * sortorder in order.
2845 * @param array $courseids is an array of course ids
2846 * @param int $categoryid
2847 * @return bool success
2849 function move_courses($courseids, $categoryid) {
2850 global $CFG, $DB, $OUTPUT;
2852 if (empty($courseids)) {
2857 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2861 $courseids = array_reverse($courseids);
2862 $newparent = context_coursecat
::instance($category->id
);
2865 foreach ($courseids as $courseid) {
2866 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2867 $course = new stdClass();
2868 $course->id
= $courseid;
2869 $course->category
= $category->id
;
2870 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
2871 if ($category->visible
== 0) {
2872 // hide the course when moving into hidden category,
2873 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2874 $course->visible
= 0;
2877 $DB->update_record('course', $course);
2878 add_to_log($course->id
, "course", "move", "edit.php?id=$course->id", $course->id
);
2880 $context = context_course
::instance($course->id
);
2881 context_moved($context, $newparent);
2884 fix_course_sortorder();
2890 * Hide course category and child course and subcategories
2891 * @param stdClass $category
2894 function course_category_hide($category) {
2897 $category->visible
= 0;
2898 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id
));
2899 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id
));
2900 $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
2901 $DB->set_field('course', 'visible', 0, array('category' => $category->id
));
2902 // get all child categories and hide too
2903 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
2904 foreach ($subcats as $cat) {
2905 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id'=>$cat->id
));
2906 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id
));
2907 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
2908 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
2911 add_to_log(SITEID
, "category", "hide", "editcategory.php?id=$category->id", $category->id
);
2915 * Show course category and child course and subcategories
2916 * @param stdClass $category
2919 function course_category_show($category) {
2922 $category->visible
= 1;
2923 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id
));
2924 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id
));
2925 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id
));
2926 // get all child categories and unhide too
2927 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
2928 foreach ($subcats as $cat) {
2929 if ($cat->visibleold
) {
2930 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id
));
2932 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
2935 add_to_log(SITEID
, "category", "show", "editcategory.php?id=$category->id", $category->id
);
2939 * Efficiently moves a category - NOTE that this can have
2940 * a huge impact access-control-wise...
2942 function move_category($category, $newparentcat) {
2945 $context = context_coursecat
::instance($category->id
);
2948 if (empty($newparentcat->id
)) {
2949 $DB->set_field('course_categories', 'parent', 0, array('id' => $category->id
));
2950 $newparent = context_system
::instance();
2952 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id' => $category->id
));
2953 $newparent = context_coursecat
::instance($newparentcat->id
);
2955 if (!$newparentcat->visible
and $category->visible
) {
2956 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
2961 context_moved($context, $newparent);
2963 // now make it last in new category
2964 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id'=>$category->id
));
2967 add_to_log(SITEID
, "category", "move", "editcategory.php?id=$category->id", $category->id
);
2969 // and fix the sortorders
2970 fix_course_sortorder();
2973 course_category_hide($category);
2978 * Returns the display name of the given section that the course prefers
2980 * Implementation of this function is provided by course format
2981 * @see format_base::get_section_name()
2983 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2984 * @param int|stdClass $section Section object from database or just field course_sections.section
2985 * @return string Display name that the course format prefers, e.g. "Week 2"
2987 function get_section_name($courseorid, $section) {
2988 return course_get_format($courseorid)->get_section_name($section);
2992 * Tells if current course format uses sections
2994 * @param string $format Course format ID e.g. 'weeks' $course->format
2997 function course_format_uses_sections($format) {
2998 $course = new stdClass();
2999 $course->format
= $format;
3000 return course_get_format($course)->uses_sections();
3004 * Returns the information about the ajax support in the given source format
3006 * The returned object's property (boolean)capable indicates that
3007 * the course format supports Moodle course ajax features.
3008 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3010 * @param string $format
3013 function course_format_ajax_support($format) {
3014 $course = new stdClass();
3015 $course->format
= $format;
3016 return course_get_format($course)->supports_ajax();
3020 * Can the current user delete this course?
3021 * Course creators have exception,
3022 * 1 day after the creation they can sill delete the course.
3023 * @param int $courseid
3026 function can_delete_course($courseid) {
3029 $context = context_course
::instance($courseid);
3031 if (has_capability('moodle/course:delete', $context)) {
3035 // hack: now try to find out if creator created this course recently (1 day)
3036 if (!has_capability('moodle/course:create', $context)) {
3040 $since = time() - 60*60*24;
3042 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3043 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3045 return $DB->record_exists_select('log', $select, $params);
3049 * Save the Your name for 'Some role' strings.
3051 * @param integer $courseid the id of this course.
3052 * @param array $data the data that came from the course settings form.
3054 function save_local_role_names($courseid, $data) {
3056 $context = context_course
::instance($courseid);
3058 foreach ($data as $fieldname => $value) {
3059 if (strpos($fieldname, 'role_') !== 0) {
3062 list($ignored, $roleid) = explode('_', $fieldname);
3064 // make up our mind whether we want to delete, update or insert
3066 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
3068 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
3069 $rolename->name
= $value;
3070 $DB->update_record('role_names', $rolename);
3073 $rolename = new stdClass
;
3074 $rolename->contextid
= $context->id
;
3075 $rolename->roleid
= $roleid;
3076 $rolename->name
= $value;
3077 $DB->insert_record('role_names', $rolename);
3083 * Create a course and either return a $course object
3085 * Please note this functions does not verify any access control,
3086 * the calling code is responsible for all validation (usually it is the form definition).
3088 * @param array $editoroptions course description editor options
3089 * @param object $data - all the data needed for an entry in the 'course' table
3090 * @return object new course instance
3092 function create_course($data, $editoroptions = NULL) {
3095 //check the categoryid - must be given for all new courses
3096 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
3098 //check if the shortname already exist
3099 if (!empty($data->shortname
)) {
3100 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
3101 throw new moodle_exception('shortnametaken');
3105 //check if the id number already exist
3106 if (!empty($data->idnumber
)) {
3107 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
3108 throw new moodle_exception('idnumbertaken');
3112 $data->timecreated
= time();
3113 $data->timemodified
= $data->timecreated
;
3115 // place at beginning of any category
3116 $data->sortorder
= 0;
3118 if ($editoroptions) {
3119 // summary text is updated later, we need context to store the files first
3120 $data->summary
= '';
3121 $data->summary_format
= FORMAT_HTML
;
3124 if (!isset($data->visible
)) {
3125 // data not from form, add missing visibility info
3126 $data->visible
= $category->visible
;
3128 $data->visibleold
= $data->visible
;
3130 $newcourseid = $DB->insert_record('course', $data);
3131 $context = context_course
::instance($newcourseid, MUST_EXIST
);
3133 if ($editoroptions) {
3134 // Save the files used in the summary editor and store
3135 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3136 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
3137 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
3140 // update course format options
3141 course_get_format($newcourseid)->update_course_format_options($data);
3143 $course = course_get_format($newcourseid)->get_course();
3146 blocks_add_default_course_blocks($course);
3148 // Create a default section.
3149 course_create_sections_if_missing($course, 0);
3151 fix_course_sortorder();
3153 // new context created - better mark it as dirty
3154 mark_context_dirty($context->path
);
3156 // Save any custom role names.
3157 save_local_role_names($course->id
, (array)$data);
3159 // set up enrolments
3160 enrol_course_updated(true, $course, $data);
3162 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3165 events_trigger('course_created', $course);
3171 * Create a new course category and marks the context as dirty
3173 * This function does not set the sortorder for the new category and
3174 * @see{fix_course_sortorder} should be called after creating a new course
3177 * Please note that this function does not verify access control.
3179 * @param object $category All of the data required for an entry in the course_categories table
3180 * @return object new course category
3182 function create_course_category($category) {
3185 $category->timemodified
= time();
3186 $category->id
= $DB->insert_record('course_categories', $category);
3187 $category = $DB->get_record('course_categories', array('id' => $category->id
));
3189 // We should mark the context as dirty
3190 $category->context
= context_coursecat
::instance($category->id
);
3191 $category->context
->mark_dirty();
3199 * Please note this functions does not verify any access control,
3200 * the calling code is responsible for all validation (usually it is the form definition).
3202 * @param object $data - all the data needed for an entry in the 'course' table
3203 * @param array $editoroptions course description editor options
3206 function update_course($data, $editoroptions = NULL) {
3209 $data->timemodified
= time();
3211 $oldcourse = course_get_format($data->id
)->get_course();
3212 $context = context_course
::instance($oldcourse->id
);
3214 if ($editoroptions) {
3215 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3218 if (!isset($data->category
) or empty($data->category
)) {
3219 // prevent nulls and 0 in category field
3220 unset($data->category
);
3222 $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
3224 if (!isset($data->visible
)) {
3225 // data not from form, add missing visibility info
3226 $data->visible
= $oldcourse->visible
;
3229 if ($data->visible
!= $oldcourse->visible
) {
3230 // reset the visibleold flag when manually hiding/unhiding course
3231 $data->visibleold
= $data->visible
;
3234 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
3235 if (empty($newcategory->visible
)) {
3236 // make sure when moving into hidden category the course is hidden automatically
3242 // Update with the new data
3243 $DB->update_record('course', $data);
3244 // make sure the modinfo cache is reset
3245 rebuild_course_cache($data->id
);
3247 // update course format options with full course data
3248 course_get_format($data->id
)->update_course_format_options($data, $oldcourse);
3250 $course = $DB->get_record('course', array('id'=>$data->id
));
3253 $newparent = context_coursecat
::instance($course->category
);
3254 context_moved($context, $newparent);
3257 fix_course_sortorder();
3259 // Test for and remove blocks which aren't appropriate anymore
3260 blocks_remove_inappropriate($course);
3262 // Save any custom role names.
3263 save_local_role_names($course->id
, $data);
3265 // update enrol settings
3266 enrol_course_updated(false, $course, $data);
3268 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3271 events_trigger('course_updated', $course);
3273 if ($oldcourse->format
!== $course->format
) {
3274 // Remove all options stored for the previous format
3275 // We assume that new course format migrated everything it needed watching trigger
3276 // 'course_updated' and in method format_XXX::update_course_format_options()
3277 $DB->delete_records('course_format_options',
3278 array('courseid' => $course->id
, 'format' => $oldcourse->format
));
3283 * Average number of participants
3286 function average_number_of_participants() {
3289 //count total of enrolments for visible course (except front page)
3290 $sql = 'SELECT COUNT(*) FROM (
3291 SELECT DISTINCT ue.userid, e.courseid
3292 FROM {user_enrolments} ue, {enrol} e, {course} c
3293 WHERE ue.enrolid = e.id
3294 AND e.courseid <> :siteid
3295 AND c.id = e.courseid
3296 AND c.visible = 1) total';
3297 $params = array('siteid' => $SITE->id
);
3298 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3301 //count total of visible courses (minus front page)
3302 $coursetotal = $DB->count_records('course', array('visible' => 1));
3303 $coursetotal = $coursetotal - 1 ;
3305 //average of enrolment
3306 if (empty($coursetotal)) {
3307 $participantaverage = 0;
3309 $participantaverage = $enrolmenttotal / $coursetotal;
3312 return $participantaverage;
3316 * Average number of course modules
3319 function average_number_of_courses_modules() {
3322 //count total of visible course module (except front page)
3323 $sql = 'SELECT COUNT(*) FROM (
3324 SELECT cm.course, cm.module
3325 FROM {course} c, {course_modules} cm
3326 WHERE c.id = cm.course
3329 AND c.visible = 1) total';
3330 $params = array('siteid' => $SITE->id
);
3331 $moduletotal = $DB->count_records_sql($sql, $params);
3334 //count total of visible courses (minus front page)
3335 $coursetotal = $DB->count_records('course', array('visible' => 1));
3336 $coursetotal = $coursetotal - 1 ;
3338 //average of course module
3339 if (empty($coursetotal)) {
3340 $coursemoduleaverage = 0;
3342 $coursemoduleaverage = $moduletotal / $coursetotal;
3345 return $coursemoduleaverage;
3349 * This class pertains to course requests and contains methods associated with
3350 * create, approving, and removing course requests.
3352 * Please note we do not allow embedded images here because there is no context
3353 * to store them with proper access control.
3355 * @copyright 2009 Sam Hemelryk
3356 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3359 * @property-read int $id
3360 * @property-read string $fullname
3361 * @property-read string $shortname
3362 * @property-read string $summary
3363 * @property-read int $summaryformat
3364 * @property-read int $summarytrust
3365 * @property-read string $reason
3366 * @property-read int $requester
3368 class course_request
{
3371 * This is the stdClass that stores the properties for the course request
3372 * and is externally accessed through the __get magic method
3375 protected $properties;
3378 * An array of options for the summary editor used by course request forms.
3379 * This is initially set by {@link summary_editor_options()}
3383 protected static $summaryeditoroptions;
3386 * Static function to prepare the summary editor for working with a course
3390 * @param null|stdClass $data Optional, an object containing the default values
3391 * for the form, these may be modified when preparing the
3392 * editor so this should be called before creating the form
3393 * @return stdClass An object that can be used to set the default values for
3396 public static function prepare($data=null) {
3397 if ($data === null) {
3398 $data = new stdClass
;
3400 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
3405 * Static function to create a new course request when passed an array of properties
3408 * This function also handles saving any files that may have been used in the editor
3411 * @param stdClass $data
3412 * @return course_request The newly created course request
3414 public static function create($data) {
3415 global $USER, $DB, $CFG;
3416 $data->requester
= $USER->id
;
3418 // Setting the default category if none set.
3419 if (empty($data->category
) ||
empty($CFG->requestcategoryselection
)) {
3420 $data->category
= $CFG->defaultrequestcategory
;
3423 // Summary is a required field so copy the text over
3424 $data->summary
= $data->summary_editor
['text'];
3425 $data->summaryformat
= $data->summary_editor
['format'];
3427 $data->id
= $DB->insert_record('course_request', $data);
3429 // Create a new course_request object and return it
3430 $request = new course_request($data);
3432 // Notify the admin if required.
3433 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
3436 $a->link
= "$CFG->wwwroot/course/pending.php";
3437 $a->user
= fullname($USER);
3438 $subject = get_string('courserequest');
3439 $message = get_string('courserequestnotifyemail', 'admin', $a);
3440 foreach ($users as $user) {
3441 $request->notify($user, $USER, 'courserequested', $subject, $message);
3449 * Returns an array of options to use with a summary editor
3451 * @uses course_request::$summaryeditoroptions
3452 * @return array An array of options to use with the editor
3454 public static function summary_editor_options() {
3456 if (self
::$summaryeditoroptions === null) {
3457 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
3459 return self
::$summaryeditoroptions;
3463 * Loads the properties for this course request object. Id is required and if
3464 * only id is provided then we load the rest of the properties from the database
3466 * @param stdClass|int $properties Either an object containing properties
3467 * or the course_request id to load
3469 public function __construct($properties) {
3471 if (empty($properties->id
)) {
3472 if (empty($properties)) {
3473 throw new coding_exception('You must provide a course request id when creating a course_request object');
3476 $properties = new stdClass
;
3477 $properties->id
= (int)$id;
3480 if (empty($properties->requester
)) {
3481 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
3482 print_error('unknowncourserequest');
3485 $this->properties
= $properties;
3487 $this->properties
->collision
= null;
3491 * Returns the requested property
3493 * @param string $key
3496 public function __get($key) {
3497 return $this->properties
->$key;
3501 * Override this to ensure empty($request->blah) calls return a reliable answer...
3503 * This is required because we define the __get method
3506 * @return bool True is it not empty, false otherwise
3508 public function __isset($key) {
3509 return (!empty($this->properties
->$key));
3513 * Returns the user who requested this course
3515 * Uses a static var to cache the results and cut down the number of db queries
3517 * @staticvar array $requesters An array of cached users
3518 * @return stdClass The user who requested the course
3520 public function get_requester() {
3522 static $requesters= array();
3523 if (!array_key_exists($this->properties
->requester
, $requesters)) {
3524 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
3526 return $requesters[$this->properties
->requester
];
3530 * Checks that the shortname used by the course does not conflict with any other
3531 * courses that exist
3533 * @param string|null $shortnamemark The string to append to the requests shortname
3534 * should a conflict be found
3535 * @return bool true is there is a conflict, false otherwise
3537 public function check_shortname_collision($shortnamemark = '[*]') {
3540 if ($this->properties
->collision
!== null) {
3541 return $this->properties
->collision
;
3544 if (empty($this->properties
->shortname
)) {
3545 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
3546 $this->properties
->collision
= false;
3547 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
3548 if (!empty($shortnamemark)) {
3549 $this->properties
->shortname
.= ' '.$shortnamemark;
3551 $this->properties
->collision
= true;
3553 $this->properties
->collision
= false;
3555 return $this->properties
->collision
;
3559 * This function approves the request turning it into a course
3561 * This function converts the course request into a course, at the same time
3562 * transferring any files used in the summary to the new course and then removing
3563 * the course request and the files associated with it.
3565 * @return int The id of the course that was created from this request
3567 public function approve() {
3568 global $CFG, $DB, $USER;
3570 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
3572 $courseconfig = get_config('moodlecourse');
3574 // Transfer appropriate settings
3575 $data = clone($this->properties
);
3577 unset($data->reason
);
3578 unset($data->requester
);
3580 // If the category is not set, if the current user does not have the rights to change the category, or if the
3581 // category does not exist, we set the default category to the course to be approved.
3582 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
3583 if (empty($data->category
) ||
!has_capability('moodle/course:changecategory', context_system
::instance()) ||
3584 (!$category = get_course_category($data->category
))) {
3585 $category = get_course_category($CFG->defaultrequestcategory
);
3589 $data->category
= $category->id
;
3590 $data->sortorder
= $category->sortorder
; // place as the first in category
3592 // Set misc settings
3593 $data->requested
= 1;
3595 // Apply course default settings
3596 $data->format
= $courseconfig->format
;
3597 $data->newsitems
= $courseconfig->newsitems
;
3598 $data->showgrades
= $courseconfig->showgrades
;
3599 $data->showreports
= $courseconfig->showreports
;
3600 $data->maxbytes
= $courseconfig->maxbytes
;
3601 $data->groupmode
= $courseconfig->groupmode
;
3602 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
3603 $data->visible
= $courseconfig->visible
;
3604 $data->visibleold
= $data->visible
;
3605 $data->lang
= $courseconfig->lang
;
3607 $course = create_course($data);
3608 $context = context_course
::instance($course->id
, MUST_EXIST
);
3610 // add enrol instances
3611 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
3612 if ($manual = enrol_get_plugin('manual')) {
3613 $manual->add_default_instance($course);
3617 // enrol the requester as teacher if necessary
3618 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3619 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
3624 $a = new stdClass();
3625 $a->name
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
3626 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
3627 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3633 * Reject a course request
3635 * This function rejects a course request, emailing the requesting user the
3636 * provided notice and then removing the request from the database
3638 * @param string $notice The message to display to the user
3640 public function reject($notice) {
3642 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
3643 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3648 * Deletes the course request and any associated files
3650 public function delete() {
3652 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
3656 * Send a message from one user to another using events_trigger
3658 * @param object $touser
3659 * @param object $fromuser
3660 * @param string $name
3661 * @param string $subject
3662 * @param string $message
3664 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3665 $eventdata = new stdClass();
3666 $eventdata->component
= 'moodle';
3667 $eventdata->name
= $name;
3668 $eventdata->userfrom
= $fromuser;
3669 $eventdata->userto
= $touser;
3670 $eventdata->subject
= $subject;
3671 $eventdata->fullmessage
= $message;
3672 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
3673 $eventdata->fullmessagehtml
= '';
3674 $eventdata->smallmessage
= '';
3675 $eventdata->notification
= 1;
3676 message_send($eventdata);
3681 * Return a list of page types
3682 * @param string $pagetype current page type
3683 * @param stdClass $parentcontext Block's parent context
3684 * @param stdClass $currentcontext Current context of block
3686 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3687 // $currentcontext could be null, get_context_info_array() will throw an error if this is the case.
3688 if (isset($currentcontext)) {
3689 // if above course context ,display all course fomats
3690 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id
);
3691 if ($course->id
== SITEID
) {
3692 return array('*'=>get_string('page-x', 'pagetype'));
3695 return array('*'=>get_string('page-x', 'pagetype'),
3696 'course-*'=>get_string('page-course-x', 'pagetype'),
3697 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
3702 * Determine whether course ajax should be enabled for the specified course
3704 * @param stdClass $course The course to test against
3705 * @return boolean Whether course ajax is enabled or note
3707 function course_ajax_enabled($course) {
3708 global $CFG, $PAGE, $SITE;
3710 // Ajax must be enabled globally
3711 if (!$CFG->enableajax
) {
3715 // The user must be editing for AJAX to be included
3716 if (!$PAGE->user_is_editing()) {
3720 // Check that the theme suports
3721 if (!$PAGE->theme
->enablecourseajax
) {
3725 // Check that the course format supports ajax functionality
3726 // The site 'format' doesn't have information on course format support
3727 if ($SITE->id
!== $course->id
) {
3728 $courseformatajaxsupport = course_format_ajax_support($course->format
);
3729 if (!$courseformatajaxsupport->capable
) {
3734 // All conditions have been met so course ajax should be enabled
3739 * Include the relevant javascript and language strings for the resource
3740 * toolbox YUI module
3742 * @param integer $id The ID of the course being applied to
3743 * @param array $usedmodules An array containing the names of the modules in use on the page
3744 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3745 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3746 * * resourceurl The URL to post changes to for resource changes
3747 * * sectionurl The URL to post changes to for section changes
3748 * * pageparams Additional parameters to pass through in the post
3751 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3752 global $PAGE, $SITE;
3754 // Ensure that ajax should be included
3755 if (!course_ajax_enabled($course)) {
3760 $config = new stdClass();
3763 // The URL to use for resource changes
3764 if (!isset($config->resourceurl
)) {
3765 $config->resourceurl
= '/course/rest.php';
3768 // The URL to use for section changes
3769 if (!isset($config->sectionurl
)) {
3770 $config->sectionurl
= '/course/rest.php';
3773 // Any additional parameters which need to be included on page submission
3774 if (!isset($config->pageparams
)) {
3775 $config->pageparams
= array();
3778 // Include toolboxes
3779 $PAGE->requires
->yui_module('moodle-course-toolboxes',
3780 'M.course.init_resource_toolbox',
3782 'courseid' => $course->id
,
3783 'ajaxurl' => $config->resourceurl
,
3784 'config' => $config,
3787 $PAGE->requires
->yui_module('moodle-course-toolboxes',
3788 'M.course.init_section_toolbox',
3790 'courseid' => $course->id
,
3791 'format' => $course->format
,
3792 'ajaxurl' => $config->sectionurl
,
3793 'config' => $config,
3797 // Include course dragdrop
3798 if ($course->id
!= $SITE->id
) {
3799 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3801 'courseid' => $course->id
,
3802 'ajaxurl' => $config->sectionurl
,
3803 'config' => $config,
3806 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3808 'courseid' => $course->id
,
3809 'ajaxurl' => $config->resourceurl
,
3810 'config' => $config,
3814 // Require various strings for the command toolbox
3815 $PAGE->requires
->strings_for_js(array(
3818 'deletechecktypename',
3820 'edittitleinstructions',
3826 'clicktochangeinbrackets',
3833 // Include format-specific strings
3834 if ($course->id
!= $SITE->id
) {
3835 $PAGE->requires
->strings_for_js(array(
3838 ), 'format_' . $course->format
);
3841 // For confirming resource deletion we need the name of the module in question
3842 foreach ($usedmodules as $module => $modname) {
3843 $PAGE->requires
->string_for_js('pluginname', $module);
3846 // Load drag and drop upload AJAX.
3847 dndupload_add_to_course($course, $enabledmodules);
3853 * Returns the sorted list of available course formats, filtered by enabled if necessary
3855 * @param bool $enabledonly return only formats that are enabled
3856 * @return array array of sorted format names
3858 function get_sorted_course_formats($enabledonly = false) {
3860 $formats = get_plugin_list('format');
3862 if (!empty($CFG->format_plugins_sortorder
)) {
3863 $order = explode(',', $CFG->format_plugins_sortorder
);
3864 $order = array_merge(array_intersect($order, array_keys($formats)),
3865 array_diff(array_keys($formats), $order));
3867 $order = array_keys($formats);
3869 if (!$enabledonly) {
3872 $sortedformats = array();
3873 foreach ($order as $formatname) {
3874 if (!get_config('format_'.$formatname, 'disabled')) {
3875 $sortedformats[] = $formatname;
3878 return $sortedformats;
3882 * The URL to use for the specified course (with section)
3884 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3885 * @param int|stdClass $section Section object from database or just field course_sections.section
3886 * if omitted the course view page is returned
3887 * @param array $options options for view URL. At the moment core uses:
3888 * 'navigation' (bool) if true and section has no separate page, the function returns null
3889 * 'sr' (int) used by multipage formats to specify to which section to return
3890 * @return moodle_url The url of course
3892 function course_get_url($courseorid, $section = null, $options = array()) {
3893 return course_get_format($courseorid)->get_view_url($section, $options);