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','generalbox');
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 if ($types = $gettypesfunc()) {
1148 $group = new stdClass();
1149 $group->name
= $modname;
1150 $group->icon
= $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1151 foreach($types as $type) {
1152 if ($type->typestr
=== '--') {
1155 if (strpos($type->typestr
, '--') === 0) {
1156 $group->title
= str_replace('--', '', $type->typestr
);
1159 // Set the Sub Type metadata
1160 $subtype = new stdClass();
1161 $subtype->title
= $type->typestr
;
1162 $subtype->type
= str_replace('&', '&', $type->type
);
1163 $subtype->name
= preg_replace('/.*type=/', '', $subtype->type
);
1164 $subtype->archetype
= $type->modclass
;
1166 // The group archetype should match the subtype archetypes and all subtypes
1167 // should have the same archetype
1168 $group->archetype
= $subtype->archetype
;
1170 if (get_string_manager()->string_exists('help' . $subtype->name
, $modname)) {
1171 $subtype->help
= get_string('help' . $subtype->name
, $modname);
1173 $subtype->link
= new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name
));
1174 $group->types
[] = $subtype;
1176 $modlist[$course->id
][$modname] = $group;
1179 $module = new stdClass();
1180 $module->title
= $modnamestr;
1181 $module->name
= $modname;
1182 $module->link
= new moodle_url($urlbase, array('add' => $modname));
1183 $module->icon
= $OUTPUT->pix_icon('icon', '', $module->name
, array('class' => 'icon'));
1184 $sm = get_string_manager();
1185 if ($sm->string_exists('modulename_help', $modname)) {
1186 $module->help
= get_string('modulename_help', $modname);
1187 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1188 $link = get_string('modulename_link', $modname);
1189 $linktext = get_string('morehelp');
1190 $module->help
.= html_writer
::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1193 $module->archetype
= plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
1194 $modlist[$course->id
][$modname] = $module;
1196 $return[$modname] = $modlist[$course->id
][$modname];
1203 * Return the course category context for the category with id $categoryid, except
1204 * that if $categoryid is 0, return the system context.
1206 * @param integer $categoryid a category id or 0.
1207 * @return object the corresponding context
1209 function get_category_or_system_context($categoryid) {
1211 return context_coursecat
::instance($categoryid, IGNORE_MISSING
);
1213 return context_system
::instance();
1218 * Gets the child categories of a given courses category. Uses a static cache
1219 * to make repeat calls efficient.
1221 * @param int $parentid the id of a course category.
1222 * @return array all the child course categories.
1224 function get_child_categories($parentid) {
1225 static $allcategories = null;
1227 // only fill in this variable the first time
1228 if (null == $allcategories) {
1229 $allcategories = array();
1231 $categories = get_categories();
1232 foreach ($categories as $category) {
1233 if (empty($allcategories[$category->parent
])) {
1234 $allcategories[$category->parent
] = array();
1236 $allcategories[$category->parent
][] = $category;
1240 if (empty($allcategories[$parentid])) {
1243 return $allcategories[$parentid];
1248 * This function recursively travels the categories, building up a nice list
1249 * for display. It also makes an array that list all the parents for each
1252 * For example, if you have a tree of categories like:
1253 * Miscellaneous (id = 1)
1254 * Subcategory (id = 2)
1255 * Sub-subcategory (id = 4)
1256 * Other category (id = 3)
1257 * Then after calling this function you will have
1258 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1259 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1260 * 3 => 'Other category');
1261 * $parents = array(2 => array(1), 4 => array(1, 2));
1263 * If you specify $requiredcapability, then only categories where the current
1264 * user has that capability will be added to $list, although all categories
1265 * will still be added to $parents, and if you only have $requiredcapability
1266 * in a child category, not the parent, then the child catgegory will still be
1269 * If you specify the option $excluded, then that category, and all its children,
1270 * are omitted from the tree. This is useful when you are doing something like
1271 * moving categories, where you do not want to allow people to move a category
1272 * to be the child of itself.
1274 * @param array $list For output, accumulates an array categoryid => full category path name
1275 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1276 * @param string/array $requiredcapability if given, only categories where the current
1277 * user has this capability will be added to $list. Can also be an array of capabilities,
1278 * in which case they are all required.
1279 * @param integer $excludeid Omit this category and its children from the lists built.
1280 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1281 * @param string $path For internal use, as part of recursive calls.
1283 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1284 $excludeid = 0, $category = NULL, $path = "") {
1286 // initialize the arrays if needed
1287 if (!is_array($list)) {
1290 if (!is_array($parents)) {
1294 if (empty($category)) {
1295 // Start at the top level.
1296 $category = new stdClass
;
1299 // This is the excluded category, don't include it.
1300 if ($excludeid > 0 && $excludeid == $category->id
) {
1304 $context = context_coursecat
::instance($category->id
);
1305 $categoryname = format_string($category->name
, true, array('context' => $context));
1309 $path = $path.' / '.$categoryname;
1311 $path = $categoryname;
1314 // Add this category to $list, if the permissions check out.
1315 if (empty($requiredcapability)) {
1316 $list[$category->id
] = $path;
1319 $requiredcapability = (array)$requiredcapability;
1320 if (has_all_capabilities($requiredcapability, $context)) {
1321 $list[$category->id
] = $path;
1326 // Add all the children recursively, while updating the parents array.
1327 if ($categories = get_child_categories($category->id
)) {
1328 foreach ($categories as $cat) {
1329 if (!empty($category->id
)) {
1330 if (isset($parents[$category->id
])) {
1331 $parents[$cat->id
] = $parents[$category->id
];
1333 $parents[$cat->id
][] = $category->id
;
1335 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
1341 * This function generates a structured array of courses and categories.
1343 * The depth of categories is limited by $CFG->maxcategorydepth however there
1344 * is no limit on the number of courses!
1346 * Suitable for use with the course renderers course_category_tree method:
1347 * $renderer = $PAGE->get_renderer('core','course');
1348 * echo $renderer->course_category_tree(get_course_category_tree());
1350 * @global moodle_database $DB
1354 function get_course_category_tree($id = 0, $depth = 0) {
1356 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', context_system
::instance());
1357 $categories = get_child_categories($id);
1358 $categoryids = array();
1359 foreach ($categories as $key => &$category) {
1360 if (!$category->visible
&& !$viewhiddencats) {
1361 unset($categories[$key]);
1364 $categoryids[$category->id
] = $category;
1365 if (empty($CFG->maxcategorydepth
) ||
$depth <= $CFG->maxcategorydepth
) {
1366 list($category->categories
, $subcategories) = get_course_category_tree($category->id
, $depth+
1);
1367 foreach ($subcategories as $subid=>$subcat) {
1368 $categoryids[$subid] = $subcat;
1370 $category->courses
= array();
1375 // This is a recursive call so return the required array
1376 return array($categories, $categoryids);
1379 if (empty($categoryids)) {
1380 // No categories available (probably all hidden).
1384 // The depth is 0 this function has just been called so we can finish it off
1386 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1387 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
1389 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
1393 WHERE c.category $catsql ORDER BY c.sortorder ASC";
1394 if ($courses = $DB->get_records_sql($sql, $catparams)) {
1395 // loop throught them
1396 foreach ($courses as $course) {
1397 if ($course->id
== SITEID
) {
1400 context_instance_preload($course);
1401 if (!empty($course->visible
) ||
has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
1402 $categoryids[$course->category
]->courses
[$course->id
] = $course;
1410 * Recursive function to print out all the categories in a nice format
1411 * with or without courses included
1413 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1416 // maxcategorydepth == 0 meant no limit
1417 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
1421 if (!$displaylist) {
1422 make_categories_list($displaylist, $parentslist);
1425 if (!$categorycourses) {
1427 $categorycourses = get_category_courses_array($category->id
);
1429 $categorycourses = get_category_courses_array();
1434 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', context_system
::instance())) {
1435 print_category_info($category, $depth, $showcourses, $categorycourses[$category->id
]);
1437 return; // Don't bother printing children of invisible categories
1441 $category = new stdClass();
1442 $category->id
= "0";
1445 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
1446 $countcats = count($categories);
1450 foreach ($categories as $cat) {
1452 if ($count == $countcats) {
1455 $up = $first ?
false : true;
1456 $down = $last ?
false : true;
1459 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses, $categorycourses);
1465 * Gets an array whose keys are category ids and whose values are arrays of courses in the corresponding category.
1467 * @param int $categoryid
1470 function get_category_courses_array($categoryid = 0) {
1471 $tree = get_course_category_tree($categoryid);
1472 $flattened = array();
1473 foreach ($tree as $category) {
1474 get_category_courses_array_recursively($flattened, $category);
1480 * Recursive function to help flatten the course category tree.
1482 * Do not call this function directly, instead calll its parent function {@link get_category_courses_array}
1484 * @param array &$flattened An array passed by reference in which to store courses for each category.
1485 * @param stdClass $category The category to get courses for.
1487 function get_category_courses_array_recursively(array &$flattened, $category) {
1488 $flattened[$category->id
] = $category->courses
;
1489 foreach ($category->categories
as $childcategory) {
1490 get_category_courses_array_recursively($flattened, $childcategory);
1495 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
1497 function make_categories_options() {
1498 make_categories_list($cats,$parents);
1499 foreach ($cats as $key => $value) {
1500 if (array_key_exists($key,$parents)) {
1501 if ($indent = count($parents[$key])) {
1502 for ($i = 0; $i < $indent; $i++
) {
1503 $cats[$key] = ' '.$cats[$key];
1512 * Prints the category information.
1514 * This function is only used by print_whole_category_list() above
1516 * @param stdClass $category
1517 * @param int $depth The depth of the category.
1518 * @param bool $showcourses If set to true course information will also be printed.
1519 * @param array|null $courses An array of courses belonging to the category, or null if you don't have it yet.
1521 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1522 global $CFG, $DB, $OUTPUT;
1524 $strsummary = get_string('summary');
1527 if (!$category->visible
) {
1528 $catlinkcss = array('class'=>'dimmed');
1530 static $coursecount = null;
1531 if (null === $coursecount) {
1532 // only need to check this once
1533 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT
;
1536 if ($showcourses and $coursecount) {
1537 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
1539 $catimage = " ";
1542 if (is_null($courses)) {
1543 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
1545 $context = context_coursecat
::instance($category->id
);
1546 $fullname = format_string($category->name
, true, array('context' => $context));
1548 if ($showcourses and $coursecount) {
1549 echo '<div class="categorylist clearfix">';
1551 $cat .= html_writer
::tag('div', $catimage, array('class'=>'image'));
1552 $catlink = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
1553 $cat .= html_writer
::tag('div', $catlink, array('class'=>'name'));
1557 for ($i=0; $i< $depth; $i++
) {
1558 $html = html_writer
::tag('div', $html . $cat, array('class'=>'indentation'));
1564 echo html_writer
::tag('div', $html, array('class'=>'category'));
1565 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
1567 // does the depth exceed maxcategorydepth
1568 // maxcategorydepth == 0 or unset meant no limit
1569 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
1570 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
1571 foreach ($courses as $course) {
1573 if (!$course->visible
) {
1574 $linkcss = array('class'=>'dimmed');
1577 $coursename = get_course_display_name_for_list($course);
1578 $courselink = html_writer
::link(new moodle_url('/course/view.php', array('id'=>$course->id
)), format_string($coursename), $linkcss);
1582 if ($icons = enrol_get_course_info_icons($course)) {
1583 foreach ($icons as $pix_icon) {
1584 $courseicon = $OUTPUT->render($pix_icon);
1588 $coursecontent = html_writer
::tag('div', $courseicon.$courselink, array('class'=>'name'));
1590 if ($course->summary
) {
1591 $link = new moodle_url('/course/info.php?id='.$course->id
);
1592 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
1593 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
1594 array('title'=>$strsummary));
1596 $coursecontent .= html_writer
::tag('div', $actionlink, array('class'=>'info'));
1600 for ($i=0; $i <= $depth; $i++
) {
1601 $html = html_writer
::tag('div', $html . $coursecontent , array('class'=>'indentation'));
1602 $coursecontent = '';
1604 echo html_writer
::tag('div', $html, array('class'=>'course clearfloat'));
1609 echo '<div class="categorylist">';
1611 $cat = html_writer
::link(new moodle_url('/course/category.php', array('id'=>$category->id
)), $fullname, $catlinkcss);
1612 if (count($courses) > 0) {
1613 $cat .= html_writer
::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
1617 for ($i=0; $i< $depth; $i++
) {
1618 $html = html_writer
::tag('div', $html .$cat, array('class'=>'indentation'));
1625 echo html_writer
::tag('div', $html, array('class'=>'category'));
1626 echo html_writer
::tag('div', '', array('class'=>'clearfloat'));
1632 * Print the buttons relating to course requests.
1634 * @param object $systemcontext the system context.
1636 function print_course_request_buttons($systemcontext) {
1637 global $CFG, $DB, $OUTPUT;
1638 if (empty($CFG->enablecourserequests
)) {
1641 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
1642 /// Print a button to request a new course
1643 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
1645 /// Print a button to manage pending requests
1646 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
1647 $disabled = !$DB->record_exists('course_request', array());
1648 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
1653 * Does the user have permission to edit things in this category?
1655 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1656 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1658 function can_edit_in_category($categoryid = 0) {
1659 $context = get_category_or_system_context($categoryid);
1660 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1664 * Prints the turn editing on/off button on course/index.php or course/category.php.
1666 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1667 * @return string HTML of the editing button, or empty string, if this user is not allowed
1670 function update_category_button($categoryid = 0) {
1671 global $CFG, $PAGE, $OUTPUT;
1673 // Check permissions.
1674 if (!can_edit_in_category($categoryid)) {
1678 // Work out the appropriate action.
1679 if ($PAGE->user_is_editing()) {
1680 $label = get_string('turneditingoff');
1683 $label = get_string('turneditingon');
1687 // Generate the button HTML.
1688 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
1690 $options['id'] = $categoryid;
1691 $page = 'category.php';
1693 $page = 'index.php';
1695 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
1699 * Print courses in category. If category is 0 then all courses are printed.
1700 * @param int|stdClass $category category object or id.
1701 * @return bool true if courses found and printed, else false.
1703 function print_courses($category) {
1704 global $CFG, $OUTPUT;
1706 if (!is_object($category) && $category==0) {
1707 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1708 if (is_array($categories) && count($categories) == 1) {
1709 $category = array_shift($categories);
1710 $courses = get_courses_wmanagers($category->id
,
1712 array('summary','summaryformat'));
1714 $courses = get_courses_wmanagers('all',
1716 array('summary','summaryformat'));
1720 $courses = get_courses_wmanagers($category->id
,
1722 array('summary','summaryformat'));
1726 echo html_writer
::start_tag('ul', array('class'=>'unlist'));
1727 foreach ($courses as $course) {
1728 $coursecontext = context_course
::instance($course->id
);
1729 if ($course->visible
== 1 ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
1730 echo html_writer
::start_tag('li');
1731 print_course($course);
1732 echo html_writer
::end_tag('li');
1735 echo html_writer
::end_tag('ul');
1737 echo $OUTPUT->heading(get_string("nocoursesyet"));
1738 $context = context_system
::instance();
1739 if (has_capability('moodle/course:create', $context)) {
1741 if (!empty($category->id
)) {
1742 $options['category'] = $category->id
;
1744 $options['category'] = $CFG->defaultrequestcategory
;
1746 echo html_writer
::start_tag('div', array('class'=>'addcoursebutton'));
1747 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
1748 echo html_writer
::end_tag('div');
1756 * Print a description of a course, suitable for browsing in a list.
1758 * @param object $course the course object.
1759 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
1761 function print_course($course, $highlightterms = '') {
1762 global $CFG, $USER, $DB, $OUTPUT;
1764 $context = context_course
::instance($course->id
);
1766 // Rewrite file URLs so that they are correct
1767 $course->summary
= file_rewrite_pluginfile_urls($course->summary
, 'pluginfile.php', $context->id
, 'course', 'summary', NULL);
1769 echo html_writer
::start_tag('div', array('class'=>'coursebox clearfix'));
1770 echo html_writer
::start_tag('div', array('class'=>'info'));
1771 echo html_writer
::start_tag('h3', array('class'=>'name'));
1773 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id
));
1775 $coursename = get_course_display_name_for_list($course);
1776 $linktext = highlight($highlightterms, format_string($coursename));
1777 $linkparams = array('title'=>get_string('entercourse'));
1778 if (empty($course->visible
)) {
1779 $linkparams['class'] = 'dimmed';
1781 echo html_writer
::link($linkhref, $linktext, $linkparams);
1782 echo html_writer
::end_tag('h3');
1784 /// first find all roles that are supposed to be displayed
1785 if (!empty($CFG->coursecontact
)) {
1786 $managerroles = explode(',', $CFG->coursecontact
);
1789 if (!isset($course->managers
)) {
1790 list($sort, $sortparams) = users_order_by_sql('u');
1791 $rusers = get_role_users($managerroles, $context, true,
1792 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
1793 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
1794 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
1796 // use the managers array if we have it for perf reasosn
1797 // populate the datastructure like output of get_role_users();
1798 foreach ($course->managers
as $manager) {
1799 $user = clone($manager->user
);
1800 $user->roleid
= $manager->roleid
;
1801 $user->rolename
= $manager->rolename
;
1802 $user->roleshortname
= $manager->roleshortname
;
1803 $user->rolecoursealias
= $manager->rolecoursealias
;
1804 $rusers[$user->id
] = $user;
1808 $namesarray = array();
1809 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1810 foreach ($rusers as $ra) {
1811 if (isset($namesarray[$ra->id
])) {
1812 // only display a user once with the higest sortorder role
1816 $role = new stdClass();
1817 $role->id
= $ra->roleid
;
1818 $role->name
= $ra->rolename
;
1819 $role->shortname
= $ra->roleshortname
;
1820 $role->coursealias
= $ra->rolecoursealias
;
1821 $rolename = role_get_name($role, $context, ROLENAME_ALIAS
);
1823 $fullname = fullname($ra, $canviewfullnames);
1824 $namesarray[$ra->id
] = $rolename.': '.
1825 html_writer
::link(new moodle_url('/user/view.php', array('id'=>$ra->id
, 'course'=>SITEID
)), $fullname);
1828 if (!empty($namesarray)) {
1829 echo html_writer
::start_tag('ul', array('class'=>'teachers'));
1830 foreach ($namesarray as $name) {
1831 echo html_writer
::tag('li', $name);
1833 echo html_writer
::end_tag('ul');
1836 echo html_writer
::end_tag('div'); // End of info div
1838 echo html_writer
::start_tag('div', array('class'=>'summary'));
1839 $options = new stdClass();
1840 $options->noclean
= true;
1841 $options->para
= false;
1842 $options->overflowdiv
= true;
1843 if (!isset($course->summaryformat
)) {
1844 $course->summaryformat
= FORMAT_MOODLE
;
1846 echo highlight($highlightterms, format_text($course->summary
, $course->summaryformat
, $options, $course->id
));
1847 if ($icons = enrol_get_course_info_icons($course)) {
1848 echo html_writer
::start_tag('div', array('class'=>'enrolmenticons'));
1849 foreach ($icons as $icon) {
1850 $icon->attributes
["alt"] .= ": ". format_string($coursename, true, array('context'=>$context));
1851 echo $OUTPUT->render($icon);
1853 echo html_writer
::end_tag('div'); // End of enrolmenticons div
1855 echo html_writer
::end_tag('div'); // End of summary div
1856 echo html_writer
::end_tag('div'); // End of coursebox div
1860 * Prints custom user information on the home page.
1861 * Over time this can include all sorts of information
1863 function print_my_moodle() {
1864 global $USER, $CFG, $DB, $OUTPUT;
1866 if (!isloggedin() or isguestuser()) {
1867 print_error('nopermissions', '', '', 'See My Moodle');
1870 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
1872 $rcourses = array();
1873 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
1874 $rcourses = get_my_remotecourses($USER->id
);
1875 $rhosts = get_my_remotehosts();
1878 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
1880 if (!empty($courses)) {
1881 echo '<ul class="unlist">';
1882 foreach ($courses as $course) {
1883 if ($course->id
== SITEID
) {
1887 print_course($course);
1894 if (!empty($rcourses)) {
1895 // at the IDP, we know of all the remote courses
1896 foreach ($rcourses as $course) {
1897 print_remote_course($course, "100%");
1899 } elseif (!empty($rhosts)) {
1900 // non-IDP, we know of all the remote servers, but not courses
1901 foreach ($rhosts as $host) {
1902 print_remote_host($host, "100%");
1908 if ($DB->count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
1909 echo "<table width=\"100%\"><tr><td align=\"center\">";
1910 print_course_search("", false, "short");
1911 echo "</td><td align=\"center\">";
1912 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
1913 echo "</td></tr></table>\n";
1917 if ($DB->count_records("course_categories") > 1) {
1918 echo $OUTPUT->box_start("categorybox");
1919 print_whole_category_list();
1920 echo $OUTPUT->box_end();
1928 function print_course_search($value="", $return=false, $format="plain") {
1934 $id = 'coursesearch';
1940 $strsearchcourses= get_string("searchcourses");
1942 if ($format == 'plain') {
1943 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1944 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1945 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
1946 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
1947 $output .= '<input type="submit" value="'.get_string('go').'" />';
1948 $output .= '</fieldset></form>';
1949 } else if ($format == 'short') {
1950 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1951 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1952 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
1953 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
1954 $output .= '<input type="submit" value="'.get_string('go').'" />';
1955 $output .= '</fieldset></form>';
1956 } else if ($format == 'navbar') {
1957 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
1958 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
1959 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
1960 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
1961 $output .= '<input type="submit" value="'.get_string('go').'" />';
1962 $output .= '</fieldset></form>';
1971 function print_remote_course($course, $width="100%") {
1976 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
1978 echo '<div class="coursebox remotecoursebox clearfix">';
1979 echo '<div class="info">';
1980 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1981 $linkcss.' href="'.$url.'">'
1982 . format_string($course->fullname
) .'</a><br />'
1983 . format_string($course->hostname
) . ' : '
1984 . format_string($course->cat_name
) . ' : '
1985 . format_string($course->shortname
). '</div>';
1986 echo '</div><div class="summary">';
1987 $options = new stdClass();
1988 $options->noclean
= true;
1989 $options->para
= false;
1990 $options->overflowdiv
= true;
1991 echo format_text($course->summary
, $course->summaryformat
, $options);
1996 function print_remote_host($host, $width="100%") {
2001 echo '<div class="coursebox clearfix">';
2002 echo '<div class="info">';
2003 echo '<div class="name">';
2004 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2005 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2006 . s($host['name']).'</a> - ';
2007 echo $host['count'] . ' ' . get_string('courses');
2014 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2016 function add_course_module($mod) {
2019 $mod->added
= time();
2022 $cmid = $DB->insert_record("course_modules", $mod);
2023 rebuild_course_cache($mod->course
, true);
2028 * Creates missing course section(s) and rebuilds course cache
2030 * @param int|stdClass $courseorid course id or course object
2031 * @param int|array $sections list of relative section numbers to create
2032 * @return bool if there were any sections created
2034 function course_create_sections_if_missing($courseorid, $sections) {
2036 if (!is_array($sections)) {
2037 $sections = array($sections);
2039 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
2040 if (is_object($courseorid)) {
2041 $courseorid = $courseorid->id
;
2043 $coursechanged = false;
2044 foreach ($sections as $sectionnum) {
2045 if (!in_array($sectionnum, $existing)) {
2046 $cw = new stdClass();
2047 $cw->course
= $courseorid;
2048 $cw->section
= $sectionnum;
2050 $cw->summaryformat
= FORMAT_HTML
;
2052 $id = $DB->insert_record("course_sections", $cw);
2053 $coursechanged = true;
2056 if ($coursechanged) {
2057 rebuild_course_cache($courseorid, true);
2059 return $coursechanged;
2063 * Adds an existing module to the section
2065 * Updates both tables {course_sections} and {course_modules}
2067 * @param int|stdClass $courseorid course id or course object
2068 * @param int $cmid id of the module already existing in course_modules table
2069 * @param int $sectionnum relative number of the section (field course_sections.section)
2070 * If section does not exist it will be created
2071 * @param int|stdClass $beforemod id or object with field id corresponding to the module
2072 * before which the module needs to be included. Null for inserting in the
2073 * end of the section
2074 * @return int The course_sections ID where the module is inserted
2076 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
2077 global $DB, $COURSE;
2078 if (is_object($beforemod)) {
2079 $beforemod = $beforemod->id
;
2081 if (is_object($courseorid)) {
2082 $courseid = $courseorid->id
;
2084 $courseid = $courseorid;
2086 course_create_sections_if_missing($courseorid, $sectionnum);
2087 // Do not try to use modinfo here, there is no guarantee it is valid!
2088 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST
);
2089 $modarray = explode(",", trim($section->sequence
));
2090 if (empty($section->sequence
)) {
2091 $newsequence = "$cmid";
2092 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
2093 $insertarray = array($cmid, $beforemod);
2094 array_splice($modarray, $key[0], 1, $insertarray);
2095 $newsequence = implode(",", $modarray);
2097 $newsequence = "$section->sequence,$cmid";
2099 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id
));
2100 $DB->set_field('course_modules', 'section', $section->id
, array('id' => $cmid));
2101 if (is_object($courseorid)) {
2102 rebuild_course_cache($courseorid->id
, true);
2104 rebuild_course_cache($courseorid, true);
2106 return $section->id
; // Return course_sections ID that was used.
2109 function set_coursemodule_groupmode($id, $groupmode) {
2111 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST
);
2112 if ($cm->groupmode
!= $groupmode) {
2113 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id
));
2114 rebuild_course_cache($cm->course
, true);
2116 return ($cm->groupmode
!= $groupmode);
2119 function set_coursemodule_idnumber($id, $idnumber) {
2121 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST
);
2122 if ($cm->idnumber
!= $idnumber) {
2123 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id
));
2124 rebuild_course_cache($cm->course
, true);
2126 return ($cm->idnumber
!= $idnumber);
2130 * Set the visibility of a module and inherent properties.
2132 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
2133 * has been moved to {@link set_section_visible()} which was the only place from which
2134 * the parameter was used.
2136 * @param int $id of the module
2137 * @param int $visible state of the module
2138 * @return bool false when the module was not found, true otherwise
2140 function set_coursemodule_visible($id, $visible) {
2142 require_once($CFG->libdir
.'/gradelib.php');
2144 // Trigger developer's attention when using the previously removed argument.
2145 if (func_num_args() > 2) {
2146 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
2147 has been removed.', DEBUG_DEVELOPER
);
2150 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2154 // Create events and propagate visibility to associated grade items if the value has changed.
2155 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
2156 if ($cm->visible
== $visible) {
2160 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module
))) {
2163 if ($events = $DB->get_records('event', array('instance'=>$cm->instance
, 'modulename'=>$modulename))) {
2164 foreach($events as $event) {
2173 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
2174 $grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
));
2176 foreach ($grade_items as $grade_item) {
2177 $grade_item->set_hidden(!$visible);
2181 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
2182 // affect visibleold to allow for an original visibility restore. See set_section_visible().
2183 $cminfo = new stdClass();
2185 $cminfo->visible
= $visible;
2186 $cminfo->visibleold
= $visible;
2187 $DB->update_record('course_modules', $cminfo);
2189 rebuild_course_cache($cm->course
, true);
2194 * This function will handles the whole deletion process of a module. This includes calling
2195 * the modules delete_instance function, deleting files, events, grades, conditional data,
2196 * the data in the course_module and course_sections table and adding a module deletion
2199 * @param int $cmid the course module id
2202 function course_delete_module($cmid) {
2203 global $CFG, $DB, $USER;
2205 require_once($CFG->libdir
.'/gradelib.php');
2206 require_once($CFG->dirroot
.'/blog/lib.php');
2208 // Get the course module.
2209 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
2213 // Get the module context.
2214 $modcontext = context_module
::instance($cm->id
);
2216 // Get the course module name.
2217 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module
), MUST_EXIST
);
2219 // Get the file location of the delete_instance function for this module.
2220 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
2222 // Include the file required to call the delete_instance function for this module.
2223 if (file_exists($modlib)) {
2224 require_once($modlib);
2226 throw new moodle_exception("This module is missing mod/$modulename/lib.php", '', '',
2227 null, 'failedtodeletemodulemissinglibfile');
2230 $deleteinstancefunction = $modulename . "_delete_instance";
2232 if (!$deleteinstancefunction($cm->instance
)) {
2233 throw new moodle_exception("Could not delete the $modulename (instance)", '', '',
2234 null, 'failedtodeletemoduleinstance');
2237 // Remove all module files in case modules forget to do that.
2238 $fs = get_file_storage();
2239 $fs->delete_area_files($modcontext->id
);
2241 // Delete events from calendar.
2242 if ($events = $DB->get_records('event', array('instance' => $cm->instance
, 'modulename' => $modulename))) {
2243 foreach($events as $event) {
2244 delete_event($event->id
);
2248 // Delete grade items, outcome items and grades attached to modules.
2249 if ($grade_items = grade_item
::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
2250 'iteminstance' => $cm->instance
, 'courseid' => $cm->course
))) {
2251 foreach ($grade_items as $grade_item) {
2252 $grade_item->delete('moddelete');
2256 // Delete completion and availability data; it is better to do this even if the
2257 // features are not turned on, in case they were turned on previously (these will be
2258 // very quick on an empty table).
2259 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id
));
2260 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id
));
2261 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id
));
2262 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id
,
2263 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY
));
2265 // Delete the context.
2266 delete_context(CONTEXT_MODULE
, $cm->id
);
2268 // Delete the module from the course_modules table.
2269 $DB->delete_records('course_modules', array('id' => $cm->id
));
2271 // Delete module from that section.
2272 if (!delete_mod_from_section($cm->id
, $cm->section
)) {
2273 throw new moodle_exception("Could not delete the $modulename from section", '', '',
2274 null, 'failedtodeletemodulefromsection');
2277 // Trigger a mod_deleted event with information about this module.
2278 $eventdata = new stdClass();
2279 $eventdata->modulename
= $modulename;
2280 $eventdata->cmid
= $cm->id
;
2281 $eventdata->courseid
= $cm->course
;
2282 $eventdata->userid
= $USER->id
;
2283 events_trigger('mod_deleted', $eventdata);
2285 add_to_log($cm->course
, 'course', "delete mod",
2286 "view.php?id=$cm->course",
2287 "$modulename $cm->instance", $cm->id
);
2289 rebuild_course_cache($cm->course
, true);
2292 function delete_mod_from_section($modid, $sectionid) {
2295 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
2297 $modarray = explode(",", $section->sequence
);
2299 if ($key = array_keys ($modarray, $modid)) {
2300 array_splice($modarray, $key[0], 1);
2301 $newsequence = implode(",", $modarray);
2302 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id
));
2303 rebuild_course_cache($section->course
, true);
2314 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2316 * @param object $course course object
2317 * @param int $section Section number (not id!!!)
2318 * @param int $move (-1 or 1)
2319 * @return boolean true if section moved successfully
2320 * @todo MDL-33379 remove this function in 2.5
2322 function move_section($course, $section, $move) {
2323 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER
);
2325 /// Moves a whole course section up and down within the course
2332 $sectiondest = $section +
$move;
2334 // compartibility with course formats using field 'numsections'
2335 $courseformatoptions = course_get_format($course)->get_format_options();
2336 if (array_key_exists('numsections', $courseformatoptions) &&
2337 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
2341 $retval = move_section_to($course, $section, $sectiondest);
2346 * Moves a section within a course, from a position to another.
2347 * Be very careful: $section and $destination refer to section number,
2350 * @param object $course
2351 * @param int $section Section number (not id!!!)
2352 * @param int $destination
2353 * @return boolean Result
2355 function move_section_to($course, $section, $destination) {
2356 /// Moves a whole course section up and down within the course
2359 if (!$destination && $destination != 0) {
2363 // compartibility with course formats using field 'numsections'
2364 $courseformatoptions = course_get_format($course)->get_format_options();
2365 if ((array_key_exists('numsections', $courseformatoptions) &&
2366 ($destination > $courseformatoptions['numsections'])) ||
($destination < 1)) {
2370 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2371 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id
),
2372 'section ASC, id ASC', 'id, section')) {
2376 $movedsections = reorder_sections($sections, $section, $destination);
2378 // Update all sections. Do this in 2 steps to avoid breaking database
2379 // uniqueness constraint
2380 $transaction = $DB->start_delegated_transaction();
2381 foreach ($movedsections as $id => $position) {
2382 if ($sections[$id] !== $position) {
2383 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
2386 foreach ($movedsections as $id => $position) {
2387 if ($sections[$id] !== $position) {
2388 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2392 // If we move the highlighted section itself, then just highlight the destination.
2393 // Adjust the higlighted section location if we move something over it either direction.
2394 if ($section == $course->marker
) {
2395 course_set_marker($course->id
, $destination);
2396 } elseif ($section > $course->marker
&& $course->marker
>= $destination) {
2397 course_set_marker($course->id
, $course->marker+
1);
2398 } elseif ($section < $course->marker
&& $course->marker
<= $destination) {
2399 course_set_marker($course->id
, $course->marker
-1);
2402 $transaction->allow_commit();
2403 rebuild_course_cache($course->id
, true);
2408 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2409 * an original position number and a target position number, rebuilds the array so that the
2410 * move is made without any duplication of section positions.
2411 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2412 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2414 * @param array $sections
2415 * @param int $origin_position
2416 * @param int $target_position
2419 function reorder_sections($sections, $origin_position, $target_position) {
2420 if (!is_array($sections)) {
2424 // We can't move section position 0
2425 if ($origin_position < 1) {
2426 echo "We can't move section position 0";
2430 // Locate origin section in sections array
2431 if (!$origin_key = array_search($origin_position, $sections)) {
2432 echo "searched position not in sections array";
2433 return false; // searched position not in sections array
2436 // Extract origin section
2437 $origin_section = $sections[$origin_key];
2438 unset($sections[$origin_key]);
2440 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2442 $append_array = array();
2443 foreach ($sections as $id => $position) {
2445 $append_array[$id] = $position;
2446 unset($sections[$id]);
2448 if ($position == $target_position) {
2449 if ($target_position < $origin_position) {
2450 $append_array[$id] = $position;
2451 unset($sections[$id]);
2457 // Append moved section
2458 $sections[$origin_key] = $origin_section;
2460 // Append rest of array (if applicable)
2461 if (!empty($append_array)) {
2462 foreach ($append_array as $id => $position) {
2463 $sections[$id] = $position;
2467 // Renumber positions
2469 foreach ($sections as $id => $p) {
2470 $sections[$id] = $position;
2479 * Move the module object $mod to the specified $section
2480 * If $beforemod exists then that is the module
2481 * before which $modid should be inserted
2482 * All parameters are objects
2484 function moveto_module($mod, $section, $beforemod=NULL) {
2485 global $OUTPUT, $DB;
2487 /// Remove original module from original section
2488 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2489 echo $OUTPUT->notification("Could not delete module from existing section");
2492 // if moving to a hidden section then hide module
2493 if (!$section->visible
&& $mod->visible
) {
2494 // Set this in the object because it is sent as a response to ajax calls.
2496 set_coursemodule_visible($mod->id
, 0);
2497 // Set visibleold to 1 so module will be visible when section is made visible.
2498 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id
));
2500 if ($section->visible
&& !$mod->visible
) {
2501 set_coursemodule_visible($mod->id
, $mod->visibleold
);
2502 // Set this in the object because it is sent as a response to ajax calls.
2503 $mod->visible
= $mod->visibleold
;
2506 /// Add the module into the new section
2507 course_add_cm_to_section($section->course
, $mod->id
, $section->section
, $beforemod);
2512 * Returns the list of all editing actions that current user can perform on the module
2514 * @param cm_info $mod The module to produce editing buttons for
2515 * @param int $indent The current indenting (default -1 means no move left-right actions)
2516 * @param int $sr The section to link back to (used for creating the links)
2517 * @return array array of action_link or pix_icon objects
2519 function course_get_cm_edit_actions(cm_info
$mod, $indent = -1, $sr = null) {
2520 global $COURSE, $SITE;
2524 $coursecontext = context_course
::instance($mod->course
);
2525 $modcontext = context_module
::instance($mod->id
);
2527 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
2528 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
2530 // no permission to edit anything
2531 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
2535 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2538 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
2539 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
2540 $str->assign
= get_string('assignroles', 'role');
2541 $str->groupsnone
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
2542 $str->groupsseparate
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
2543 $str->groupsvisible
= get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
2544 $str->forcedgroupsnone
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
2545 $str->forcedgroupsseparate
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
2546 $str->forcedgroupsvisible
= get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
2549 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2552 $baseurl->param('sr', $sr);
2557 if ($mod->modname
!== 'label' && $hasmanageactivities &&
2558 (($mod->course
== $COURSE->id
&& course_ajax_enabled($COURSE)) ||
2559 ($mod->course
== SITEID
&& course_ajax_enabled($SITE)))) {
2560 // we will not display link if we are on some other-course page (where we should not see this module anyway)
2561 $actions['title'] = new action_link(
2562 new moodle_url($baseurl, array('update' => $mod->id
)),
2563 new pix_icon('t/editstring', $str->edittitle
, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
2565 array('class' => 'editing_title', 'title' => $str->edittitle
)
2570 if ($hasmanageactivities) {
2571 if (right_to_left()) { // Exchange arrows on RTL
2572 $rightarrow = 't/left';
2573 $leftarrow = 't/right';
2575 $rightarrow = 't/right';
2576 $leftarrow = 't/left';
2580 $actions['moveleft'] = new action_link(
2581 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '-1')),
2582 new pix_icon($leftarrow, $str->moveleft
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2584 array('class' => 'editing_moveleft', 'title' => $str->moveleft
)
2588 $actions['moveright'] = new action_link(
2589 new moodle_url($baseurl, array('id' => $mod->id
, 'indent' => '1')),
2590 new pix_icon($rightarrow, $str->moveright
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2592 array('class' => 'editing_moveright', 'title' => $str->moveright
)
2598 if ($hasmanageactivities) {
2599 $actions['move'] = new action_link(
2600 new moodle_url($baseurl, array('copy' => $mod->id
)),
2601 new pix_icon('t/move', $str->move
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2603 array('class' => 'editing_move', 'title' => $str->move
)
2608 if ($hasmanageactivities) {
2609 $actions['update'] = new action_link(
2610 new moodle_url($baseurl, array('update' => $mod->id
)),
2611 new pix_icon('t/edit', $str->update
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2613 array('class' => 'editing_update', 'title' => $str->update
)
2617 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
2618 // note that restoring on front page is never allowed
2619 if ($mod->course
!= SITEID
&& has_all_capabilities($dupecaps, $coursecontext) &&
2620 plugin_supports('mod', $mod->modname
, FEATURE_BACKUP_MOODLE2
)) {
2621 $actions['duplicate'] = new action_link(
2622 new moodle_url($baseurl, array('duplicate' => $mod->id
)),
2623 new pix_icon('t/copy', $str->duplicate
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2625 array('class' => 'editing_duplicate', 'title' => $str->duplicate
)
2630 if ($hasmanageactivities) {
2631 $actions['delete'] = new action_link(
2632 new moodle_url($baseurl, array('delete' => $mod->id
)),
2633 new pix_icon('t/delete', $str->delete
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2635 array('class' => 'editing_delete', 'title' => $str->delete
)
2640 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2641 if ($mod->visible
) {
2642 $actions['hide'] = new action_link(
2643 new moodle_url($baseurl, array('hide' => $mod->id
)),
2644 new pix_icon('t/hide', $str->hide
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2646 array('class' => 'editing_hide', 'title' => $str->hide
)
2649 $actions['show'] = new action_link(
2650 new moodle_url($baseurl, array('show' => $mod->id
)),
2651 new pix_icon('t/show', $str->show
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2653 array('class' => 'editing_show', 'title' => $str->show
)
2659 if ($hasmanageactivities and plugin_supports('mod', $mod->modname
, FEATURE_GROUPS
, 0)) {
2660 if ($mod->coursegroupmodeforce
) {
2661 $modgroupmode = $mod->coursegroupmode
;
2663 $modgroupmode = $mod->groupmode
;
2665 if ($modgroupmode == SEPARATEGROUPS
) {
2666 $groupmode = NOGROUPS
;
2667 $grouptitle = $str->groupsseparate
;
2668 $forcedgrouptitle = $str->forcedgroupsseparate
;
2669 $actionname = 'groupsseparate';
2670 $groupimage = 't/groups';
2671 } else if ($modgroupmode == VISIBLEGROUPS
) {
2672 $groupmode = SEPARATEGROUPS
;
2673 $grouptitle = $str->groupsvisible
;
2674 $forcedgrouptitle = $str->forcedgroupsvisible
;
2675 $actionname = 'groupsvisible';
2676 $groupimage = 't/groupv';
2678 $groupmode = VISIBLEGROUPS
;
2679 $grouptitle = $str->groupsnone
;
2680 $forcedgrouptitle = $str->forcedgroupsnone
;
2681 $actionname = 'groupsnone';
2682 $groupimage = 't/groupn';
2684 if (!$mod->coursegroupmodeforce
) {
2685 $actions[$actionname] = new action_link(
2686 new moodle_url($baseurl, array('id' => $mod->id
, 'groupmode' => $groupmode)),
2687 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2689 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
2692 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
2697 if (has_capability('moodle/role:assign', $modcontext)){
2698 $actions['assign'] = new action_link(
2699 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id
)),
2700 new pix_icon('t/assignroles', $str->assign
, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2702 array('class' => 'editing_assign', 'title' => $str->assign
)
2710 * given a course object with shortname & fullname, this function will
2711 * truncate the the number of chars allowed and add ... if it was too long
2713 function course_format_name ($course,$max=100) {
2715 $context = context_course
::instance($course->id
);
2716 $shortname = format_string($course->shortname
, true, array('context' => $context));
2717 $fullname = format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
2718 $str = $shortname.': '. $fullname;
2719 if (textlib
::strlen($str) <= $max) {
2723 return textlib
::substr($str,0,$max-3).'...';
2728 * Is the user allowed to add this type of module to this course?
2729 * @param object $course the course settings. Only $course->id is used.
2730 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2731 * @return bool whether the current user is allowed to add this type of module to this course.
2733 function course_allowed_module($course, $modname) {
2734 if (is_numeric($modname)) {
2735 throw new coding_exception('Function course_allowed_module no longer
2736 supports numeric module ids. Please update your code to pass the module name.');
2739 $capability = 'mod/' . $modname . ':addinstance';
2740 if (!get_capability_info($capability)) {
2741 // Debug warning that the capability does not exist, but no more than once per page.
2742 static $warned = array();
2743 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE
, MOD_ARCHETYPE_OTHER
);
2744 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM
) {
2745 debugging('The module ' . $modname . ' does not define the standard capability ' .
2746 $capability , DEBUG_DEVELOPER
);
2747 $warned[$modname] = 1;
2750 // If the capability does not exist, the module can always be added.
2754 $coursecontext = context_course
::instance($course->id
);
2755 return has_capability($capability, $coursecontext);
2759 * Recursively delete category including all subcategories and courses.
2760 * @param stdClass $category
2761 * @param boolean $showfeedback display some notices
2762 * @return array return deleted courses
2764 function category_delete_full($category, $showfeedback=true) {
2766 require_once($CFG->libdir
.'/gradelib.php');
2767 require_once($CFG->libdir
.'/questionlib.php');
2768 require_once($CFG->dirroot
.'/cohort/lib.php');
2770 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
2771 foreach ($children as $childcat) {
2772 category_delete_full($childcat, $showfeedback);
2776 $deletedcourses = array();
2777 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC')) {
2778 foreach ($courses as $course) {
2779 if (!delete_course($course, false)) {
2780 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname
);
2782 $deletedcourses[] = $course;
2786 // move or delete cohorts in this context
2787 cohort_delete_category($category);
2789 // now delete anything that may depend on course category context
2790 grade_course_category_delete($category->id
, 0, $showfeedback);
2791 if (!question_delete_course_category($category, 0, $showfeedback)) {
2792 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name
);
2795 // finally delete the category and it's context
2796 $DB->delete_records('course_categories', array('id'=>$category->id
));
2797 delete_context(CONTEXT_COURSECAT
, $category->id
);
2798 add_to_log(SITEID
, "category", "delete", "index.php", "$category->name (ID $category->id)");
2800 events_trigger('course_category_deleted', $category);
2802 return $deletedcourses;
2806 * Delete category, but move contents to another category.
2807 * @param object $ccategory
2808 * @param int $newparentid category id
2809 * @return bool status
2811 function category_delete_move($category, $newparentid, $showfeedback=true) {
2812 global $CFG, $DB, $OUTPUT;
2813 require_once($CFG->libdir
.'/gradelib.php');
2814 require_once($CFG->libdir
.'/questionlib.php');
2815 require_once($CFG->dirroot
.'/cohort/lib.php');
2817 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
2821 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id
), 'sortorder ASC')) {
2822 foreach ($children as $childcat) {
2823 move_category($childcat, $newparentcat);
2827 if ($courses = $DB->get_records('course', array('category'=>$category->id
), 'sortorder ASC', 'id')) {
2828 if (!move_courses(array_keys($courses), $newparentid)) {
2829 if ($showfeedback) {
2830 echo $OUTPUT->notification("Error moving courses");
2834 if ($showfeedback) {
2835 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
2839 // move or delete cohorts in this context
2840 cohort_delete_category($category);
2842 // now delete anything that may depend on course category context
2843 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
2844 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
2845 if ($showfeedback) {
2846 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2851 // finally delete the category and it's context
2852 $DB->delete_records('course_categories', array('id'=>$category->id
));
2853 delete_context(CONTEXT_COURSECAT
, $category->id
);
2854 add_to_log(SITEID
, "category", "delete", "index.php", "$category->name (ID $category->id)");
2856 events_trigger('course_category_deleted', $category);
2858 if ($showfeedback) {
2859 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
2865 * Efficiently moves many courses around while maintaining
2866 * sortorder in order.
2868 * @param array $courseids is an array of course ids
2869 * @param int $categoryid
2870 * @return bool success
2872 function move_courses($courseids, $categoryid) {
2873 global $CFG, $DB, $OUTPUT;
2875 if (empty($courseids)) {
2880 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2884 $courseids = array_reverse($courseids);
2885 $newparent = context_coursecat
::instance($category->id
);
2888 foreach ($courseids as $courseid) {
2889 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2890 $course = new stdClass();
2891 $course->id
= $courseid;
2892 $course->category
= $category->id
;
2893 $course->sortorder
= $category->sortorder + MAX_COURSES_IN_CATEGORY
- $i++
;
2894 if ($category->visible
== 0) {
2895 // hide the course when moving into hidden category,
2896 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2897 $course->visible
= 0;
2900 $DB->update_record('course', $course);
2901 add_to_log($course->id
, "course", "move", "edit.php?id=$course->id", $course->id
);
2903 $context = context_course
::instance($course->id
);
2904 context_moved($context, $newparent);
2907 fix_course_sortorder();
2913 * Hide course category and child course and subcategories
2914 * @param stdClass $category
2917 function course_category_hide($category) {
2920 $category->visible
= 0;
2921 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id
));
2922 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id
));
2923 $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
2924 $DB->set_field('course', 'visible', 0, array('category' => $category->id
));
2925 // get all child categories and hide too
2926 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
2927 foreach ($subcats as $cat) {
2928 $DB->set_field('course_categories', 'visibleold', $cat->visible
, array('id'=>$cat->id
));
2929 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id
));
2930 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id
));
2931 $DB->set_field('course', 'visible', 0, array('category' => $cat->id
));
2934 add_to_log(SITEID
, "category", "hide", "editcategory.php?id=$category->id", $category->id
);
2938 * Show course category and child course and subcategories
2939 * @param stdClass $category
2942 function course_category_show($category) {
2945 $category->visible
= 1;
2946 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id
));
2947 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id
));
2948 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id
));
2949 // get all child categories and unhide too
2950 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
2951 foreach ($subcats as $cat) {
2952 if ($cat->visibleold
) {
2953 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id
));
2955 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id
));
2958 add_to_log(SITEID
, "category", "show", "editcategory.php?id=$category->id", $category->id
);
2962 * Efficiently moves a category - NOTE that this can have
2963 * a huge impact access-control-wise...
2965 function move_category($category, $newparentcat) {
2968 $context = context_coursecat
::instance($category->id
);
2971 if (empty($newparentcat->id
)) {
2972 $DB->set_field('course_categories', 'parent', 0, array('id' => $category->id
));
2973 $newparent = context_system
::instance();
2975 $DB->set_field('course_categories', 'parent', $newparentcat->id
, array('id' => $category->id
));
2976 $newparent = context_coursecat
::instance($newparentcat->id
);
2978 if (!$newparentcat->visible
and $category->visible
) {
2979 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
2984 context_moved($context, $newparent);
2986 // now make it last in new category
2987 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('id'=>$category->id
));
2990 add_to_log(SITEID
, "category", "move", "editcategory.php?id=$category->id", $category->id
);
2992 // and fix the sortorders
2993 fix_course_sortorder();
2996 course_category_hide($category);
3001 * Returns the display name of the given section that the course prefers
3003 * Implementation of this function is provided by course format
3004 * @see format_base::get_section_name()
3006 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
3007 * @param int|stdClass $section Section object from database or just field course_sections.section
3008 * @return string Display name that the course format prefers, e.g. "Week 2"
3010 function get_section_name($courseorid, $section) {
3011 return course_get_format($courseorid)->get_section_name($section);
3015 * Tells if current course format uses sections
3017 * @param string $format Course format ID e.g. 'weeks' $course->format
3020 function course_format_uses_sections($format) {
3021 $course = new stdClass();
3022 $course->format
= $format;
3023 return course_get_format($course)->uses_sections();
3027 * Returns the information about the ajax support in the given source format
3029 * The returned object's property (boolean)capable indicates that
3030 * the course format supports Moodle course ajax features.
3031 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3033 * @param string $format
3036 function course_format_ajax_support($format) {
3037 $course = new stdClass();
3038 $course->format
= $format;
3039 return course_get_format($course)->supports_ajax();
3043 * Can the current user delete this course?
3044 * Course creators have exception,
3045 * 1 day after the creation they can sill delete the course.
3046 * @param int $courseid
3049 function can_delete_course($courseid) {
3052 $context = context_course
::instance($courseid);
3054 if (has_capability('moodle/course:delete', $context)) {
3058 // hack: now try to find out if creator created this course recently (1 day)
3059 if (!has_capability('moodle/course:create', $context)) {
3063 $since = time() - 60*60*24;
3065 $params = array('userid'=>$USER->id
, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3066 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3068 return $DB->record_exists_select('log', $select, $params);
3072 * Save the Your name for 'Some role' strings.
3074 * @param integer $courseid the id of this course.
3075 * @param array $data the data that came from the course settings form.
3077 function save_local_role_names($courseid, $data) {
3079 $context = context_course
::instance($courseid);
3081 foreach ($data as $fieldname => $value) {
3082 if (strpos($fieldname, 'role_') !== 0) {
3085 list($ignored, $roleid) = explode('_', $fieldname);
3087 // make up our mind whether we want to delete, update or insert
3089 $DB->delete_records('role_names', array('contextid' => $context->id
, 'roleid' => $roleid));
3091 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id
, 'roleid' => $roleid))) {
3092 $rolename->name
= $value;
3093 $DB->update_record('role_names', $rolename);
3096 $rolename = new stdClass
;
3097 $rolename->contextid
= $context->id
;
3098 $rolename->roleid
= $roleid;
3099 $rolename->name
= $value;
3100 $DB->insert_record('role_names', $rolename);
3106 * Create a course and either return a $course object
3108 * Please note this functions does not verify any access control,
3109 * the calling code is responsible for all validation (usually it is the form definition).
3111 * @param array $editoroptions course description editor options
3112 * @param object $data - all the data needed for an entry in the 'course' table
3113 * @return object new course instance
3115 function create_course($data, $editoroptions = NULL) {
3118 //check the categoryid - must be given for all new courses
3119 $category = $DB->get_record('course_categories', array('id'=>$data->category
), '*', MUST_EXIST
);
3121 //check if the shortname already exist
3122 if (!empty($data->shortname
)) {
3123 if ($DB->record_exists('course', array('shortname' => $data->shortname
))) {
3124 throw new moodle_exception('shortnametaken');
3128 //check if the id number already exist
3129 if (!empty($data->idnumber
)) {
3130 if ($DB->record_exists('course', array('idnumber' => $data->idnumber
))) {
3131 throw new moodle_exception('idnumbertaken');
3135 $data->timecreated
= time();
3136 $data->timemodified
= $data->timecreated
;
3138 // place at beginning of any category
3139 $data->sortorder
= 0;
3141 if ($editoroptions) {
3142 // summary text is updated later, we need context to store the files first
3143 $data->summary
= '';
3144 $data->summary_format
= FORMAT_HTML
;
3147 if (!isset($data->visible
)) {
3148 // data not from form, add missing visibility info
3149 $data->visible
= $category->visible
;
3151 $data->visibleold
= $data->visible
;
3153 $newcourseid = $DB->insert_record('course', $data);
3154 $context = context_course
::instance($newcourseid, MUST_EXIST
);
3156 if ($editoroptions) {
3157 // Save the files used in the summary editor and store
3158 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3159 $DB->set_field('course', 'summary', $data->summary
, array('id'=>$newcourseid));
3160 $DB->set_field('course', 'summaryformat', $data->summary_format
, array('id'=>$newcourseid));
3163 // update course format options
3164 course_get_format($newcourseid)->update_course_format_options($data);
3166 $course = course_get_format($newcourseid)->get_course();
3169 blocks_add_default_course_blocks($course);
3171 // Create a default section.
3172 course_create_sections_if_missing($course, 0);
3174 fix_course_sortorder();
3176 // new context created - better mark it as dirty
3177 mark_context_dirty($context->path
);
3179 // Save any custom role names.
3180 save_local_role_names($course->id
, (array)$data);
3182 // set up enrolments
3183 enrol_course_updated(true, $course, $data);
3185 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3188 events_trigger('course_created', $course);
3194 * Create a new course category and marks the context as dirty
3196 * This function does not set the sortorder for the new category and
3197 * @see{fix_course_sortorder} should be called after creating a new course
3200 * Please note that this function does not verify access control.
3202 * @param object $category All of the data required for an entry in the course_categories table
3203 * @return object new course category
3205 function create_course_category($category) {
3208 $category->timemodified
= time();
3209 $category->id
= $DB->insert_record('course_categories', $category);
3210 $category = $DB->get_record('course_categories', array('id' => $category->id
));
3212 // We should mark the context as dirty
3213 $category->context
= context_coursecat
::instance($category->id
);
3214 $category->context
->mark_dirty();
3222 * Please note this functions does not verify any access control,
3223 * the calling code is responsible for all validation (usually it is the form definition).
3225 * @param object $data - all the data needed for an entry in the 'course' table
3226 * @param array $editoroptions course description editor options
3229 function update_course($data, $editoroptions = NULL) {
3232 $data->timemodified
= time();
3234 $oldcourse = course_get_format($data->id
)->get_course();
3235 $context = context_course
::instance($oldcourse->id
);
3237 if ($editoroptions) {
3238 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3241 if (!isset($data->category
) or empty($data->category
)) {
3242 // prevent nulls and 0 in category field
3243 unset($data->category
);
3245 $movecat = (isset($data->category
) and $oldcourse->category
!= $data->category
);
3247 if (!isset($data->visible
)) {
3248 // data not from form, add missing visibility info
3249 $data->visible
= $oldcourse->visible
;
3252 if ($data->visible
!= $oldcourse->visible
) {
3253 // reset the visibleold flag when manually hiding/unhiding course
3254 $data->visibleold
= $data->visible
;
3257 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category
));
3258 if (empty($newcategory->visible
)) {
3259 // make sure when moving into hidden category the course is hidden automatically
3265 // Update with the new data
3266 $DB->update_record('course', $data);
3267 // make sure the modinfo cache is reset
3268 rebuild_course_cache($data->id
);
3270 // update course format options with full course data
3271 course_get_format($data->id
)->update_course_format_options($data, $oldcourse);
3273 $course = $DB->get_record('course', array('id'=>$data->id
));
3276 $newparent = context_coursecat
::instance($course->category
);
3277 context_moved($context, $newparent);
3280 fix_course_sortorder();
3282 // Test for and remove blocks which aren't appropriate anymore
3283 blocks_remove_inappropriate($course);
3285 // Save any custom role names.
3286 save_local_role_names($course->id
, $data);
3288 // update enrol settings
3289 enrol_course_updated(false, $course, $data);
3291 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3294 events_trigger('course_updated', $course);
3296 if ($oldcourse->format
!== $course->format
) {
3297 // Remove all options stored for the previous format
3298 // We assume that new course format migrated everything it needed watching trigger
3299 // 'course_updated' and in method format_XXX::update_course_format_options()
3300 $DB->delete_records('course_format_options',
3301 array('courseid' => $course->id
, 'format' => $oldcourse->format
));
3306 * Average number of participants
3309 function average_number_of_participants() {
3312 //count total of enrolments for visible course (except front page)
3313 $sql = 'SELECT COUNT(*) FROM (
3314 SELECT DISTINCT ue.userid, e.courseid
3315 FROM {user_enrolments} ue, {enrol} e, {course} c
3316 WHERE ue.enrolid = e.id
3317 AND e.courseid <> :siteid
3318 AND c.id = e.courseid
3319 AND c.visible = 1) total';
3320 $params = array('siteid' => $SITE->id
);
3321 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3324 //count total of visible courses (minus front page)
3325 $coursetotal = $DB->count_records('course', array('visible' => 1));
3326 $coursetotal = $coursetotal - 1 ;
3328 //average of enrolment
3329 if (empty($coursetotal)) {
3330 $participantaverage = 0;
3332 $participantaverage = $enrolmenttotal / $coursetotal;
3335 return $participantaverage;
3339 * Average number of course modules
3342 function average_number_of_courses_modules() {
3345 //count total of visible course module (except front page)
3346 $sql = 'SELECT COUNT(*) FROM (
3347 SELECT cm.course, cm.module
3348 FROM {course} c, {course_modules} cm
3349 WHERE c.id = cm.course
3352 AND c.visible = 1) total';
3353 $params = array('siteid' => $SITE->id
);
3354 $moduletotal = $DB->count_records_sql($sql, $params);
3357 //count total of visible courses (minus front page)
3358 $coursetotal = $DB->count_records('course', array('visible' => 1));
3359 $coursetotal = $coursetotal - 1 ;
3361 //average of course module
3362 if (empty($coursetotal)) {
3363 $coursemoduleaverage = 0;
3365 $coursemoduleaverage = $moduletotal / $coursetotal;
3368 return $coursemoduleaverage;
3372 * This class pertains to course requests and contains methods associated with
3373 * create, approving, and removing course requests.
3375 * Please note we do not allow embedded images here because there is no context
3376 * to store them with proper access control.
3378 * @copyright 2009 Sam Hemelryk
3379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3382 * @property-read int $id
3383 * @property-read string $fullname
3384 * @property-read string $shortname
3385 * @property-read string $summary
3386 * @property-read int $summaryformat
3387 * @property-read int $summarytrust
3388 * @property-read string $reason
3389 * @property-read int $requester
3391 class course_request
{
3394 * This is the stdClass that stores the properties for the course request
3395 * and is externally accessed through the __get magic method
3398 protected $properties;
3401 * An array of options for the summary editor used by course request forms.
3402 * This is initially set by {@link summary_editor_options()}
3406 protected static $summaryeditoroptions;
3409 * Static function to prepare the summary editor for working with a course
3413 * @param null|stdClass $data Optional, an object containing the default values
3414 * for the form, these may be modified when preparing the
3415 * editor so this should be called before creating the form
3416 * @return stdClass An object that can be used to set the default values for
3419 public static function prepare($data=null) {
3420 if ($data === null) {
3421 $data = new stdClass
;
3423 $data = file_prepare_standard_editor($data, 'summary', self
::summary_editor_options());
3428 * Static function to create a new course request when passed an array of properties
3431 * This function also handles saving any files that may have been used in the editor
3434 * @param stdClass $data
3435 * @return course_request The newly created course request
3437 public static function create($data) {
3438 global $USER, $DB, $CFG;
3439 $data->requester
= $USER->id
;
3441 // Setting the default category if none set.
3442 if (empty($data->category
) ||
empty($CFG->requestcategoryselection
)) {
3443 $data->category
= $CFG->defaultrequestcategory
;
3446 // Summary is a required field so copy the text over
3447 $data->summary
= $data->summary_editor
['text'];
3448 $data->summaryformat
= $data->summary_editor
['format'];
3450 $data->id
= $DB->insert_record('course_request', $data);
3452 // Create a new course_request object and return it
3453 $request = new course_request($data);
3455 // Notify the admin if required.
3456 if ($users = get_users_from_config($CFG->courserequestnotify
, 'moodle/site:approvecourse')) {
3459 $a->link
= "$CFG->wwwroot/course/pending.php";
3460 $a->user
= fullname($USER);
3461 $subject = get_string('courserequest');
3462 $message = get_string('courserequestnotifyemail', 'admin', $a);
3463 foreach ($users as $user) {
3464 $request->notify($user, $USER, 'courserequested', $subject, $message);
3472 * Returns an array of options to use with a summary editor
3474 * @uses course_request::$summaryeditoroptions
3475 * @return array An array of options to use with the editor
3477 public static function summary_editor_options() {
3479 if (self
::$summaryeditoroptions === null) {
3480 self
::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
3482 return self
::$summaryeditoroptions;
3486 * Loads the properties for this course request object. Id is required and if
3487 * only id is provided then we load the rest of the properties from the database
3489 * @param stdClass|int $properties Either an object containing properties
3490 * or the course_request id to load
3492 public function __construct($properties) {
3494 if (empty($properties->id
)) {
3495 if (empty($properties)) {
3496 throw new coding_exception('You must provide a course request id when creating a course_request object');
3499 $properties = new stdClass
;
3500 $properties->id
= (int)$id;
3503 if (empty($properties->requester
)) {
3504 if (!($this->properties
= $DB->get_record('course_request', array('id' => $properties->id
)))) {
3505 print_error('unknowncourserequest');
3508 $this->properties
= $properties;
3510 $this->properties
->collision
= null;
3514 * Returns the requested property
3516 * @param string $key
3519 public function __get($key) {
3520 return $this->properties
->$key;
3524 * Override this to ensure empty($request->blah) calls return a reliable answer...
3526 * This is required because we define the __get method
3529 * @return bool True is it not empty, false otherwise
3531 public function __isset($key) {
3532 return (!empty($this->properties
->$key));
3536 * Returns the user who requested this course
3538 * Uses a static var to cache the results and cut down the number of db queries
3540 * @staticvar array $requesters An array of cached users
3541 * @return stdClass The user who requested the course
3543 public function get_requester() {
3545 static $requesters= array();
3546 if (!array_key_exists($this->properties
->requester
, $requesters)) {
3547 $requesters[$this->properties
->requester
] = $DB->get_record('user', array('id'=>$this->properties
->requester
));
3549 return $requesters[$this->properties
->requester
];
3553 * Checks that the shortname used by the course does not conflict with any other
3554 * courses that exist
3556 * @param string|null $shortnamemark The string to append to the requests shortname
3557 * should a conflict be found
3558 * @return bool true is there is a conflict, false otherwise
3560 public function check_shortname_collision($shortnamemark = '[*]') {
3563 if ($this->properties
->collision
!== null) {
3564 return $this->properties
->collision
;
3567 if (empty($this->properties
->shortname
)) {
3568 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER
);
3569 $this->properties
->collision
= false;
3570 } else if ($DB->record_exists('course', array('shortname' => $this->properties
->shortname
))) {
3571 if (!empty($shortnamemark)) {
3572 $this->properties
->shortname
.= ' '.$shortnamemark;
3574 $this->properties
->collision
= true;
3576 $this->properties
->collision
= false;
3578 return $this->properties
->collision
;
3582 * This function approves the request turning it into a course
3584 * This function converts the course request into a course, at the same time
3585 * transferring any files used in the summary to the new course and then removing
3586 * the course request and the files associated with it.
3588 * @return int The id of the course that was created from this request
3590 public function approve() {
3591 global $CFG, $DB, $USER;
3593 $user = $DB->get_record('user', array('id' => $this->properties
->requester
, 'deleted'=>0), '*', MUST_EXIST
);
3595 $courseconfig = get_config('moodlecourse');
3597 // Transfer appropriate settings
3598 $data = clone($this->properties
);
3600 unset($data->reason
);
3601 unset($data->requester
);
3603 // If the category is not set, if the current user does not have the rights to change the category, or if the
3604 // category does not exist, we set the default category to the course to be approved.
3605 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
3606 if (empty($data->category
) ||
!has_capability('moodle/course:changecategory', context_system
::instance()) ||
3607 (!$category = get_course_category($data->category
))) {
3608 $category = get_course_category($CFG->defaultrequestcategory
);
3612 $data->category
= $category->id
;
3613 $data->sortorder
= $category->sortorder
; // place as the first in category
3615 // Set misc settings
3616 $data->requested
= 1;
3618 // Apply course default settings
3619 $data->format
= $courseconfig->format
;
3620 $data->newsitems
= $courseconfig->newsitems
;
3621 $data->showgrades
= $courseconfig->showgrades
;
3622 $data->showreports
= $courseconfig->showreports
;
3623 $data->maxbytes
= $courseconfig->maxbytes
;
3624 $data->groupmode
= $courseconfig->groupmode
;
3625 $data->groupmodeforce
= $courseconfig->groupmodeforce
;
3626 $data->visible
= $courseconfig->visible
;
3627 $data->visibleold
= $data->visible
;
3628 $data->lang
= $courseconfig->lang
;
3630 $course = create_course($data);
3631 $context = context_course
::instance($course->id
, MUST_EXIST
);
3633 // add enrol instances
3634 if (!$DB->record_exists('enrol', array('courseid'=>$course->id
, 'enrol'=>'manual'))) {
3635 if ($manual = enrol_get_plugin('manual')) {
3636 $manual->add_default_instance($course);
3640 // enrol the requester as teacher if necessary
3641 if (!empty($CFG->creatornewroleid
) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3642 enrol_try_internal_enrol($course->id
, $user->id
, $CFG->creatornewroleid
);
3647 $a = new stdClass();
3648 $a->name
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
3649 $a->url
= $CFG->wwwroot
.'/course/view.php?id=' . $course->id
;
3650 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3656 * Reject a course request
3658 * This function rejects a course request, emailing the requesting user the
3659 * provided notice and then removing the request from the database
3661 * @param string $notice The message to display to the user
3663 public function reject($notice) {
3665 $user = $DB->get_record('user', array('id' => $this->properties
->requester
), '*', MUST_EXIST
);
3666 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3671 * Deletes the course request and any associated files
3673 public function delete() {
3675 $DB->delete_records('course_request', array('id' => $this->properties
->id
));
3679 * Send a message from one user to another using events_trigger
3681 * @param object $touser
3682 * @param object $fromuser
3683 * @param string $name
3684 * @param string $subject
3685 * @param string $message
3687 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3688 $eventdata = new stdClass();
3689 $eventdata->component
= 'moodle';
3690 $eventdata->name
= $name;
3691 $eventdata->userfrom
= $fromuser;
3692 $eventdata->userto
= $touser;
3693 $eventdata->subject
= $subject;
3694 $eventdata->fullmessage
= $message;
3695 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
3696 $eventdata->fullmessagehtml
= '';
3697 $eventdata->smallmessage
= '';
3698 $eventdata->notification
= 1;
3699 message_send($eventdata);
3704 * Return a list of page types
3705 * @param string $pagetype current page type
3706 * @param stdClass $parentcontext Block's parent context
3707 * @param stdClass $currentcontext Current context of block
3709 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3710 // if above course context ,display all course fomats
3711 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id
);
3712 if ($course->id
== SITEID
) {
3713 return array('*'=>get_string('page-x', 'pagetype'));
3715 return array('*'=>get_string('page-x', 'pagetype'),
3716 'course-*'=>get_string('page-course-x', 'pagetype'),
3717 'course-view-*'=>get_string('page-course-view-x', 'pagetype')
3723 * Determine whether course ajax should be enabled for the specified course
3725 * @param stdClass $course The course to test against
3726 * @return boolean Whether course ajax is enabled or note
3728 function course_ajax_enabled($course) {
3729 global $CFG, $PAGE, $SITE;
3731 // Ajax must be enabled globally
3732 if (!$CFG->enableajax
) {
3736 // The user must be editing for AJAX to be included
3737 if (!$PAGE->user_is_editing()) {
3741 // Check that the theme suports
3742 if (!$PAGE->theme
->enablecourseajax
) {
3746 // Check that the course format supports ajax functionality
3747 // The site 'format' doesn't have information on course format support
3748 if ($SITE->id
!== $course->id
) {
3749 $courseformatajaxsupport = course_format_ajax_support($course->format
);
3750 if (!$courseformatajaxsupport->capable
) {
3755 // All conditions have been met so course ajax should be enabled
3760 * Include the relevant javascript and language strings for the resource
3761 * toolbox YUI module
3763 * @param integer $id The ID of the course being applied to
3764 * @param array $usedmodules An array containing the names of the modules in use on the page
3765 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3766 * @param stdClass $config An object containing configuration parameters for ajax modules including:
3767 * * resourceurl The URL to post changes to for resource changes
3768 * * sectionurl The URL to post changes to for section changes
3769 * * pageparams Additional parameters to pass through in the post
3772 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3773 global $PAGE, $SITE;
3775 // Ensure that ajax should be included
3776 if (!course_ajax_enabled($course)) {
3781 $config = new stdClass();
3784 // The URL to use for resource changes
3785 if (!isset($config->resourceurl
)) {
3786 $config->resourceurl
= '/course/rest.php';
3789 // The URL to use for section changes
3790 if (!isset($config->sectionurl
)) {
3791 $config->sectionurl
= '/course/rest.php';
3794 // Any additional parameters which need to be included on page submission
3795 if (!isset($config->pageparams
)) {
3796 $config->pageparams
= array();
3799 // Include toolboxes
3800 $PAGE->requires
->yui_module('moodle-course-toolboxes',
3801 'M.course.init_resource_toolbox',
3803 'courseid' => $course->id
,
3804 'ajaxurl' => $config->resourceurl
,
3805 'config' => $config,
3808 $PAGE->requires
->yui_module('moodle-course-toolboxes',
3809 'M.course.init_section_toolbox',
3811 'courseid' => $course->id
,
3812 'format' => $course->format
,
3813 'ajaxurl' => $config->sectionurl
,
3814 'config' => $config,
3818 // Include course dragdrop
3819 if ($course->id
!= $SITE->id
) {
3820 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3822 'courseid' => $course->id
,
3823 'ajaxurl' => $config->sectionurl
,
3824 'config' => $config,
3827 $PAGE->requires
->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3829 'courseid' => $course->id
,
3830 'ajaxurl' => $config->resourceurl
,
3831 'config' => $config,
3835 // Include blocks dragdrop
3837 'courseid' => $course->id
,
3838 'pagetype' => $PAGE->pagetype
,
3839 'pagelayout' => $PAGE->pagelayout
,
3840 'subpage' => $PAGE->subpage
,
3841 'regions' => $PAGE->blocks
->get_regions(),
3843 $PAGE->requires
->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
3845 // Require various strings for the command toolbox
3846 $PAGE->requires
->strings_for_js(array(
3849 'deletechecktypename',
3851 'edittitleinstructions',
3857 'clicktochangeinbrackets',
3864 // Include format-specific strings
3865 if ($course->id
!= $SITE->id
) {
3866 $PAGE->requires
->strings_for_js(array(
3869 ), 'format_' . $course->format
);
3872 // For confirming resource deletion we need the name of the module in question
3873 foreach ($usedmodules as $module => $modname) {
3874 $PAGE->requires
->string_for_js('pluginname', $module);
3877 // Load drag and drop upload AJAX.
3878 dndupload_add_to_course($course, $enabledmodules);
3884 * Returns the sorted list of available course formats, filtered by enabled if necessary
3886 * @param bool $enabledonly return only formats that are enabled
3887 * @return array array of sorted format names
3889 function get_sorted_course_formats($enabledonly = false) {
3891 $formats = get_plugin_list('format');
3893 if (!empty($CFG->format_plugins_sortorder
)) {
3894 $order = explode(',', $CFG->format_plugins_sortorder
);
3895 $order = array_merge(array_intersect($order, array_keys($formats)),
3896 array_diff(array_keys($formats), $order));
3898 $order = array_keys($formats);
3900 if (!$enabledonly) {
3903 $sortedformats = array();
3904 foreach ($order as $formatname) {
3905 if (!get_config('format_'.$formatname, 'disabled')) {
3906 $sortedformats[] = $formatname;
3909 return $sortedformats;
3913 * The URL to use for the specified course (with section)
3915 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3916 * @param int|stdClass $section Section object from database or just field course_sections.section
3917 * if omitted the course view page is returned
3918 * @param array $options options for view URL. At the moment core uses:
3919 * 'navigation' (bool) if true and section has no separate page, the function returns null
3920 * 'sr' (int) used by multipage formats to specify to which section to return
3921 * @return moodle_url The url of course
3923 function course_get_url($courseorid, $section = null, $options = array()) {
3924 return course_get_format($courseorid)->get_view_url($section, $options);