Merge branch 'MDL-39586_master' of git://github.com/dmonllao/moodle
[moodle.git] / course / lib.php
blobf1663f74464b6a157e6159481f2681d3b8000f44
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library of useful functions
21 * @copyright 1999 Martin Dougiamas http://dougiamas.com
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core
24 * @subpackage course
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir.'/completionlib.php');
30 require_once($CFG->libdir.'/filelib.php');
31 require_once($CFG->dirroot.'/course/dnduploadlib.php');
32 require_once($CFG->dirroot.'/course/format/lib.php');
34 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
37 /**
38 * Number of courses to display when summaries are included.
39 * @var int
40 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
42 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
44 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
45 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
46 define('FRONTPAGENEWS', '0');
47 define('FRONTPAGECOURSELIST', '1'); // Not used. TODO MDL-38832 remove
48 define('FRONTPAGECATEGORYNAMES', '2');
49 define('FRONTPAGETOPICONLY', '3'); // Not used. TODO MDL-38832 remove
50 define('FRONTPAGECATEGORYCOMBO', '4');
51 define('FRONTPAGEENROLLEDCOURSELIST', '5');
52 define('FRONTPAGEALLCOURSELIST', '6');
53 define('FRONTPAGECOURSESEARCH', '7');
54 define('FRONTPAGECOURSELIMIT', 200); // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage. TODO MDL-38832 remove
55 define('EXCELROWS', 65535);
56 define('FIRSTUSEDEXCELROW', 3);
58 define('MOD_CLASS_ACTIVITY', 0);
59 define('MOD_CLASS_RESOURCE', 1);
61 function make_log_url($module, $url) {
62 switch ($module) {
63 case 'course':
64 if (strpos($url, 'report/') === 0) {
65 // there is only one report type, course reports are deprecated
66 $url = "/$url";
67 break;
69 case 'file':
70 case 'login':
71 case 'lib':
72 case 'admin':
73 case 'calendar':
74 case 'category':
75 case 'mnet course':
76 if (strpos($url, '../') === 0) {
77 $url = ltrim($url, '.');
78 } else {
79 $url = "/course/$url";
81 break;
82 case 'user':
83 case 'blog':
84 $url = "/$module/$url";
85 break;
86 case 'upload':
87 $url = $url;
88 break;
89 case 'coursetags':
90 $url = '/'.$url;
91 break;
92 case 'library':
93 case '':
94 $url = '/';
95 break;
96 case 'message':
97 $url = "/message/$url";
98 break;
99 case 'notes':
100 $url = "/notes/$url";
101 break;
102 case 'tag':
103 $url = "/tag/$url";
104 break;
105 case 'role':
106 $url = '/'.$url;
107 break;
108 default:
109 $url = "/mod/$module/$url";
110 break;
113 //now let's sanitise urls - there might be some ugly nasties:-(
114 $parts = explode('?', $url);
115 $script = array_shift($parts);
116 if (strpos($script, 'http') === 0) {
117 $script = clean_param($script, PARAM_URL);
118 } else {
119 $script = clean_param($script, PARAM_PATH);
122 $query = '';
123 if ($parts) {
124 $query = implode('', $parts);
125 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
126 $parts = explode('&', $query);
127 $eq = urlencode('=');
128 foreach ($parts as $key=>$part) {
129 $part = urlencode(urldecode($part));
130 $part = str_replace($eq, '=', $part);
131 $parts[$key] = $part;
133 $query = '?'.implode('&amp;', $parts);
136 return $script.$query;
140 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
141 $modname="", $modid=0, $modaction="", $groupid=0) {
142 global $CFG, $DB;
144 // It is assumed that $date is the GMT time of midnight for that day,
145 // and so the next 86400 seconds worth of logs are printed.
147 /// Setup for group handling.
149 // TODO: I don't understand group/context/etc. enough to be able to do
150 // something interesting with it here
151 // What is the context of a remote course?
153 /// If the group mode is separate, and this user does not have editing privileges,
154 /// then only the user's group can be viewed.
155 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
156 // $groupid = get_current_group($course->id);
158 /// If this course doesn't have groups, no groupid can be specified.
159 //else if (!$course->groupmode) {
160 // $groupid = 0;
163 $groupid = 0;
165 $joins = array();
166 $where = '';
168 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
169 FROM {mnet_log} l
170 LEFT JOIN {user} u ON l.userid = u.id
171 WHERE ";
172 $params = array();
174 $where .= "l.hostid = :hostid";
175 $params['hostid'] = $hostid;
177 // TODO: Is 1 really a magic number referring to the sitename?
178 if ($course != SITEID || $modid != 0) {
179 $where .= " AND l.course=:courseid";
180 $params['courseid'] = $course;
183 if ($modname) {
184 $where .= " AND l.module = :modname";
185 $params['modname'] = $modname;
188 if ('site_errors' === $modid) {
189 $where .= " AND ( l.action='error' OR l.action='infected' )";
190 } else if ($modid) {
191 //TODO: This assumes that modids are the same across sites... probably
192 //not true
193 $where .= " AND l.cmid = :modid";
194 $params['modid'] = $modid;
197 if ($modaction) {
198 $firstletter = substr($modaction, 0, 1);
199 if ($firstletter == '-') {
200 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
201 $params['modaction'] = '%'.substr($modaction, 1).'%';
202 } else {
203 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
204 $params['modaction'] = '%'.$modaction.'%';
208 if ($user) {
209 $where .= " AND l.userid = :user";
210 $params['user'] = $user;
213 if ($date) {
214 $enddate = $date + 86400;
215 $where .= " AND l.time > :date AND l.time < :enddate";
216 $params['date'] = $date;
217 $params['enddate'] = $enddate;
220 $result = array();
221 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
222 if(!empty($result['totalcount'])) {
223 $where .= " ORDER BY $order";
224 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
225 } else {
226 $result['logs'] = array();
228 return $result;
231 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
232 $modname="", $modid=0, $modaction="", $groupid=0) {
233 global $DB, $SESSION, $USER;
234 // It is assumed that $date is the GMT time of midnight for that day,
235 // and so the next 86400 seconds worth of logs are printed.
237 /// Setup for group handling.
239 /// If the group mode is separate, and this user does not have editing privileges,
240 /// then only the user's group can be viewed.
241 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
242 if (isset($SESSION->currentgroup[$course->id])) {
243 $groupid = $SESSION->currentgroup[$course->id];
244 } else {
245 $groupid = groups_get_all_groups($course->id, $USER->id);
246 if (is_array($groupid)) {
247 $groupid = array_shift(array_keys($groupid));
248 $SESSION->currentgroup[$course->id] = $groupid;
249 } else {
250 $groupid = 0;
254 /// If this course doesn't have groups, no groupid can be specified.
255 else if (!$course->groupmode) {
256 $groupid = 0;
259 $joins = array();
260 $params = array();
262 if ($course->id != SITEID || $modid != 0) {
263 $joins[] = "l.course = :courseid";
264 $params['courseid'] = $course->id;
267 if ($modname) {
268 $joins[] = "l.module = :modname";
269 $params['modname'] = $modname;
272 if ('site_errors' === $modid) {
273 $joins[] = "( l.action='error' OR l.action='infected' )";
274 } else if ($modid) {
275 $joins[] = "l.cmid = :modid";
276 $params['modid'] = $modid;
279 if ($modaction) {
280 $firstletter = substr($modaction, 0, 1);
281 if ($firstletter == '-') {
282 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
283 $params['modaction'] = '%'.substr($modaction, 1).'%';
284 } else {
285 $joins[] = $DB->sql_like('l.action', ':modaction', false);
286 $params['modaction'] = '%'.$modaction.'%';
291 /// Getting all members of a group.
292 if ($groupid and !$user) {
293 if ($gusers = groups_get_members($groupid)) {
294 $gusers = array_keys($gusers);
295 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
296 } else {
297 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
300 else if ($user) {
301 $joins[] = "l.userid = :userid";
302 $params['userid'] = $user;
305 if ($date) {
306 $enddate = $date + 86400;
307 $joins[] = "l.time > :date AND l.time < :enddate";
308 $params['date'] = $date;
309 $params['enddate'] = $enddate;
312 $selector = implode(' AND ', $joins);
314 $totalcount = 0; // Initialise
315 $result = array();
316 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
317 $result['totalcount'] = $totalcount;
318 return $result;
322 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
323 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
325 global $CFG, $DB, $OUTPUT;
327 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
328 $modname, $modid, $modaction, $groupid)) {
329 echo $OUTPUT->notification("No logs found!");
330 echo $OUTPUT->footer();
331 exit;
334 $courses = array();
336 if ($course->id == SITEID) {
337 $courses[0] = '';
338 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
339 foreach ($ccc as $cc) {
340 $courses[$cc->id] = $cc->shortname;
343 } else {
344 $courses[$course->id] = $course->shortname;
347 $totalcount = $logs['totalcount'];
348 $count=0;
349 $ldcache = array();
350 $tt = getdate(time());
351 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
353 $strftimedatetime = get_string("strftimedatetime");
355 echo "<div class=\"info\">\n";
356 print_string("displayingrecords", "", $totalcount);
357 echo "</div>\n";
359 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
361 $table = new html_table();
362 $table->classes = array('logtable','generaltable');
363 $table->align = array('right', 'left', 'left');
364 $table->head = array(
365 get_string('time'),
366 get_string('ip_address'),
367 get_string('fullnameuser'),
368 get_string('action'),
369 get_string('info')
371 $table->data = array();
373 if ($course->id == SITEID) {
374 array_unshift($table->align, 'left');
375 array_unshift($table->head, get_string('course'));
378 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
379 if (empty($logs['logs'])) {
380 $logs['logs'] = array();
383 foreach ($logs['logs'] as $log) {
385 if (isset($ldcache[$log->module][$log->action])) {
386 $ld = $ldcache[$log->module][$log->action];
387 } else {
388 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
389 $ldcache[$log->module][$log->action] = $ld;
391 if ($ld && is_numeric($log->info)) {
392 // ugly hack to make sure fullname is shown correctly
393 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
394 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
395 } else {
396 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
400 //Filter log->info
401 $log->info = format_string($log->info);
403 // If $log->url has been trimmed short by the db size restriction
404 // code in add_to_log, keep a note so we don't add a link to a broken url
405 $brokenurl=(textlib::strlen($log->url)==100 && textlib::substr($log->url,97)=='...');
407 $row = array();
408 if ($course->id == SITEID) {
409 if (empty($log->course)) {
410 $row[] = get_string('site');
411 } else {
412 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
416 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
418 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
419 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
421 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
423 $displayaction="$log->module $log->action";
424 if ($brokenurl) {
425 $row[] = $displayaction;
426 } else {
427 $link = make_log_url($log->module,$log->url);
428 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
430 $row[] = $log->info;
431 $table->data[] = $row;
434 echo html_writer::table($table);
435 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
439 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
440 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
442 global $CFG, $DB, $OUTPUT;
444 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
445 $modname, $modid, $modaction, $groupid)) {
446 echo $OUTPUT->notification("No logs found!");
447 echo $OUTPUT->footer();
448 exit;
451 if ($course->id == SITEID) {
452 $courses[0] = '';
453 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
454 foreach ($ccc as $cc) {
455 $courses[$cc->id] = $cc->shortname;
460 $totalcount = $logs['totalcount'];
461 $count=0;
462 $ldcache = array();
463 $tt = getdate(time());
464 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
466 $strftimedatetime = get_string("strftimedatetime");
468 echo "<div class=\"info\">\n";
469 print_string("displayingrecords", "", $totalcount);
470 echo "</div>\n";
472 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
474 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
475 echo "<tr>";
476 if ($course->id == SITEID) {
477 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
479 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
480 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
481 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
482 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
483 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
484 echo "</tr>\n";
486 if (empty($logs['logs'])) {
487 echo "</table>\n";
488 return;
491 $row = 1;
492 foreach ($logs['logs'] as $log) {
494 $log->info = $log->coursename;
495 $row = ($row + 1) % 2;
497 if (isset($ldcache[$log->module][$log->action])) {
498 $ld = $ldcache[$log->module][$log->action];
499 } else {
500 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
501 $ldcache[$log->module][$log->action] = $ld;
503 if (0 && $ld && !empty($log->info)) {
504 // ugly hack to make sure fullname is shown correctly
505 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
506 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
507 } else {
508 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
512 //Filter log->info
513 $log->info = format_string($log->info);
515 echo '<tr class="r'.$row.'">';
516 if ($course->id == SITEID) {
517 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
518 echo "<td class=\"r$row c0\" >\n";
519 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
520 echo "</td>\n";
522 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
523 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
524 echo "<td class=\"r$row c2\" >\n";
525 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
526 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
527 echo "</td>\n";
528 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
529 echo "<td class=\"r$row c3\" >\n";
530 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
531 echo "</td>\n";
532 echo "<td class=\"r$row c4\">\n";
533 echo $log->action .': '.$log->module;
534 echo "</td>\n";
535 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
536 echo "</tr>\n";
538 echo "</table>\n";
540 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
544 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
545 $modid, $modaction, $groupid) {
546 global $DB, $CFG;
548 require_once($CFG->libdir . '/csvlib.class.php');
550 $csvexporter = new csv_export_writer('tab');
552 $header = array();
553 $header[] = get_string('course');
554 $header[] = get_string('time');
555 $header[] = get_string('ip_address');
556 $header[] = get_string('fullnameuser');
557 $header[] = get_string('action');
558 $header[] = get_string('info');
560 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
561 $modname, $modid, $modaction, $groupid)) {
562 return false;
565 $courses = array();
567 if ($course->id == SITEID) {
568 $courses[0] = '';
569 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
570 foreach ($ccc as $cc) {
571 $courses[$cc->id] = $cc->shortname;
574 } else {
575 $courses[$course->id] = $course->shortname;
578 $count=0;
579 $ldcache = array();
580 $tt = getdate(time());
581 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
583 $strftimedatetime = get_string("strftimedatetime");
585 $csvexporter->set_filename('logs', '.txt');
586 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
587 $csvexporter->add_data($title);
588 $csvexporter->add_data($header);
590 if (empty($logs['logs'])) {
591 return true;
594 foreach ($logs['logs'] as $log) {
595 if (isset($ldcache[$log->module][$log->action])) {
596 $ld = $ldcache[$log->module][$log->action];
597 } else {
598 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
599 $ldcache[$log->module][$log->action] = $ld;
601 if ($ld && is_numeric($log->info)) {
602 // ugly hack to make sure fullname is shown correctly
603 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
604 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
605 } else {
606 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
610 //Filter log->info
611 $log->info = format_string($log->info);
612 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
614 $coursecontext = context_course::instance($course->id);
615 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
616 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
617 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
618 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
619 $csvexporter->add_data($row);
621 $csvexporter->download_file();
622 return true;
626 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
627 $modid, $modaction, $groupid) {
629 global $CFG, $DB;
631 require_once("$CFG->libdir/excellib.class.php");
633 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
634 $modname, $modid, $modaction, $groupid)) {
635 return false;
638 $courses = array();
640 if ($course->id == SITEID) {
641 $courses[0] = '';
642 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
643 foreach ($ccc as $cc) {
644 $courses[$cc->id] = $cc->shortname;
647 } else {
648 $courses[$course->id] = $course->shortname;
651 $count=0;
652 $ldcache = array();
653 $tt = getdate(time());
654 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
656 $strftimedatetime = get_string("strftimedatetime");
658 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
659 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
660 $filename .= '.xls';
662 $workbook = new MoodleExcelWorkbook('-');
663 $workbook->send($filename);
665 $worksheet = array();
666 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
667 get_string('fullnameuser'), get_string('action'), get_string('info'));
669 // Creating worksheets
670 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
671 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
672 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
673 $worksheet[$wsnumber]->set_column(1, 1, 30);
674 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
675 userdate(time(), $strftimedatetime));
676 $col = 0;
677 foreach ($headers as $item) {
678 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
679 $col++;
683 if (empty($logs['logs'])) {
684 $workbook->close();
685 return true;
688 $formatDate =& $workbook->add_format();
689 $formatDate->set_num_format(get_string('log_excel_date_format'));
691 $row = FIRSTUSEDEXCELROW;
692 $wsnumber = 1;
693 $myxls =& $worksheet[$wsnumber];
694 foreach ($logs['logs'] as $log) {
695 if (isset($ldcache[$log->module][$log->action])) {
696 $ld = $ldcache[$log->module][$log->action];
697 } else {
698 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
699 $ldcache[$log->module][$log->action] = $ld;
701 if ($ld && is_numeric($log->info)) {
702 // ugly hack to make sure fullname is shown correctly
703 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
704 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
705 } else {
706 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
710 // Filter log->info
711 $log->info = format_string($log->info);
712 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
714 if ($nroPages>1) {
715 if ($row > EXCELROWS) {
716 $wsnumber++;
717 $myxls =& $worksheet[$wsnumber];
718 $row = FIRSTUSEDEXCELROW;
722 $coursecontext = context_course::instance($course->id);
724 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
725 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
726 $myxls->write($row, 2, $log->ip, '');
727 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
728 $myxls->write($row, 3, $fullname, '');
729 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
730 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
731 $myxls->write($row, 5, $log->info, '');
733 $row++;
736 $workbook->close();
737 return true;
740 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
741 $modid, $modaction, $groupid) {
743 global $CFG, $DB;
745 require_once("$CFG->libdir/odslib.class.php");
747 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
748 $modname, $modid, $modaction, $groupid)) {
749 return false;
752 $courses = array();
754 if ($course->id == SITEID) {
755 $courses[0] = '';
756 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
757 foreach ($ccc as $cc) {
758 $courses[$cc->id] = $cc->shortname;
761 } else {
762 $courses[$course->id] = $course->shortname;
765 $count=0;
766 $ldcache = array();
767 $tt = getdate(time());
768 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
770 $strftimedatetime = get_string("strftimedatetime");
772 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
773 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
774 $filename .= '.ods';
776 $workbook = new MoodleODSWorkbook('-');
777 $workbook->send($filename);
779 $worksheet = array();
780 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
781 get_string('fullnameuser'), get_string('action'), get_string('info'));
783 // Creating worksheets
784 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
785 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
786 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
787 $worksheet[$wsnumber]->set_column(1, 1, 30);
788 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
789 userdate(time(), $strftimedatetime));
790 $col = 0;
791 foreach ($headers as $item) {
792 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
793 $col++;
797 if (empty($logs['logs'])) {
798 $workbook->close();
799 return true;
802 $formatDate =& $workbook->add_format();
803 $formatDate->set_num_format(get_string('log_excel_date_format'));
805 $row = FIRSTUSEDEXCELROW;
806 $wsnumber = 1;
807 $myxls =& $worksheet[$wsnumber];
808 foreach ($logs['logs'] as $log) {
809 if (isset($ldcache[$log->module][$log->action])) {
810 $ld = $ldcache[$log->module][$log->action];
811 } else {
812 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
813 $ldcache[$log->module][$log->action] = $ld;
815 if ($ld && is_numeric($log->info)) {
816 // ugly hack to make sure fullname is shown correctly
817 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
818 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
819 } else {
820 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
824 // Filter log->info
825 $log->info = format_string($log->info);
826 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
828 if ($nroPages>1) {
829 if ($row > EXCELROWS) {
830 $wsnumber++;
831 $myxls =& $worksheet[$wsnumber];
832 $row = FIRSTUSEDEXCELROW;
836 $coursecontext = context_course::instance($course->id);
838 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
839 $myxls->write_date($row, 1, $log->time);
840 $myxls->write_string($row, 2, $log->ip);
841 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
842 $myxls->write_string($row, 3, $fullname);
843 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
844 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
845 $myxls->write_string($row, 5, $log->info);
847 $row++;
850 $workbook->close();
851 return true;
855 * For a given course, returns an array of course activity objects
856 * Each item in the array contains he following properties:
858 function get_array_of_activities($courseid) {
859 // cm - course module id
860 // mod - name of the module (eg forum)
861 // section - the number of the section (eg week or topic)
862 // name - the name of the instance
863 // visible - is the instance visible or not
864 // groupingid - grouping id
865 // groupmembersonly - is this instance visible to group members only
866 // extra - contains extra string to include in any link
867 global $CFG, $DB;
868 if(!empty($CFG->enableavailability)) {
869 require_once($CFG->libdir.'/conditionlib.php');
872 $course = $DB->get_record('course', array('id'=>$courseid));
874 if (empty($course)) {
875 throw new moodle_exception('courseidnotfound');
878 $mod = array();
880 $rawmods = get_course_mods($courseid);
881 if (empty($rawmods)) {
882 return $mod; // always return array
885 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
886 foreach ($sections as $section) {
887 if (!empty($section->sequence)) {
888 $sequence = explode(",", $section->sequence);
889 foreach ($sequence as $seq) {
890 if (empty($rawmods[$seq])) {
891 continue;
893 $mod[$seq] = new stdClass();
894 $mod[$seq]->id = $rawmods[$seq]->instance;
895 $mod[$seq]->cm = $rawmods[$seq]->id;
896 $mod[$seq]->mod = $rawmods[$seq]->modname;
898 // Oh dear. Inconsistent names left here for backward compatibility.
899 $mod[$seq]->section = $section->section;
900 $mod[$seq]->sectionid = $rawmods[$seq]->section;
902 $mod[$seq]->module = $rawmods[$seq]->module;
903 $mod[$seq]->added = $rawmods[$seq]->added;
904 $mod[$seq]->score = $rawmods[$seq]->score;
905 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
906 $mod[$seq]->visible = $rawmods[$seq]->visible;
907 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
908 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
909 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
910 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
911 $mod[$seq]->indent = $rawmods[$seq]->indent;
912 $mod[$seq]->completion = $rawmods[$seq]->completion;
913 $mod[$seq]->extra = "";
914 $mod[$seq]->completiongradeitemnumber =
915 $rawmods[$seq]->completiongradeitemnumber;
916 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
917 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
918 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
919 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
920 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
921 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
922 if (!empty($CFG->enableavailability)) {
923 condition_info::fill_availability_conditions($rawmods[$seq]);
924 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
925 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
926 $mod[$seq]->conditionsfield = $rawmods[$seq]->conditionsfield;
929 $modname = $mod[$seq]->mod;
930 $functionname = $modname."_get_coursemodule_info";
932 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
933 continue;
936 include_once("$CFG->dirroot/mod/$modname/lib.php");
938 if ($hasfunction = function_exists($functionname)) {
939 if ($info = $functionname($rawmods[$seq])) {
940 if (!empty($info->icon)) {
941 $mod[$seq]->icon = $info->icon;
943 if (!empty($info->iconcomponent)) {
944 $mod[$seq]->iconcomponent = $info->iconcomponent;
946 if (!empty($info->name)) {
947 $mod[$seq]->name = $info->name;
949 if ($info instanceof cached_cm_info) {
950 // When using cached_cm_info you can include three new fields
951 // that aren't available for legacy code
952 if (!empty($info->content)) {
953 $mod[$seq]->content = $info->content;
955 if (!empty($info->extraclasses)) {
956 $mod[$seq]->extraclasses = $info->extraclasses;
958 if (!empty($info->iconurl)) {
959 $mod[$seq]->iconurl = $info->iconurl;
961 if (!empty($info->onclick)) {
962 $mod[$seq]->onclick = $info->onclick;
964 if (!empty($info->customdata)) {
965 $mod[$seq]->customdata = $info->customdata;
967 } else {
968 // When using a stdclass, the (horrible) deprecated ->extra field
969 // is available for BC
970 if (!empty($info->extra)) {
971 $mod[$seq]->extra = $info->extra;
976 // When there is no modname_get_coursemodule_info function,
977 // but showdescriptions is enabled, then we use the 'intro'
978 // and 'introformat' fields in the module table
979 if (!$hasfunction && $rawmods[$seq]->showdescription) {
980 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
981 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
982 // Set content from intro and introformat. Filters are disabled
983 // because we filter it with format_text at display time
984 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
985 $modvalues, $rawmods[$seq]->id, false);
987 // To save making another query just below, put name in here
988 $mod[$seq]->name = $modvalues->name;
991 if (!isset($mod[$seq]->name)) {
992 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
995 // Minimise the database size by unsetting default options when they are
996 // 'empty'. This list corresponds to code in the cm_info constructor.
997 foreach (array('idnumber', 'groupmode', 'groupingid', 'groupmembersonly',
998 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
999 'icon', 'iconcomponent', 'customdata', 'showavailability', 'availablefrom',
1000 'availableuntil', 'conditionscompletion', 'conditionsgrade',
1001 'completionview', 'completionexpected', 'score', 'showdescription')
1002 as $property) {
1003 if (property_exists($mod[$seq], $property) &&
1004 empty($mod[$seq]->{$property})) {
1005 unset($mod[$seq]->{$property});
1008 // Special case: this value is usually set to null, but may be 0
1009 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
1010 is_null($mod[$seq]->completiongradeitemnumber)) {
1011 unset($mod[$seq]->completiongradeitemnumber);
1017 return $mod;
1021 * Returns the localised human-readable names of all used modules
1023 * @param bool $plural if true returns the plural forms of the names
1024 * @return array where key is the module name (component name without 'mod_') and
1025 * the value is the human-readable string. Array sorted alphabetically by value
1027 function get_module_types_names($plural = false) {
1028 static $modnames = null;
1029 global $DB, $CFG;
1030 if ($modnames === null) {
1031 $modnames = array(0 => array(), 1 => array());
1032 if ($allmods = $DB->get_records("modules")) {
1033 foreach ($allmods as $mod) {
1034 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
1035 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
1036 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
1039 collatorlib::asort($modnames[0]);
1040 collatorlib::asort($modnames[1]);
1043 return $modnames[(int)$plural];
1047 * Set highlighted section. Only one section can be highlighted at the time.
1049 * @param int $courseid course id
1050 * @param int $marker highlight section with this number, 0 means remove higlightin
1051 * @return void
1053 function course_set_marker($courseid, $marker) {
1054 global $DB;
1055 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1056 format_base::reset_course_cache($courseid);
1060 * For a given course section, marks it visible or hidden,
1061 * and does the same for every activity in that section
1063 * @param int $courseid course id
1064 * @param int $sectionnumber The section number to adjust
1065 * @param int $visibility The new visibility
1066 * @return array A list of resources which were hidden in the section
1068 function set_section_visible($courseid, $sectionnumber, $visibility) {
1069 global $DB;
1071 $resourcestotoggle = array();
1072 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1073 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1074 if (!empty($section->sequence)) {
1075 $modules = explode(",", $section->sequence);
1076 foreach ($modules as $moduleid) {
1077 if ($cm = $DB->get_record('course_modules', array('id' => $moduleid), 'visible, visibleold')) {
1078 if ($visibility) {
1079 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1080 set_coursemodule_visible($moduleid, $cm->visibleold);
1081 } else {
1082 // We hide the section, so we hide the module but we store the original state in visibleold.
1083 set_coursemodule_visible($moduleid, 0);
1084 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1089 rebuild_course_cache($courseid, true);
1091 // Determine which modules are visible for AJAX update
1092 if (!empty($modules)) {
1093 list($insql, $params) = $DB->get_in_or_equal($modules);
1094 $select = 'id ' . $insql . ' AND visible = ?';
1095 array_push($params, $visibility);
1096 if (!$visibility) {
1097 $select .= ' AND visibleold = 1';
1099 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
1102 return $resourcestotoggle;
1106 * Retrieve all metadata for the requested modules
1108 * @param object $course The Course
1109 * @param array $modnames An array containing the list of modules and their
1110 * names
1111 * @param int $sectionreturn The section to return to
1112 * @return array A list of stdClass objects containing metadata about each
1113 * module
1115 function get_module_metadata($course, $modnames, $sectionreturn = null) {
1116 global $CFG, $OUTPUT;
1118 // get_module_metadata will be called once per section on the page and courses may show
1119 // different modules to one another
1120 static $modlist = array();
1121 if (!isset($modlist[$course->id])) {
1122 $modlist[$course->id] = array();
1125 $return = array();
1126 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
1127 if ($sectionreturn !== null) {
1128 $urlbase->param('sr', $sectionreturn);
1130 foreach($modnames as $modname => $modnamestr) {
1131 if (!course_allowed_module($course, $modname)) {
1132 continue;
1134 if (isset($modlist[$course->id][$modname])) {
1135 // This module is already cached
1136 $return[$modname] = $modlist[$course->id][$modname];
1137 continue;
1140 // Include the module lib
1141 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1142 if (!file_exists($libfile)) {
1143 continue;
1145 include_once($libfile);
1147 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1148 $gettypesfunc = $modname.'_get_types';
1149 if (function_exists($gettypesfunc)) {
1150 $types = $gettypesfunc();
1151 if (is_array($types) && count($types) > 0) {
1152 $group = new stdClass();
1153 $group->name = $modname;
1154 $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
1155 foreach($types as $type) {
1156 if ($type->typestr === '--') {
1157 continue;
1159 if (strpos($type->typestr, '--') === 0) {
1160 $group->title = str_replace('--', '', $type->typestr);
1161 continue;
1163 // Set the Sub Type metadata
1164 $subtype = new stdClass();
1165 $subtype->title = $type->typestr;
1166 $subtype->type = str_replace('&amp;', '&', $type->type);
1167 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
1168 $subtype->archetype = $type->modclass;
1170 // The group archetype should match the subtype archetypes and all subtypes
1171 // should have the same archetype
1172 $group->archetype = $subtype->archetype;
1174 if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
1175 $subtype->help = get_string('help' . $subtype->name, $modname);
1177 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $subtype->name));
1178 $group->types[] = $subtype;
1180 $modlist[$course->id][$modname] = $group;
1182 } else {
1183 $module = new stdClass();
1184 $module->title = $modnamestr;
1185 $module->name = $modname;
1186 $module->link = new moodle_url($urlbase, array('add' => $modname));
1187 $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
1188 $sm = get_string_manager();
1189 if ($sm->string_exists('modulename_help', $modname)) {
1190 $module->help = get_string('modulename_help', $modname);
1191 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs
1192 $link = get_string('modulename_link', $modname);
1193 $linktext = get_string('morehelp');
1194 $module->help .= html_writer::tag('div', $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
1197 $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1198 $modlist[$course->id][$modname] = $module;
1200 if (isset($modlist[$course->id][$modname])) {
1201 $return[$modname] = $modlist[$course->id][$modname];
1202 } else {
1203 debugging("Invalid module metadata configuration for {$modname}");
1207 return $return;
1211 * Return the course category context for the category with id $categoryid, except
1212 * that if $categoryid is 0, return the system context.
1214 * @param integer $categoryid a category id or 0.
1215 * @return object the corresponding context
1217 function get_category_or_system_context($categoryid) {
1218 if ($categoryid) {
1219 return context_coursecat::instance($categoryid, IGNORE_MISSING);
1220 } else {
1221 return context_system::instance();
1226 * Returns full course categories trees to be used in html_writer::select()
1228 * Calls {@link coursecat::make_categories_list()} to build the tree and
1229 * adds whitespace to denote nesting
1231 * @return array array mapping coursecat id to the display name
1233 function make_categories_options() {
1234 global $CFG;
1235 require_once($CFG->libdir. '/coursecatlib.php');
1236 $cats = coursecat::make_categories_list();
1237 foreach ($cats as $key => $value) {
1238 $cats[$key] = str_repeat('&nbsp;', coursecat::get($key)->depth - 1). $value;
1240 return $cats;
1244 * Print the buttons relating to course requests.
1246 * @param object $context current page context.
1248 function print_course_request_buttons($context) {
1249 global $CFG, $DB, $OUTPUT;
1250 if (empty($CFG->enablecourserequests)) {
1251 return;
1253 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
1254 /// Print a button to request a new course
1255 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
1257 /// Print a button to manage pending requests
1258 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
1259 $disabled = !$DB->record_exists('course_request', array());
1260 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
1265 * Does the user have permission to edit things in this category?
1267 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1268 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1270 function can_edit_in_category($categoryid = 0) {
1271 $context = get_category_or_system_context($categoryid);
1272 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1275 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1277 function add_course_module($mod) {
1278 global $DB;
1280 $mod->added = time();
1281 unset($mod->id);
1283 $cmid = $DB->insert_record("course_modules", $mod);
1284 rebuild_course_cache($mod->course, true);
1285 return $cmid;
1289 * Creates missing course section(s) and rebuilds course cache
1291 * @param int|stdClass $courseorid course id or course object
1292 * @param int|array $sections list of relative section numbers to create
1293 * @return bool if there were any sections created
1295 function course_create_sections_if_missing($courseorid, $sections) {
1296 global $DB;
1297 if (!is_array($sections)) {
1298 $sections = array($sections);
1300 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1301 if (is_object($courseorid)) {
1302 $courseorid = $courseorid->id;
1304 $coursechanged = false;
1305 foreach ($sections as $sectionnum) {
1306 if (!in_array($sectionnum, $existing)) {
1307 $cw = new stdClass();
1308 $cw->course = $courseorid;
1309 $cw->section = $sectionnum;
1310 $cw->summary = '';
1311 $cw->summaryformat = FORMAT_HTML;
1312 $cw->sequence = '';
1313 $id = $DB->insert_record("course_sections", $cw);
1314 $coursechanged = true;
1317 if ($coursechanged) {
1318 rebuild_course_cache($courseorid, true);
1320 return $coursechanged;
1324 * Adds an existing module to the section
1326 * Updates both tables {course_sections} and {course_modules}
1328 * @param int|stdClass $courseorid course id or course object
1329 * @param int $cmid id of the module already existing in course_modules table
1330 * @param int $sectionnum relative number of the section (field course_sections.section)
1331 * If section does not exist it will be created
1332 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1333 * before which the module needs to be included. Null for inserting in the
1334 * end of the section
1335 * @return int The course_sections ID where the module is inserted
1337 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
1338 global $DB, $COURSE;
1339 if (is_object($beforemod)) {
1340 $beforemod = $beforemod->id;
1342 if (is_object($courseorid)) {
1343 $courseid = $courseorid->id;
1344 } else {
1345 $courseid = $courseorid;
1347 course_create_sections_if_missing($courseorid, $sectionnum);
1348 // Do not try to use modinfo here, there is no guarantee it is valid!
1349 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
1350 $modarray = explode(",", trim($section->sequence));
1351 if (empty($section->sequence)) {
1352 $newsequence = "$cmid";
1353 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
1354 $insertarray = array($cmid, $beforemod);
1355 array_splice($modarray, $key[0], 1, $insertarray);
1356 $newsequence = implode(",", $modarray);
1357 } else {
1358 $newsequence = "$section->sequence,$cmid";
1360 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
1361 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
1362 if (is_object($courseorid)) {
1363 rebuild_course_cache($courseorid->id, true);
1364 } else {
1365 rebuild_course_cache($courseorid, true);
1367 return $section->id; // Return course_sections ID that was used.
1370 function set_coursemodule_groupmode($id, $groupmode) {
1371 global $DB;
1372 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1373 if ($cm->groupmode != $groupmode) {
1374 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1375 rebuild_course_cache($cm->course, true);
1377 return ($cm->groupmode != $groupmode);
1380 function set_coursemodule_idnumber($id, $idnumber) {
1381 global $DB;
1382 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1383 if ($cm->idnumber != $idnumber) {
1384 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1385 rebuild_course_cache($cm->course, true);
1387 return ($cm->idnumber != $idnumber);
1391 * Set the visibility of a module and inherent properties.
1393 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1394 * has been moved to {@link set_section_visible()} which was the only place from which
1395 * the parameter was used.
1397 * @param int $id of the module
1398 * @param int $visible state of the module
1399 * @return bool false when the module was not found, true otherwise
1401 function set_coursemodule_visible($id, $visible) {
1402 global $DB, $CFG;
1403 require_once($CFG->libdir.'/gradelib.php');
1405 // Trigger developer's attention when using the previously removed argument.
1406 if (func_num_args() > 2) {
1407 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1408 has been removed.', DEBUG_DEVELOPER);
1411 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
1412 return false;
1415 // Create events and propagate visibility to associated grade items if the value has changed.
1416 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1417 if ($cm->visible == $visible) {
1418 return true;
1421 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
1422 return false;
1424 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
1425 foreach($events as $event) {
1426 if ($visible) {
1427 show_event($event);
1428 } else {
1429 hide_event($event);
1434 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1435 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1436 if ($grade_items) {
1437 foreach ($grade_items as $grade_item) {
1438 $grade_item->set_hidden(!$visible);
1442 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1443 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1444 $cminfo = new stdClass();
1445 $cminfo->id = $id;
1446 $cminfo->visible = $visible;
1447 $cminfo->visibleold = $visible;
1448 $DB->update_record('course_modules', $cminfo);
1450 rebuild_course_cache($cm->course, true);
1451 return true;
1455 * This function will handles the whole deletion process of a module. This includes calling
1456 * the modules delete_instance function, deleting files, events, grades, conditional data,
1457 * the data in the course_module and course_sections table and adding a module deletion
1458 * event to the DB.
1460 * @param int $cmid the course module id
1461 * @since 2.5
1463 function course_delete_module($cmid) {
1464 global $CFG, $DB, $USER;
1466 require_once($CFG->libdir.'/gradelib.php');
1467 require_once($CFG->dirroot.'/blog/lib.php');
1469 // Get the course module.
1470 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1471 return true;
1474 // Get the module context.
1475 $modcontext = context_module::instance($cm->id);
1477 // Get the course module name.
1478 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1480 // Get the file location of the delete_instance function for this module.
1481 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1483 // Include the file required to call the delete_instance function for this module.
1484 if (file_exists($modlib)) {
1485 require_once($modlib);
1486 } else {
1487 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1488 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1491 $deleteinstancefunction = $modulename . '_delete_instance';
1493 // Ensure the delete_instance function exists for this module.
1494 if (!function_exists($deleteinstancefunction)) {
1495 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1496 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1499 // Call the delete_instance function, if it returns false throw an exception.
1500 if (!$deleteinstancefunction($cm->instance)) {
1501 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1502 "Cannot delete the module $modulename (instance).");
1505 // Remove all module files in case modules forget to do that.
1506 $fs = get_file_storage();
1507 $fs->delete_area_files($modcontext->id);
1509 // Delete events from calendar.
1510 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1511 foreach($events as $event) {
1512 delete_event($event->id);
1516 // Delete grade items, outcome items and grades attached to modules.
1517 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1518 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1519 foreach ($grade_items as $grade_item) {
1520 $grade_item->delete('moddelete');
1524 // Delete completion and availability data; it is better to do this even if the
1525 // features are not turned on, in case they were turned on previously (these will be
1526 // very quick on an empty table).
1527 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1528 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
1529 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
1530 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1531 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1533 // Delete the context.
1534 delete_context(CONTEXT_MODULE, $cm->id);
1536 // Delete the module from the course_modules table.
1537 $DB->delete_records('course_modules', array('id' => $cm->id));
1539 // Delete module from that section.
1540 if (!delete_mod_from_section($cm->id, $cm->section)) {
1541 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1542 "Cannot delete the module $modulename (instance) from section.");
1545 // Trigger a mod_deleted event with information about this module.
1546 $eventdata = new stdClass();
1547 $eventdata->modulename = $modulename;
1548 $eventdata->cmid = $cm->id;
1549 $eventdata->courseid = $cm->course;
1550 $eventdata->userid = $USER->id;
1551 events_trigger('mod_deleted', $eventdata);
1553 add_to_log($cm->course, 'course', "delete mod",
1554 "view.php?id=$cm->course",
1555 "$modulename $cm->instance", $cm->id);
1557 rebuild_course_cache($cm->course, true);
1560 function delete_mod_from_section($modid, $sectionid) {
1561 global $DB;
1563 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1565 $modarray = explode(",", $section->sequence);
1567 if ($key = array_keys ($modarray, $modid)) {
1568 array_splice($modarray, $key[0], 1);
1569 $newsequence = implode(",", $modarray);
1570 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1571 rebuild_course_cache($section->course, true);
1572 return true;
1573 } else {
1574 return false;
1578 return false;
1582 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
1584 * @param object $course course object
1585 * @param int $section Section number (not id!!!)
1586 * @param int $move (-1 or 1)
1587 * @return boolean true if section moved successfully
1588 * @todo MDL-33379 remove this function in 2.5
1590 function move_section($course, $section, $move) {
1591 debugging('This function will be removed before 2.5 is released please use move_section_to', DEBUG_DEVELOPER);
1593 /// Moves a whole course section up and down within the course
1594 global $USER;
1596 if (!$move) {
1597 return true;
1600 $sectiondest = $section + $move;
1602 // compartibility with course formats using field 'numsections'
1603 $courseformatoptions = course_get_format($course)->get_format_options();
1604 if (array_key_exists('numsections', $courseformatoptions) &&
1605 $sectiondest > $courseformatoptions['numsections'] or $sectiondest < 1) {
1606 return false;
1609 $retval = move_section_to($course, $section, $sectiondest);
1610 return $retval;
1614 * Moves a section within a course, from a position to another.
1615 * Be very careful: $section and $destination refer to section number,
1616 * not id!.
1618 * @param object $course
1619 * @param int $section Section number (not id!!!)
1620 * @param int $destination
1621 * @return boolean Result
1623 function move_section_to($course, $section, $destination) {
1624 /// Moves a whole course section up and down within the course
1625 global $USER, $DB;
1627 if (!$destination && $destination != 0) {
1628 return true;
1631 // compartibility with course formats using field 'numsections'
1632 $courseformatoptions = course_get_format($course)->get_format_options();
1633 if ((array_key_exists('numsections', $courseformatoptions) &&
1634 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1635 return false;
1638 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1639 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1640 'section ASC, id ASC', 'id, section')) {
1641 return false;
1644 $movedsections = reorder_sections($sections, $section, $destination);
1646 // Update all sections. Do this in 2 steps to avoid breaking database
1647 // uniqueness constraint
1648 $transaction = $DB->start_delegated_transaction();
1649 foreach ($movedsections as $id => $position) {
1650 if ($sections[$id] !== $position) {
1651 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1654 foreach ($movedsections as $id => $position) {
1655 if ($sections[$id] !== $position) {
1656 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1660 // If we move the highlighted section itself, then just highlight the destination.
1661 // Adjust the higlighted section location if we move something over it either direction.
1662 if ($section == $course->marker) {
1663 course_set_marker($course->id, $destination);
1664 } elseif ($section > $course->marker && $course->marker >= $destination) {
1665 course_set_marker($course->id, $course->marker+1);
1666 } elseif ($section < $course->marker && $course->marker <= $destination) {
1667 course_set_marker($course->id, $course->marker-1);
1670 $transaction->allow_commit();
1671 rebuild_course_cache($course->id, true);
1672 return true;
1676 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1677 * an original position number and a target position number, rebuilds the array so that the
1678 * move is made without any duplication of section positions.
1679 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1680 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1682 * @param array $sections
1683 * @param int $origin_position
1684 * @param int $target_position
1685 * @return array
1687 function reorder_sections($sections, $origin_position, $target_position) {
1688 if (!is_array($sections)) {
1689 return false;
1692 // We can't move section position 0
1693 if ($origin_position < 1) {
1694 echo "We can't move section position 0";
1695 return false;
1698 // Locate origin section in sections array
1699 if (!$origin_key = array_search($origin_position, $sections)) {
1700 echo "searched position not in sections array";
1701 return false; // searched position not in sections array
1704 // Extract origin section
1705 $origin_section = $sections[$origin_key];
1706 unset($sections[$origin_key]);
1708 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1709 $found = false;
1710 $append_array = array();
1711 foreach ($sections as $id => $position) {
1712 if ($found) {
1713 $append_array[$id] = $position;
1714 unset($sections[$id]);
1716 if ($position == $target_position) {
1717 if ($target_position < $origin_position) {
1718 $append_array[$id] = $position;
1719 unset($sections[$id]);
1721 $found = true;
1725 // Append moved section
1726 $sections[$origin_key] = $origin_section;
1728 // Append rest of array (if applicable)
1729 if (!empty($append_array)) {
1730 foreach ($append_array as $id => $position) {
1731 $sections[$id] = $position;
1735 // Renumber positions
1736 $position = 0;
1737 foreach ($sections as $id => $p) {
1738 $sections[$id] = $position;
1739 $position++;
1742 return $sections;
1747 * Move the module object $mod to the specified $section
1748 * If $beforemod exists then that is the module
1749 * before which $modid should be inserted
1750 * All parameters are objects
1752 function moveto_module($mod, $section, $beforemod=NULL) {
1753 global $OUTPUT, $DB;
1755 /// Remove original module from original section
1756 if (! delete_mod_from_section($mod->id, $mod->section)) {
1757 echo $OUTPUT->notification("Could not delete module from existing section");
1760 // if moving to a hidden section then hide module
1761 if ($mod->section != $section->id) {
1762 if (!$section->visible && $mod->visible) {
1763 // Set this in the object because it is sent as a response to ajax calls.
1764 $mod->visible = 0;
1765 set_coursemodule_visible($mod->id, 0);
1766 // Set visibleold to 1 so module will be visible when section is made visible.
1767 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1769 if ($section->visible && !$mod->visible) {
1770 set_coursemodule_visible($mod->id, $mod->visibleold);
1771 // Set this in the object because it is sent as a response to ajax calls.
1772 $mod->visible = $mod->visibleold;
1776 /// Add the module into the new section
1777 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1778 return true;
1782 * Returns the list of all editing actions that current user can perform on the module
1784 * @param cm_info $mod The module to produce editing buttons for
1785 * @param int $indent The current indenting (default -1 means no move left-right actions)
1786 * @param int $sr The section to link back to (used for creating the links)
1787 * @return array array of action_link or pix_icon objects
1789 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1790 global $COURSE, $SITE;
1792 static $str;
1794 $coursecontext = context_course::instance($mod->course);
1795 $modcontext = context_module::instance($mod->id);
1797 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1798 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1800 // no permission to edit anything
1801 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1802 return array();
1805 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1807 if (!isset($str)) {
1808 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1809 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
1810 $str->assign = get_string('assignroles', 'role');
1811 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1812 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1813 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1814 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
1815 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
1816 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1819 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1821 if ($sr !== null) {
1822 $baseurl->param('sr', $sr);
1824 $actions = array();
1826 // AJAX edit title
1827 if ($mod->has_view() && $hasmanageactivities &&
1828 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
1829 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
1830 // we will not display link if we are on some other-course page (where we should not see this module anyway)
1831 $actions['title'] = new action_link(
1832 new moodle_url($baseurl, array('update' => $mod->id)),
1833 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
1834 null,
1835 array('class' => 'editing_title', 'title' => $str->edittitle)
1839 // leftright
1840 if ($hasmanageactivities) {
1841 if (right_to_left()) { // Exchange arrows on RTL
1842 $rightarrow = 't/left';
1843 $leftarrow = 't/right';
1844 } else {
1845 $rightarrow = 't/right';
1846 $leftarrow = 't/left';
1849 if ($indent > 0) {
1850 $actions['moveleft'] = new action_link(
1851 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1852 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1853 null,
1854 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
1857 if ($indent >= 0) {
1858 $actions['moveright'] = new action_link(
1859 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1860 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1861 null,
1862 array('class' => 'editing_moveright', 'title' => $str->moveright)
1867 // move
1868 if ($hasmanageactivities) {
1869 $actions['move'] = new action_link(
1870 new moodle_url($baseurl, array('copy' => $mod->id)),
1871 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1872 null,
1873 array('class' => 'editing_move', 'title' => $str->move)
1877 // Update
1878 if ($hasmanageactivities) {
1879 $actions['update'] = new action_link(
1880 new moodle_url($baseurl, array('update' => $mod->id)),
1881 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1882 null,
1883 array('class' => 'editing_update', 'title' => $str->update)
1887 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1888 // note that restoring on front page is never allowed
1889 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
1890 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
1891 $actions['duplicate'] = new action_link(
1892 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1893 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1894 null,
1895 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
1899 // Delete
1900 if ($hasmanageactivities) {
1901 $actions['delete'] = new action_link(
1902 new moodle_url($baseurl, array('delete' => $mod->id)),
1903 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1904 null,
1905 array('class' => 'editing_delete', 'title' => $str->delete)
1909 // hideshow
1910 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1911 if ($mod->visible) {
1912 $actions['hide'] = new action_link(
1913 new moodle_url($baseurl, array('hide' => $mod->id)),
1914 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1915 null,
1916 array('class' => 'editing_hide', 'title' => $str->hide)
1918 } else {
1919 $actions['show'] = new action_link(
1920 new moodle_url($baseurl, array('show' => $mod->id)),
1921 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1922 null,
1923 array('class' => 'editing_show', 'title' => $str->show)
1928 // groupmode
1929 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1930 if ($mod->coursegroupmodeforce) {
1931 $modgroupmode = $mod->coursegroupmode;
1932 } else {
1933 $modgroupmode = $mod->groupmode;
1935 if ($modgroupmode == SEPARATEGROUPS) {
1936 $groupmode = NOGROUPS;
1937 $grouptitle = $str->groupsseparate;
1938 $forcedgrouptitle = $str->forcedgroupsseparate;
1939 $actionname = 'groupsseparate';
1940 $groupimage = 't/groups';
1941 } else if ($modgroupmode == VISIBLEGROUPS) {
1942 $groupmode = SEPARATEGROUPS;
1943 $grouptitle = $str->groupsvisible;
1944 $forcedgrouptitle = $str->forcedgroupsvisible;
1945 $actionname = 'groupsvisible';
1946 $groupimage = 't/groupv';
1947 } else {
1948 $groupmode = VISIBLEGROUPS;
1949 $grouptitle = $str->groupsnone;
1950 $forcedgrouptitle = $str->forcedgroupsnone;
1951 $actionname = 'groupsnone';
1952 $groupimage = 't/groupn';
1954 if (!$mod->coursegroupmodeforce) {
1955 $actions[$actionname] = new action_link(
1956 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
1957 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1958 null,
1959 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
1961 } else {
1962 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
1966 // Assign
1967 if (has_capability('moodle/role:assign', $modcontext)){
1968 $actions['assign'] = new action_link(
1969 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1970 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1971 null,
1972 array('class' => 'editing_assign', 'title' => $str->assign)
1976 return $actions;
1980 * given a course object with shortname & fullname, this function will
1981 * truncate the the number of chars allowed and add ... if it was too long
1983 function course_format_name ($course,$max=100) {
1985 $context = context_course::instance($course->id);
1986 $shortname = format_string($course->shortname, true, array('context' => $context));
1987 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1988 $str = $shortname.': '. $fullname;
1989 if (textlib::strlen($str) <= $max) {
1990 return $str;
1992 else {
1993 return textlib::substr($str,0,$max-3).'...';
1998 * Is the user allowed to add this type of module to this course?
1999 * @param object $course the course settings. Only $course->id is used.
2000 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2001 * @return bool whether the current user is allowed to add this type of module to this course.
2003 function course_allowed_module($course, $modname) {
2004 if (is_numeric($modname)) {
2005 throw new coding_exception('Function course_allowed_module no longer
2006 supports numeric module ids. Please update your code to pass the module name.');
2009 $capability = 'mod/' . $modname . ':addinstance';
2010 if (!get_capability_info($capability)) {
2011 // Debug warning that the capability does not exist, but no more than once per page.
2012 static $warned = array();
2013 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2014 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2015 debugging('The module ' . $modname . ' does not define the standard capability ' .
2016 $capability , DEBUG_DEVELOPER);
2017 $warned[$modname] = 1;
2020 // If the capability does not exist, the module can always be added.
2021 return true;
2024 $coursecontext = context_course::instance($course->id);
2025 return has_capability($capability, $coursecontext);
2029 * Efficiently moves many courses around while maintaining
2030 * sortorder in order.
2032 * @param array $courseids is an array of course ids
2033 * @param int $categoryid
2034 * @return bool success
2036 function move_courses($courseids, $categoryid) {
2037 global $CFG, $DB, $OUTPUT;
2039 if (empty($courseids)) {
2040 // nothing to do
2041 return;
2044 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2045 return false;
2048 $courseids = array_reverse($courseids);
2049 $newparent = context_coursecat::instance($category->id);
2050 $i = 1;
2052 foreach ($courseids as $courseid) {
2053 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
2054 $course = new stdClass();
2055 $course->id = $courseid;
2056 $course->category = $category->id;
2057 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2058 if ($category->visible == 0) {
2059 // hide the course when moving into hidden category,
2060 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2061 $course->visible = 0;
2064 $DB->update_record('course', $course);
2065 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
2067 $context = context_course::instance($course->id);
2068 context_moved($context, $newparent);
2071 fix_course_sortorder();
2072 cache_helper::purge_by_event('changesincourse');
2074 return true;
2078 * Returns the display name of the given section that the course prefers
2080 * Implementation of this function is provided by course format
2081 * @see format_base::get_section_name()
2083 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2084 * @param int|stdClass $section Section object from database or just field course_sections.section
2085 * @return string Display name that the course format prefers, e.g. "Week 2"
2087 function get_section_name($courseorid, $section) {
2088 return course_get_format($courseorid)->get_section_name($section);
2092 * Tells if current course format uses sections
2094 * @param string $format Course format ID e.g. 'weeks' $course->format
2095 * @return bool
2097 function course_format_uses_sections($format) {
2098 $course = new stdClass();
2099 $course->format = $format;
2100 return course_get_format($course)->uses_sections();
2104 * Returns the information about the ajax support in the given source format
2106 * The returned object's property (boolean)capable indicates that
2107 * the course format supports Moodle course ajax features.
2108 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2110 * @param string $format
2111 * @return stdClass
2113 function course_format_ajax_support($format) {
2114 $course = new stdClass();
2115 $course->format = $format;
2116 return course_get_format($course)->supports_ajax();
2120 * Can the current user delete this course?
2121 * Course creators have exception,
2122 * 1 day after the creation they can sill delete the course.
2123 * @param int $courseid
2124 * @return boolean
2126 function can_delete_course($courseid) {
2127 global $USER, $DB;
2129 $context = context_course::instance($courseid);
2131 if (has_capability('moodle/course:delete', $context)) {
2132 return true;
2135 // hack: now try to find out if creator created this course recently (1 day)
2136 if (!has_capability('moodle/course:create', $context)) {
2137 return false;
2140 $since = time() - 60*60*24;
2142 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2143 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2145 return $DB->record_exists_select('log', $select, $params);
2149 * Save the Your name for 'Some role' strings.
2151 * @param integer $courseid the id of this course.
2152 * @param array $data the data that came from the course settings form.
2154 function save_local_role_names($courseid, $data) {
2155 global $DB;
2156 $context = context_course::instance($courseid);
2158 foreach ($data as $fieldname => $value) {
2159 if (strpos($fieldname, 'role_') !== 0) {
2160 continue;
2162 list($ignored, $roleid) = explode('_', $fieldname);
2164 // make up our mind whether we want to delete, update or insert
2165 if (!$value) {
2166 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2168 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2169 $rolename->name = $value;
2170 $DB->update_record('role_names', $rolename);
2172 } else {
2173 $rolename = new stdClass;
2174 $rolename->contextid = $context->id;
2175 $rolename->roleid = $roleid;
2176 $rolename->name = $value;
2177 $DB->insert_record('role_names', $rolename);
2183 * Returns options to use in course overviewfiles filemanager
2185 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2186 * may be empty if course does not exist yet (course create form)
2187 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2188 * or null if overviewfiles are disabled
2190 function course_overviewfiles_options($course) {
2191 global $CFG;
2192 if (empty($CFG->courseoverviewfileslimit)) {
2193 return null;
2195 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2196 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2197 $accepted_types = '*';
2198 } else {
2199 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2200 // Make sure extensions are prefixed with dot unless they are valid typegroups
2201 foreach ($accepted_types as $i => $type) {
2202 if (substr($type, 0, 1) !== '.') {
2203 require_once($CFG->libdir. '/filelib.php');
2204 if (!count(file_get_typegroup('extension', $type))) {
2205 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2206 $accepted_types[$i] = '.'. $type;
2207 $corrected = true;
2211 if (!empty($corrected)) {
2212 set_config('courseoverviewfilesext', join(',', $accepted_types));
2215 $options = array(
2216 'maxfiles' => $CFG->courseoverviewfileslimit,
2217 'maxbytes' => $CFG->maxbytes,
2218 'subdirs' => 0,
2219 'accepted_types' => $accepted_types
2221 if (!empty($course->id)) {
2222 $options['context'] = context_course::instance($course->id);
2223 } else if (is_int($course) && $course > 0) {
2224 $options['context'] = context_course::instance($course);
2226 return $options;
2230 * Create a course and either return a $course object
2232 * Please note this functions does not verify any access control,
2233 * the calling code is responsible for all validation (usually it is the form definition).
2235 * @param array $editoroptions course description editor options
2236 * @param object $data - all the data needed for an entry in the 'course' table
2237 * @return object new course instance
2239 function create_course($data, $editoroptions = NULL) {
2240 global $CFG, $DB;
2242 //check the categoryid - must be given for all new courses
2243 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2245 //check if the shortname already exist
2246 if (!empty($data->shortname)) {
2247 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2248 throw new moodle_exception('shortnametaken');
2252 //check if the id number already exist
2253 if (!empty($data->idnumber)) {
2254 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2255 throw new moodle_exception('idnumbertaken');
2259 $data->timecreated = time();
2260 $data->timemodified = $data->timecreated;
2262 // place at beginning of any category
2263 $data->sortorder = 0;
2265 if ($editoroptions) {
2266 // summary text is updated later, we need context to store the files first
2267 $data->summary = '';
2268 $data->summary_format = FORMAT_HTML;
2271 if (!isset($data->visible)) {
2272 // data not from form, add missing visibility info
2273 $data->visible = $category->visible;
2275 $data->visibleold = $data->visible;
2277 $newcourseid = $DB->insert_record('course', $data);
2278 $context = context_course::instance($newcourseid, MUST_EXIST);
2280 if ($editoroptions) {
2281 // Save the files used in the summary editor and store
2282 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2283 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2284 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2286 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2287 // Save the course overviewfiles
2288 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2291 // update course format options
2292 course_get_format($newcourseid)->update_course_format_options($data);
2294 $course = course_get_format($newcourseid)->get_course();
2296 // Setup the blocks
2297 blocks_add_default_course_blocks($course);
2299 // Create a default section.
2300 course_create_sections_if_missing($course, 0);
2302 fix_course_sortorder();
2303 // purge appropriate caches in case fix_course_sortorder() did not change anything
2304 cache_helper::purge_by_event('changesincourse');
2306 // new context created - better mark it as dirty
2307 mark_context_dirty($context->path);
2309 // Save any custom role names.
2310 save_local_role_names($course->id, (array)$data);
2312 // set up enrolments
2313 enrol_course_updated(true, $course, $data);
2315 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2317 // Trigger events
2318 events_trigger('course_created', $course);
2320 return $course;
2324 * Update a course.
2326 * Please note this functions does not verify any access control,
2327 * the calling code is responsible for all validation (usually it is the form definition).
2329 * @param object $data - all the data needed for an entry in the 'course' table
2330 * @param array $editoroptions course description editor options
2331 * @return void
2333 function update_course($data, $editoroptions = NULL) {
2334 global $CFG, $DB;
2336 $data->timemodified = time();
2338 $oldcourse = course_get_format($data->id)->get_course();
2339 $context = context_course::instance($oldcourse->id);
2341 if ($editoroptions) {
2342 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2344 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2345 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2348 if (!isset($data->category) or empty($data->category)) {
2349 // prevent nulls and 0 in category field
2350 unset($data->category);
2352 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2354 if (!isset($data->visible)) {
2355 // data not from form, add missing visibility info
2356 $data->visible = $oldcourse->visible;
2359 if ($data->visible != $oldcourse->visible) {
2360 // reset the visibleold flag when manually hiding/unhiding course
2361 $data->visibleold = $data->visible;
2362 $changesincoursecat = true;
2363 } else {
2364 if ($movecat) {
2365 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2366 if (empty($newcategory->visible)) {
2367 // make sure when moving into hidden category the course is hidden automatically
2368 $data->visible = 0;
2373 // Update with the new data
2374 $DB->update_record('course', $data);
2375 // make sure the modinfo cache is reset
2376 rebuild_course_cache($data->id);
2378 // update course format options with full course data
2379 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2381 $course = $DB->get_record('course', array('id'=>$data->id));
2383 if ($movecat) {
2384 $newparent = context_coursecat::instance($course->category);
2385 context_moved($context, $newparent);
2388 fix_course_sortorder();
2389 // purge appropriate caches in case fix_course_sortorder() did not change anything
2390 cache_helper::purge_by_event('changesincourse');
2391 if ($changesincoursecat) {
2392 cache_helper::purge_by_event('changesincoursecat');
2395 // Test for and remove blocks which aren't appropriate anymore
2396 blocks_remove_inappropriate($course);
2398 // Save any custom role names.
2399 save_local_role_names($course->id, $data);
2401 // update enrol settings
2402 enrol_course_updated(false, $course, $data);
2404 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2406 // Trigger events
2407 events_trigger('course_updated', $course);
2409 if ($oldcourse->format !== $course->format) {
2410 // Remove all options stored for the previous format
2411 // We assume that new course format migrated everything it needed watching trigger
2412 // 'course_updated' and in method format_XXX::update_course_format_options()
2413 $DB->delete_records('course_format_options',
2414 array('courseid' => $course->id, 'format' => $oldcourse->format));
2419 * Average number of participants
2420 * @return integer
2422 function average_number_of_participants() {
2423 global $DB, $SITE;
2425 //count total of enrolments for visible course (except front page)
2426 $sql = 'SELECT COUNT(*) FROM (
2427 SELECT DISTINCT ue.userid, e.courseid
2428 FROM {user_enrolments} ue, {enrol} e, {course} c
2429 WHERE ue.enrolid = e.id
2430 AND e.courseid <> :siteid
2431 AND c.id = e.courseid
2432 AND c.visible = 1) total';
2433 $params = array('siteid' => $SITE->id);
2434 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2437 //count total of visible courses (minus front page)
2438 $coursetotal = $DB->count_records('course', array('visible' => 1));
2439 $coursetotal = $coursetotal - 1 ;
2441 //average of enrolment
2442 if (empty($coursetotal)) {
2443 $participantaverage = 0;
2444 } else {
2445 $participantaverage = $enrolmenttotal / $coursetotal;
2448 return $participantaverage;
2452 * Average number of course modules
2453 * @return integer
2455 function average_number_of_courses_modules() {
2456 global $DB, $SITE;
2458 //count total of visible course module (except front page)
2459 $sql = 'SELECT COUNT(*) FROM (
2460 SELECT cm.course, cm.module
2461 FROM {course} c, {course_modules} cm
2462 WHERE c.id = cm.course
2463 AND c.id <> :siteid
2464 AND cm.visible = 1
2465 AND c.visible = 1) total';
2466 $params = array('siteid' => $SITE->id);
2467 $moduletotal = $DB->count_records_sql($sql, $params);
2470 //count total of visible courses (minus front page)
2471 $coursetotal = $DB->count_records('course', array('visible' => 1));
2472 $coursetotal = $coursetotal - 1 ;
2474 //average of course module
2475 if (empty($coursetotal)) {
2476 $coursemoduleaverage = 0;
2477 } else {
2478 $coursemoduleaverage = $moduletotal / $coursetotal;
2481 return $coursemoduleaverage;
2485 * This class pertains to course requests and contains methods associated with
2486 * create, approving, and removing course requests.
2488 * Please note we do not allow embedded images here because there is no context
2489 * to store them with proper access control.
2491 * @copyright 2009 Sam Hemelryk
2492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2493 * @since Moodle 2.0
2495 * @property-read int $id
2496 * @property-read string $fullname
2497 * @property-read string $shortname
2498 * @property-read string $summary
2499 * @property-read int $summaryformat
2500 * @property-read int $summarytrust
2501 * @property-read string $reason
2502 * @property-read int $requester
2504 class course_request {
2507 * This is the stdClass that stores the properties for the course request
2508 * and is externally accessed through the __get magic method
2509 * @var stdClass
2511 protected $properties;
2514 * An array of options for the summary editor used by course request forms.
2515 * This is initially set by {@link summary_editor_options()}
2516 * @var array
2517 * @static
2519 protected static $summaryeditoroptions;
2522 * Static function to prepare the summary editor for working with a course
2523 * request.
2525 * @static
2526 * @param null|stdClass $data Optional, an object containing the default values
2527 * for the form, these may be modified when preparing the
2528 * editor so this should be called before creating the form
2529 * @return stdClass An object that can be used to set the default values for
2530 * an mforms form
2532 public static function prepare($data=null) {
2533 if ($data === null) {
2534 $data = new stdClass;
2536 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2537 return $data;
2541 * Static function to create a new course request when passed an array of properties
2542 * for it.
2544 * This function also handles saving any files that may have been used in the editor
2546 * @static
2547 * @param stdClass $data
2548 * @return course_request The newly created course request
2550 public static function create($data) {
2551 global $USER, $DB, $CFG;
2552 $data->requester = $USER->id;
2554 // Setting the default category if none set.
2555 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2556 $data->category = $CFG->defaultrequestcategory;
2559 // Summary is a required field so copy the text over
2560 $data->summary = $data->summary_editor['text'];
2561 $data->summaryformat = $data->summary_editor['format'];
2563 $data->id = $DB->insert_record('course_request', $data);
2565 // Create a new course_request object and return it
2566 $request = new course_request($data);
2568 // Notify the admin if required.
2569 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2571 $a = new stdClass;
2572 $a->link = "$CFG->wwwroot/course/pending.php";
2573 $a->user = fullname($USER);
2574 $subject = get_string('courserequest');
2575 $message = get_string('courserequestnotifyemail', 'admin', $a);
2576 foreach ($users as $user) {
2577 $request->notify($user, $USER, 'courserequested', $subject, $message);
2581 return $request;
2585 * Returns an array of options to use with a summary editor
2587 * @uses course_request::$summaryeditoroptions
2588 * @return array An array of options to use with the editor
2590 public static function summary_editor_options() {
2591 global $CFG;
2592 if (self::$summaryeditoroptions === null) {
2593 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2595 return self::$summaryeditoroptions;
2599 * Loads the properties for this course request object. Id is required and if
2600 * only id is provided then we load the rest of the properties from the database
2602 * @param stdClass|int $properties Either an object containing properties
2603 * or the course_request id to load
2605 public function __construct($properties) {
2606 global $DB;
2607 if (empty($properties->id)) {
2608 if (empty($properties)) {
2609 throw new coding_exception('You must provide a course request id when creating a course_request object');
2611 $id = $properties;
2612 $properties = new stdClass;
2613 $properties->id = (int)$id;
2614 unset($id);
2616 if (empty($properties->requester)) {
2617 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2618 print_error('unknowncourserequest');
2620 } else {
2621 $this->properties = $properties;
2623 $this->properties->collision = null;
2627 * Returns the requested property
2629 * @param string $key
2630 * @return mixed
2632 public function __get($key) {
2633 return $this->properties->$key;
2637 * Override this to ensure empty($request->blah) calls return a reliable answer...
2639 * This is required because we define the __get method
2641 * @param mixed $key
2642 * @return bool True is it not empty, false otherwise
2644 public function __isset($key) {
2645 return (!empty($this->properties->$key));
2649 * Returns the user who requested this course
2651 * Uses a static var to cache the results and cut down the number of db queries
2653 * @staticvar array $requesters An array of cached users
2654 * @return stdClass The user who requested the course
2656 public function get_requester() {
2657 global $DB;
2658 static $requesters= array();
2659 if (!array_key_exists($this->properties->requester, $requesters)) {
2660 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2662 return $requesters[$this->properties->requester];
2666 * Checks that the shortname used by the course does not conflict with any other
2667 * courses that exist
2669 * @param string|null $shortnamemark The string to append to the requests shortname
2670 * should a conflict be found
2671 * @return bool true is there is a conflict, false otherwise
2673 public function check_shortname_collision($shortnamemark = '[*]') {
2674 global $DB;
2676 if ($this->properties->collision !== null) {
2677 return $this->properties->collision;
2680 if (empty($this->properties->shortname)) {
2681 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2682 $this->properties->collision = false;
2683 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2684 if (!empty($shortnamemark)) {
2685 $this->properties->shortname .= ' '.$shortnamemark;
2687 $this->properties->collision = true;
2688 } else {
2689 $this->properties->collision = false;
2691 return $this->properties->collision;
2695 * Returns the category where this course request should be created
2697 * Note that we don't check here that user has a capability to view
2698 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2699 * 'moodle/course:changecategory'
2701 * @return coursecat
2703 public function get_category() {
2704 global $CFG;
2705 require_once($CFG->libdir.'/coursecatlib.php');
2706 // If the category is not set, if the current user does not have the rights to change the category, or if the
2707 // category does not exist, we set the default category to the course to be approved.
2708 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2709 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2710 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2711 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2713 if (!$category) {
2714 $category = coursecat::get_default();
2716 return $category;
2720 * This function approves the request turning it into a course
2722 * This function converts the course request into a course, at the same time
2723 * transferring any files used in the summary to the new course and then removing
2724 * the course request and the files associated with it.
2726 * @return int The id of the course that was created from this request
2728 public function approve() {
2729 global $CFG, $DB, $USER;
2731 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2733 $courseconfig = get_config('moodlecourse');
2735 // Transfer appropriate settings
2736 $data = clone($this->properties);
2737 unset($data->id);
2738 unset($data->reason);
2739 unset($data->requester);
2741 // Set category
2742 $category = $this->get_category();
2743 $data->category = $category->id;
2744 // Set misc settings
2745 $data->requested = 1;
2747 // Apply course default settings
2748 $data->format = $courseconfig->format;
2749 $data->newsitems = $courseconfig->newsitems;
2750 $data->showgrades = $courseconfig->showgrades;
2751 $data->showreports = $courseconfig->showreports;
2752 $data->maxbytes = $courseconfig->maxbytes;
2753 $data->groupmode = $courseconfig->groupmode;
2754 $data->groupmodeforce = $courseconfig->groupmodeforce;
2755 $data->visible = $courseconfig->visible;
2756 $data->visibleold = $data->visible;
2757 $data->lang = $courseconfig->lang;
2759 $course = create_course($data);
2760 $context = context_course::instance($course->id, MUST_EXIST);
2762 // add enrol instances
2763 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2764 if ($manual = enrol_get_plugin('manual')) {
2765 $manual->add_default_instance($course);
2769 // enrol the requester as teacher if necessary
2770 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2771 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2774 $this->delete();
2776 $a = new stdClass();
2777 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2778 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2779 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
2781 return $course->id;
2785 * Reject a course request
2787 * This function rejects a course request, emailing the requesting user the
2788 * provided notice and then removing the request from the database
2790 * @param string $notice The message to display to the user
2792 public function reject($notice) {
2793 global $USER, $DB;
2794 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2795 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2796 $this->delete();
2800 * Deletes the course request and any associated files
2802 public function delete() {
2803 global $DB;
2804 $DB->delete_records('course_request', array('id' => $this->properties->id));
2808 * Send a message from one user to another using events_trigger
2810 * @param object $touser
2811 * @param object $fromuser
2812 * @param string $name
2813 * @param string $subject
2814 * @param string $message
2816 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
2817 $eventdata = new stdClass();
2818 $eventdata->component = 'moodle';
2819 $eventdata->name = $name;
2820 $eventdata->userfrom = $fromuser;
2821 $eventdata->userto = $touser;
2822 $eventdata->subject = $subject;
2823 $eventdata->fullmessage = $message;
2824 $eventdata->fullmessageformat = FORMAT_PLAIN;
2825 $eventdata->fullmessagehtml = '';
2826 $eventdata->smallmessage = '';
2827 $eventdata->notification = 1;
2828 message_send($eventdata);
2833 * Return a list of page types
2834 * @param string $pagetype current page type
2835 * @param context $parentcontext Block's parent context
2836 * @param context $currentcontext Current context of block
2837 * @return array array of page types
2839 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2840 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2841 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2842 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2843 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2845 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2846 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2847 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2848 } else {
2849 // Otherwise consider it a page inside a course even if $currentcontext is null
2850 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2851 'course-*' => get_string('page-course-x', 'pagetype'),
2852 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2855 return $pagetypes;
2859 * Determine whether course ajax should be enabled for the specified course
2861 * @param stdClass $course The course to test against
2862 * @return boolean Whether course ajax is enabled or note
2864 function course_ajax_enabled($course) {
2865 global $CFG, $PAGE, $SITE;
2867 // Ajax must be enabled globally
2868 if (!$CFG->enableajax) {
2869 return false;
2872 // The user must be editing for AJAX to be included
2873 if (!$PAGE->user_is_editing()) {
2874 return false;
2877 // Check that the theme suports
2878 if (!$PAGE->theme->enablecourseajax) {
2879 return false;
2882 // Check that the course format supports ajax functionality
2883 // The site 'format' doesn't have information on course format support
2884 if ($SITE->id !== $course->id) {
2885 $courseformatajaxsupport = course_format_ajax_support($course->format);
2886 if (!$courseformatajaxsupport->capable) {
2887 return false;
2891 // All conditions have been met so course ajax should be enabled
2892 return true;
2896 * Include the relevant javascript and language strings for the resource
2897 * toolbox YUI module
2899 * @param integer $id The ID of the course being applied to
2900 * @param array $usedmodules An array containing the names of the modules in use on the page
2901 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
2902 * @param stdClass $config An object containing configuration parameters for ajax modules including:
2903 * * resourceurl The URL to post changes to for resource changes
2904 * * sectionurl The URL to post changes to for section changes
2905 * * pageparams Additional parameters to pass through in the post
2906 * @return bool
2908 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
2909 global $PAGE, $SITE;
2911 // Ensure that ajax should be included
2912 if (!course_ajax_enabled($course)) {
2913 return false;
2916 if (!$config) {
2917 $config = new stdClass();
2920 // The URL to use for resource changes
2921 if (!isset($config->resourceurl)) {
2922 $config->resourceurl = '/course/rest.php';
2925 // The URL to use for section changes
2926 if (!isset($config->sectionurl)) {
2927 $config->sectionurl = '/course/rest.php';
2930 // Any additional parameters which need to be included on page submission
2931 if (!isset($config->pageparams)) {
2932 $config->pageparams = array();
2935 // Include toolboxes
2936 $PAGE->requires->yui_module('moodle-course-toolboxes',
2937 'M.course.init_resource_toolbox',
2938 array(array(
2939 'courseid' => $course->id,
2940 'ajaxurl' => $config->resourceurl,
2941 'config' => $config,
2944 $PAGE->requires->yui_module('moodle-course-toolboxes',
2945 'M.course.init_section_toolbox',
2946 array(array(
2947 'courseid' => $course->id,
2948 'format' => $course->format,
2949 'ajaxurl' => $config->sectionurl,
2950 'config' => $config,
2954 // Include course dragdrop
2955 if ($course->id != $SITE->id) {
2956 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
2957 array(array(
2958 'courseid' => $course->id,
2959 'ajaxurl' => $config->sectionurl,
2960 'config' => $config,
2961 )), null, true);
2963 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
2964 array(array(
2965 'courseid' => $course->id,
2966 'ajaxurl' => $config->resourceurl,
2967 'config' => $config,
2968 )), null, true);
2971 // Require various strings for the command toolbox
2972 $PAGE->requires->strings_for_js(array(
2973 'moveleft',
2974 'deletechecktype',
2975 'deletechecktypename',
2976 'edittitle',
2977 'edittitleinstructions',
2978 'show',
2979 'hide',
2980 'groupsnone',
2981 'groupsvisible',
2982 'groupsseparate',
2983 'clicktochangeinbrackets',
2984 'markthistopic',
2985 'markedthistopic',
2986 'move',
2987 'movesection',
2988 ), 'moodle');
2990 // Include format-specific strings
2991 if ($course->id != $SITE->id) {
2992 $PAGE->requires->strings_for_js(array(
2993 'showfromothers',
2994 'hidefromothers',
2995 ), 'format_' . $course->format);
2998 // For confirming resource deletion we need the name of the module in question
2999 foreach ($usedmodules as $module => $modname) {
3000 $PAGE->requires->string_for_js('pluginname', $module);
3003 // Load drag and drop upload AJAX.
3004 dndupload_add_to_course($course, $enabledmodules);
3006 return true;
3010 * Returns the sorted list of available course formats, filtered by enabled if necessary
3012 * @param bool $enabledonly return only formats that are enabled
3013 * @return array array of sorted format names
3015 function get_sorted_course_formats($enabledonly = false) {
3016 global $CFG;
3017 $formats = get_plugin_list('format');
3019 if (!empty($CFG->format_plugins_sortorder)) {
3020 $order = explode(',', $CFG->format_plugins_sortorder);
3021 $order = array_merge(array_intersect($order, array_keys($formats)),
3022 array_diff(array_keys($formats), $order));
3023 } else {
3024 $order = array_keys($formats);
3026 if (!$enabledonly) {
3027 return $order;
3029 $sortedformats = array();
3030 foreach ($order as $formatname) {
3031 if (!get_config('format_'.$formatname, 'disabled')) {
3032 $sortedformats[] = $formatname;
3035 return $sortedformats;
3039 * The URL to use for the specified course (with section)
3041 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3042 * @param int|stdClass $section Section object from database or just field course_sections.section
3043 * if omitted the course view page is returned
3044 * @param array $options options for view URL. At the moment core uses:
3045 * 'navigation' (bool) if true and section has no separate page, the function returns null
3046 * 'sr' (int) used by multipage formats to specify to which section to return
3047 * @return moodle_url The url of course
3049 function course_get_url($courseorid, $section = null, $options = array()) {
3050 return course_get_format($courseorid)->get_view_url($section, $options);
3054 * Create a module.
3056 * It includes:
3057 * - capability checks and other checks
3058 * - create the module from the module info
3060 * @param object $module
3061 * @return object the created module info
3063 function create_module($moduleinfo) {
3064 global $DB, $CFG;
3066 require_once($CFG->dirroot . '/course/modlib.php');
3068 // Check manadatory attributs.
3069 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3070 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3071 $mandatoryfields[] = 'introeditor';
3073 foreach($mandatoryfields as $mandatoryfield) {
3074 if (!isset($moduleinfo->{$mandatoryfield})) {
3075 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3079 // Some additional checks (capability / existing instances).
3080 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3081 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3083 // Load module library.
3084 include_modulelib($module->name);
3086 // Add the module.
3087 $moduleinfo->module = $module->id;
3088 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3090 return $moduleinfo;
3094 * Update a module.
3096 * It includes:
3097 * - capability and other checks
3098 * - update the module
3100 * @param object $module
3101 * @return object the updated module info
3103 function update_module($moduleinfo) {
3104 global $DB, $CFG;
3106 require_once($CFG->dirroot . '/course/modlib.php');
3108 // Check the course module exists.
3109 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3111 // Check the course exists.
3112 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3114 // Some checks (capaibility / existing instances).
3115 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3117 // Load module library.
3118 include_modulelib($module->name);
3120 // Retrieve few information needed by update_moduleinfo.
3121 $moduleinfo->modulename = $cm->modname;
3122 if (!isset($moduleinfo->scale)) {
3123 $moduleinfo->scale = 0;
3125 $moduleinfo->type = 'mod';
3127 // Update the module.
3128 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3130 return $moduleinfo;
3134 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3135 * Sorts by descending order of time.
3137 * @param stdClass $a First object
3138 * @param stdClass $b Second object
3139 * @return int 0,1,-1 representing the order
3141 function compare_activities_by_time_desc($a, $b) {
3142 // Make sure the activities actually have a timestamp property.
3143 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3144 return 0;
3146 // We treat instances without timestamp as if they have a timestamp of 0.
3147 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3148 return 1;
3150 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3151 return -1;
3153 if ($a->timestamp == $b->timestamp) {
3154 return 0;
3156 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3160 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3161 * Sorts by ascending order of time.
3163 * @param stdClass $a First object
3164 * @param stdClass $b Second object
3165 * @return int 0,1,-1 representing the order
3167 function compare_activities_by_time_asc($a, $b) {
3168 // Make sure the activities actually have a timestamp property.
3169 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3170 return 0;
3172 // We treat instances without timestamp as if they have a timestamp of 0.
3173 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3174 return -1;
3176 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3177 return 1;
3179 if ($a->timestamp == $b->timestamp) {
3180 return 0;
3182 return ($a->timestamp < $b->timestamp) ? -1 : 1;