Merge branch '43675-27' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / deprecatedlib.php
bloba24e8ee885821db756a23e049a28baa7ba1dbadd
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 * deprecatedlib.php - Old functions retained only for backward compatibility
21 * Old functions retained only for backward compatibility. New code should not
22 * use any of these functions.
24 * @package core
25 * @subpackage deprecated
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 * @deprecated
31 defined('MOODLE_INTERNAL') || die();
33 /**
34 * Checks whether the password compatibility library will work with the current
35 * version of PHP. This cannot be done using PHP version numbers since the fix
36 * has been backported to earlier versions in some distributions.
38 * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
40 * @deprecated since 2.7 PHP 5.4.x should be always compatible.
42 * @return bool always returns false
44 function password_compat_not_supported() {
45 debugging('Do not use password_compat_not_supported() - bcrypt is now always available', DEBUG_DEVELOPER);
46 return false;
49 /**
50 * Factory method that was returning moodle_session object.
52 * @deprecated since 2.6
53 * @return \core\session\manager
55 function session_get_instance() {
56 // Note: the new session manager includes all methods from the original session class.
57 static $deprecatedinstance = null;
59 debugging('session_get_instance() is deprecated, use \core\session\manager instead', DEBUG_DEVELOPER);
61 if (!$deprecatedinstance) {
62 $deprecatedinstance = new \core\session\manager();
65 return $deprecatedinstance;
68 /**
69 * Returns true if legacy session used.
71 * @deprecated since 2.6
72 * @return bool
74 function session_is_legacy() {
75 debugging('session_is_legacy() is deprecated, do not use any more', DEBUG_DEVELOPER);
76 return false;
79 /**
80 * Terminates all sessions, auth hooks are not executed.
81 * Useful in upgrade scripts.
83 * @deprecated since 2.6
85 function session_kill_all() {
86 debugging('session_kill_all() is deprecated, use \core\session\manager::kill_all_sessions() instead', DEBUG_DEVELOPER);
87 \core\session\manager::kill_all_sessions();
90 /**
91 * Mark session as accessed, prevents timeouts.
93 * @deprecated since 2.6
94 * @param string $sid
96 function session_touch($sid) {
97 debugging('session_touch() is deprecated, use \core\session\manager::touch_session() instead', DEBUG_DEVELOPER);
98 \core\session\manager::touch_session($sid);
102 * Terminates one sessions, auth hooks are not executed.
104 * @deprecated since 2.6
105 * @param string $sid session id
107 function session_kill($sid) {
108 debugging('session_kill() is deprecated, use \core\session\manager::kill_session() instead', DEBUG_DEVELOPER);
109 \core\session\manager::kill_session($sid);
113 * Terminates all sessions of one user, auth hooks are not executed.
114 * NOTE: This can not work for file based sessions!
116 * @deprecated since 2.6
117 * @param int $userid user id
119 function session_kill_user($userid) {
120 debugging('session_kill_user() is deprecated, use \core\session\manager::kill_user_sessions() instead', DEBUG_DEVELOPER);
121 \core\session\manager::kill_user_sessions($userid);
125 * Session garbage collection
126 * - verify timeout for all users
127 * - kill sessions of all deleted users
128 * - kill sessions of users with disabled plugins or 'nologin' plugin
130 * @deprecated since 2.6
132 function session_gc() {
133 debugging('session_gc() is deprecated, use \core\session\manager::gc() instead', DEBUG_DEVELOPER);
134 \core\session\manager::gc();
138 * Setup $USER object - called during login, loginas, etc.
140 * Call sync_user_enrolments() manually after log-in, or log-in-as.
142 * @deprecated since 2.6
143 * @param stdClass $user full user record object
144 * @return void
146 function session_set_user($user) {
147 debugging('session_set_user() is deprecated, use \core\session\manager::set_user() instead', DEBUG_DEVELOPER);
148 \core\session\manager::set_user($user);
152 * Is current $USER logged-in-as somebody else?
153 * @deprecated since 2.6
154 * @return bool
156 function session_is_loggedinas() {
157 debugging('session_is_loggedinas() is deprecated, use \core\session\manager::is_loggedinas() instead', DEBUG_DEVELOPER);
158 return \core\session\manager::is_loggedinas();
162 * Returns the $USER object ignoring current login-as session
163 * @deprecated since 2.6
164 * @return stdClass user object
166 function session_get_realuser() {
167 debugging('session_get_realuser() is deprecated, use \core\session\manager::get_realuser() instead', DEBUG_DEVELOPER);
168 return \core\session\manager::get_realuser();
172 * Login as another user - no security checks here.
173 * @deprecated since 2.6
174 * @param int $userid
175 * @param stdClass $context
176 * @return void
178 function session_loginas($userid, $context) {
179 debugging('session_loginas() is deprecated, use \core\session\manager::loginas() instead', DEBUG_DEVELOPER);
180 \core\session\manager::loginas($userid, $context);
184 * Minify JavaScript files.
186 * @deprecated since 2.6
188 * @param array $files
189 * @return string
191 function js_minify($files) {
192 debugging('js_minify() is deprecated, use core_minify::js_files() or core_minify::js() instead.');
193 return core_minify::js_files($files);
197 * Minify CSS files.
199 * @deprecated since 2.6
201 * @param array $files
202 * @return string
204 function css_minify_css($files) {
205 debugging('css_minify_css() is deprecated, use core_minify::css_files() or core_minify::css() instead.');
206 return core_minify::css_files($files);
210 * Function to call all event handlers when triggering an event
212 * @deprecated since 2.6
214 * @param string $eventname name of the event
215 * @param mixed $eventdata event data object
216 * @return int number of failed events
218 function events_trigger($eventname, $eventdata) {
219 // TODO: uncomment after conversion of all events in standard distribution
220 // debugging('events_trigger() is deprecated, please use new events instead', DEBUG_DEVELOPER);
221 return events_trigger_legacy($eventname, $eventdata);
225 * List all core subsystems and their location
227 * This is a whitelist of components that are part of the core and their
228 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
229 * plugin is not listed here and it does not have proper plugintype prefix,
230 * then it is considered as course activity module.
232 * The location is optionally dirroot relative path. NULL means there is no special
233 * directory for this subsystem. If the location is set, the subsystem's
234 * renderer.php is expected to be there.
236 * @deprecated since 2.6, use core_component::get_core_subsystems()
238 * @param bool $fullpaths false means relative paths from dirroot, use true for performance reasons
239 * @return array of (string)name => (string|null)location
241 function get_core_subsystems($fullpaths = false) {
242 global $CFG;
244 // NOTE: do not add any other debugging here, keep forever.
246 $subsystems = core_component::get_core_subsystems();
248 if ($fullpaths) {
249 return $subsystems;
252 debugging('Short paths are deprecated when using get_core_subsystems(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
254 $dlength = strlen($CFG->dirroot);
256 foreach ($subsystems as $k => $v) {
257 if ($v === null) {
258 continue;
260 $subsystems[$k] = substr($v, $dlength+1);
263 return $subsystems;
267 * Lists all plugin types.
269 * @deprecated since 2.6, use core_component::get_plugin_types()
271 * @param bool $fullpaths false means relative paths from dirroot
272 * @return array Array of strings - name=>location
274 function get_plugin_types($fullpaths = true) {
275 global $CFG;
277 // NOTE: do not add any other debugging here, keep forever.
279 $types = core_component::get_plugin_types();
281 if ($fullpaths) {
282 return $types;
285 debugging('Short paths are deprecated when using get_plugin_types(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
287 $dlength = strlen($CFG->dirroot);
289 foreach ($types as $k => $v) {
290 if ($k === 'theme') {
291 $types[$k] = 'theme';
292 continue;
294 $types[$k] = substr($v, $dlength+1);
297 return $types;
301 * Use when listing real plugins of one type.
303 * @deprecated since 2.6, use core_component::get_plugin_list()
305 * @param string $plugintype type of plugin
306 * @return array name=>fulllocation pairs of plugins of given type
308 function get_plugin_list($plugintype) {
310 // NOTE: do not add any other debugging here, keep forever.
312 if ($plugintype === '') {
313 $plugintype = 'mod';
316 return core_component::get_plugin_list($plugintype);
320 * Get a list of all the plugins of a given type that define a certain class
321 * in a certain file. The plugin component names and class names are returned.
323 * @deprecated since 2.6, use core_component::get_plugin_list_with_class()
325 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
326 * @param string $class the part of the name of the class after the
327 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
328 * names like report_courselist_thing. If you are looking for classes with
329 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
330 * @param string $file the name of file within the plugin that defines the class.
331 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
332 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
334 function get_plugin_list_with_class($plugintype, $class, $file) {
336 // NOTE: do not add any other debugging here, keep forever.
338 return core_component::get_plugin_list_with_class($plugintype, $class, $file);
342 * Returns the exact absolute path to plugin directory.
344 * @deprecated since 2.6, use core_component::get_plugin_directory()
346 * @param string $plugintype type of plugin
347 * @param string $name name of the plugin
348 * @return string full path to plugin directory; NULL if not found
350 function get_plugin_directory($plugintype, $name) {
352 // NOTE: do not add any other debugging here, keep forever.
354 if ($plugintype === '') {
355 $plugintype = 'mod';
358 return core_component::get_plugin_directory($plugintype, $name);
362 * Normalize the component name using the "frankenstyle" names.
364 * @deprecated since 2.6, use core_component::normalize_component()
366 * @param string $component
367 * @return array as (string)$type => (string)$plugin
369 function normalize_component($component) {
371 // NOTE: do not add any other debugging here, keep forever.
373 return core_component::normalize_component($component);
377 * Return exact absolute path to a plugin directory.
379 * @deprecated since 2.6, use core_component::normalize_component()
381 * @param string $component name such as 'moodle', 'mod_forum'
382 * @return string full path to component directory; NULL if not found
384 function get_component_directory($component) {
386 // NOTE: do not add any other debugging here, keep forever.
388 return core_component::get_component_directory($component);
392 // === Deprecated before 2.6.0 ===
395 * Hack to find out the GD version by parsing phpinfo output
397 * @return int GD version (1, 2, or 0)
399 function check_gd_version() {
400 // TODO: delete function in Moodle 2.7
401 debugging('check_gd_version() is deprecated, GD extension is always available now');
403 $gdversion = 0;
405 if (function_exists('gd_info')){
406 $gd_info = gd_info();
407 if (substr_count($gd_info['GD Version'], '2.')) {
408 $gdversion = 2;
409 } else if (substr_count($gd_info['GD Version'], '1.')) {
410 $gdversion = 1;
413 } else {
414 ob_start();
415 phpinfo(INFO_MODULES);
416 $phpinfo = ob_get_contents();
417 ob_end_clean();
419 $phpinfo = explode("\n", $phpinfo);
422 foreach ($phpinfo as $text) {
423 $parts = explode('</td>', $text);
424 foreach ($parts as $key => $val) {
425 $parts[$key] = trim(strip_tags($val));
427 if ($parts[0] == 'GD Version') {
428 if (substr_count($parts[1], '2.0')) {
429 $parts[1] = '2.0';
431 $gdversion = intval($parts[1]);
436 return $gdversion; // 1, 2 or 0
440 * Not used any more, the account lockout handling is now
441 * part of authenticate_user_login().
442 * @deprecated
444 function update_login_count() {
445 // TODO: delete function in Moodle 2.6
446 debugging('update_login_count() is deprecated, all calls need to be removed');
450 * Not used any more, replaced by proper account lockout.
451 * @deprecated
453 function reset_login_count() {
454 // TODO: delete function in Moodle 2.6
455 debugging('reset_login_count() is deprecated, all calls need to be removed');
459 * Insert or update log display entry. Entry may already exist.
460 * $module, $action must be unique
461 * @deprecated
463 * @param string $module
464 * @param string $action
465 * @param string $mtable
466 * @param string $field
467 * @return void
470 function update_log_display_entry($module, $action, $mtable, $field) {
471 global $DB;
473 debugging('The update_log_display_entry() is deprecated, please use db/log.php description file instead.');
477 * Given some text in HTML format, this function will pass it
478 * through any filters that have been configured for this context.
480 * @deprecated use the text formatting in a standard way instead (http://docs.moodle.org/dev/Output_functions)
481 * this was abused mostly for embedding of attachments
482 * @todo final deprecation of this function in MDL-40607
483 * @param string $text The text to be passed through format filters
484 * @param int $courseid The current course.
485 * @return string the filtered string.
487 function filter_text($text, $courseid = NULL) {
488 global $CFG, $COURSE;
490 debugging('filter_text() is deprecated, use format_text(), format_string() etc instead.', DEBUG_DEVELOPER);
492 if (!$courseid) {
493 $courseid = $COURSE->id;
496 if (!$context = context_course::instance($courseid, IGNORE_MISSING)) {
497 return $text;
500 return filter_manager::instance()->filter_text($text, $context);
504 * This function indicates that current page requires the https
505 * when $CFG->loginhttps enabled.
507 * By using this function properly, we can ensure 100% https-ized pages
508 * at our entire discretion (login, forgot_password, change_password)
509 * @deprecated use $PAGE->https_required() instead
510 * @todo final deprecation of this function in MDL-40607
512 function httpsrequired() {
513 global $PAGE;
514 debugging('httpsrequired() is deprecated use $PAGE->https_required() instead.', DEBUG_DEVELOPER);
515 $PAGE->https_required();
519 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
521 * @deprecated use moodle_url factory methods instead
523 * @param string $path Physical path to a file
524 * @param array $options associative array of GET variables to append to the URL
525 * @param string $type (questionfile|rssfile|httpscoursefile|coursefile)
526 * @return string URL to file
528 function get_file_url($path, $options=null, $type='coursefile') {
529 global $CFG;
531 $path = str_replace('//', '/', $path);
532 $path = trim($path, '/'); // no leading and trailing slashes
534 // type of file
535 switch ($type) {
536 case 'questionfile':
537 $url = $CFG->wwwroot."/question/exportfile.php";
538 break;
539 case 'rssfile':
540 $url = $CFG->wwwroot."/rss/file.php";
541 break;
542 case 'httpscoursefile':
543 $url = $CFG->httpswwwroot."/file.php";
544 break;
545 case 'coursefile':
546 default:
547 $url = $CFG->wwwroot."/file.php";
550 if ($CFG->slasharguments) {
551 $parts = explode('/', $path);
552 foreach ($parts as $key => $part) {
553 /// anchor dash character should not be encoded
554 $subparts = explode('#', $part);
555 $subparts = array_map('rawurlencode', $subparts);
556 $parts[$key] = implode('#', $subparts);
558 $path = implode('/', $parts);
559 $ffurl = $url.'/'.$path;
560 $separator = '?';
561 } else {
562 $path = rawurlencode('/'.$path);
563 $ffurl = $url.'?file='.$path;
564 $separator = '&amp;';
567 if ($options) {
568 foreach ($options as $name=>$value) {
569 $ffurl = $ffurl.$separator.$name.'='.$value;
570 $separator = '&amp;';
574 return $ffurl;
578 * Return all course participant for a given course
580 * @deprecated use get_enrolled_users($context) instead.
581 * @todo final deprecation of this function in MDL-40607
582 * @param integer $courseid
583 * @return array of user
585 function get_course_participants($courseid) {
586 debugging('get_course_participants() is deprecated, use get_enrolled_users() instead.', DEBUG_DEVELOPER);
587 return get_enrolled_users(context_course::instance($courseid));
591 * Return true if the user is a participant for a given course
593 * @deprecated use is_enrolled($context, $userid) instead.
594 * @todo final deprecation of this function in MDL-40607
595 * @param integer $userid
596 * @param integer $courseid
597 * @return boolean
599 function is_course_participant($userid, $courseid) {
600 debugging('is_course_participant() is deprecated, use is_enrolled() instead.', DEBUG_DEVELOPER);
601 return is_enrolled(context_course::instance($courseid), $userid);
605 * Searches logs to find all enrolments since a certain date
607 * used to print recent activity
609 * @param int $courseid The course in question.
610 * @param int $timestart The date to check forward of
611 * @return object|false {@link $USER} records or false if error.
613 function get_recent_enrolments($courseid, $timestart) {
614 global $DB;
616 debugging('get_recent_enrolments() is deprecated as it returned inaccurate results.', DEBUG_DEVELOPER);
618 $context = context_course::instance($courseid);
619 $sql = "SELECT u.id, u.firstname, u.lastname, MAX(l.time)
620 FROM {user} u, {role_assignments} ra, {log} l
621 WHERE l.time > ?
622 AND l.course = ?
623 AND l.module = 'course'
624 AND l.action = 'enrol'
625 AND ".$DB->sql_cast_char2int('l.info')." = u.id
626 AND u.id = ra.userid
627 AND ra.contextid ".get_related_contexts_string($context)."
628 GROUP BY u.id, u.firstname, u.lastname
629 ORDER BY MAX(l.time) ASC";
630 $params = array($timestart, $courseid);
631 return $DB->get_records_sql($sql, $params);
635 * @deprecated use clean_param($string, PARAM_FILE) instead.
636 * @todo final deprecation of this function in MDL-40607
638 * @param string $string ?
639 * @param int $allowdots ?
640 * @return bool
642 function detect_munged_arguments($string, $allowdots=1) {
643 debugging('detect_munged_arguments() is deprecated, please use clean_param(,PARAM_FILE) instead.', DEBUG_DEVELOPER);
644 if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references
645 return true;
647 if (preg_match('/[\|\`]/', $string)) { // check for other bad characters
648 return true;
650 if (empty($string) or $string == '/') {
651 return true;
654 return false;
659 * Unzip one zip file to a destination dir
660 * Both parameters must be FULL paths
661 * If destination isn't specified, it will be the
662 * SAME directory where the zip file resides.
664 * @global object
665 * @param string $zipfile The zip file to unzip
666 * @param string $destination The location to unzip to
667 * @param bool $showstatus_ignored Unused
669 function unzip_file($zipfile, $destination = '', $showstatus_ignored = true) {
670 global $CFG;
672 //Extract everything from zipfile
673 $path_parts = pathinfo(cleardoubleslashes($zipfile));
674 $zippath = $path_parts["dirname"]; //The path of the zip file
675 $zipfilename = $path_parts["basename"]; //The name of the zip file
676 $extension = $path_parts["extension"]; //The extension of the file
678 //If no file, error
679 if (empty($zipfilename)) {
680 return false;
683 //If no extension, error
684 if (empty($extension)) {
685 return false;
688 //Clear $zipfile
689 $zipfile = cleardoubleslashes($zipfile);
691 //Check zipfile exists
692 if (!file_exists($zipfile)) {
693 return false;
696 //If no destination, passed let's go with the same directory
697 if (empty($destination)) {
698 $destination = $zippath;
701 //Clear $destination
702 $destpath = rtrim(cleardoubleslashes($destination), "/");
704 //Check destination path exists
705 if (!is_dir($destpath)) {
706 return false;
709 $packer = get_file_packer('application/zip');
711 $result = $packer->extract_to_pathname($zipfile, $destpath);
713 if ($result === false) {
714 return false;
717 foreach ($result as $status) {
718 if ($status !== true) {
719 return false;
723 return true;
727 * Zip an array of files/dirs to a destination zip file
728 * Both parameters must be FULL paths to the files/dirs
730 * @global object
731 * @param array $originalfiles Files to zip
732 * @param string $destination The destination path
733 * @return bool Outcome
735 function zip_files ($originalfiles, $destination) {
736 global $CFG;
738 //Extract everything from destination
739 $path_parts = pathinfo(cleardoubleslashes($destination));
740 $destpath = $path_parts["dirname"]; //The path of the zip file
741 $destfilename = $path_parts["basename"]; //The name of the zip file
742 $extension = $path_parts["extension"]; //The extension of the file
744 //If no file, error
745 if (empty($destfilename)) {
746 return false;
749 //If no extension, add it
750 if (empty($extension)) {
751 $extension = 'zip';
752 $destfilename = $destfilename.'.'.$extension;
755 //Check destination path exists
756 if (!is_dir($destpath)) {
757 return false;
760 //Check destination path is writable. TODO!!
762 //Clean destination filename
763 $destfilename = clean_filename($destfilename);
765 //Now check and prepare every file
766 $files = array();
767 $origpath = NULL;
769 foreach ($originalfiles as $file) { //Iterate over each file
770 //Check for every file
771 $tempfile = cleardoubleslashes($file); // no doubleslashes!
772 //Calculate the base path for all files if it isn't set
773 if ($origpath === NULL) {
774 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
776 //See if the file is readable
777 if (!is_readable($tempfile)) { //Is readable
778 continue;
780 //See if the file/dir is in the same directory than the rest
781 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
782 continue;
784 //Add the file to the array
785 $files[] = $tempfile;
788 $zipfiles = array();
789 $start = strlen($origpath)+1;
790 foreach($files as $file) {
791 $zipfiles[substr($file, $start)] = $file;
794 $packer = get_file_packer('application/zip');
796 return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename);
800 * Get the IDs for the user's groups in the given course.
802 * @global object
803 * @param int $courseid The course being examined - the 'course' table id field.
804 * @return array|bool An _array_ of groupids, or false
805 * (Was return $groupids[0] - consequences!)
806 * @deprecated use groups_get_all_groups() instead.
807 * @todo final deprecation of this function in MDL-40607
809 function mygroupid($courseid) {
810 global $USER;
812 debugging('mygroupid() is deprecated, please use groups_get_all_groups() instead.', DEBUG_DEVELOPER);
814 if ($groups = groups_get_all_groups($courseid, $USER->id)) {
815 return array_keys($groups);
816 } else {
817 return false;
823 * Returns the current group mode for a given course or activity module
825 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
827 * @param object $course Course Object
828 * @param object $cm Course Manager Object
829 * @return mixed $course->groupmode
831 function groupmode($course, $cm=null) {
833 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
834 return $cm->groupmode;
836 return $course->groupmode;
840 * Sets the current group in the session variable
841 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
842 * Sets currentgroup[$courseid] in the session variable appropriately.
843 * Does not do any permission checking.
845 * @global object
846 * @param int $courseid The course being examined - relates to id field in
847 * 'course' table.
848 * @param int $groupid The group being examined.
849 * @return int Current group id which was set by this function
851 function set_current_group($courseid, $groupid) {
852 global $SESSION;
853 return $SESSION->currentgroup[$courseid] = $groupid;
858 * Gets the current group - either from the session variable or from the database.
860 * @global object
861 * @param int $courseid The course being examined - relates to id field in
862 * 'course' table.
863 * @param bool $full If true, the return value is a full record object.
864 * If false, just the id of the record.
865 * @return int|bool
867 function get_current_group($courseid, $full = false) {
868 global $SESSION;
870 if (isset($SESSION->currentgroup[$courseid])) {
871 if ($full) {
872 return groups_get_group($SESSION->currentgroup[$courseid]);
873 } else {
874 return $SESSION->currentgroup[$courseid];
878 $mygroupid = mygroupid($courseid);
879 if (is_array($mygroupid)) {
880 $mygroupid = array_shift($mygroupid);
881 set_current_group($courseid, $mygroupid);
882 if ($full) {
883 return groups_get_group($mygroupid);
884 } else {
885 return $mygroupid;
889 if ($full) {
890 return false;
891 } else {
892 return 0;
898 * Inndicates fatal error. This function was originally printing the
899 * error message directly, since 2.0 it is throwing exception instead.
900 * The error printing is handled in default exception handler.
902 * Old method, don't call directly in new code - use print_error instead.
904 * @param string $message The message to display to the user about the error.
905 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
906 * @return void, always throws moodle_exception
908 function error($message, $link='') {
909 throw new moodle_exception('notlocalisederrormessage', 'error', $link, $message, 'error() is a deprecated function, please call print_error() instead of error()');
914 * @deprecated use $PAGE->theme->name instead.
915 * @todo final deprecation of this function in MDL-40607
916 * @return string the name of the current theme.
918 function current_theme() {
919 global $PAGE;
921 debugging('current_theme() is deprecated, please use $PAGE->theme->name instead', DEBUG_DEVELOPER);
922 return $PAGE->theme->name;
926 * Prints some red text using echo
928 * @deprecated
929 * @param string $error The text to be displayed in red
931 function formerr($error) {
932 debugging('formerr() has been deprecated. Please change your code to use $OUTPUT->error_text($string).');
933 global $OUTPUT;
934 echo $OUTPUT->error_text($error);
938 * Return the markup for the destination of the 'Skip to main content' links.
939 * Accessibility improvement for keyboard-only users.
941 * Used in course formats, /index.php and /course/index.php
943 * @deprecated use $OUTPUT->skip_link_target() in instead.
944 * @todo final deprecation of this function in MDL-40607
945 * @return string HTML element.
947 function skip_main_destination() {
948 global $OUTPUT;
950 debugging('skip_main_destination() is deprecated, please use $OUTPUT->skip_link_target() instead.', DEBUG_DEVELOPER);
951 return $OUTPUT->skip_link_target();
955 * Print a message in a standard themed container.
957 * @deprecated use $OUTPUT->container() instead.
958 * @todo final deprecation of this function in MDL-40607
959 * @param string $message, the content of the container
960 * @param boolean $clearfix clear both sides
961 * @param string $classes, space-separated class names.
962 * @param string $idbase
963 * @param boolean $return, return as string or just print it
964 * @return string|void Depending on value of $return
966 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
967 global $OUTPUT;
969 debugging('print_container() is deprecated. Please use $OUTPUT->container() instead.', DEBUG_DEVELOPER);
970 if ($clearfix) {
971 $classes .= ' clearfix';
973 $output = $OUTPUT->container($message, $classes, $idbase);
974 if ($return) {
975 return $output;
976 } else {
977 echo $output;
982 * Starts a container using divs
984 * @deprecated use $OUTPUT->container_start() instead.
985 * @todo final deprecation of this function in MDL-40607
986 * @param boolean $clearfix clear both sides
987 * @param string $classes, space-separated class names.
988 * @param string $idbase
989 * @param boolean $return, return as string or just print it
990 * @return string|void Based on value of $return
992 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
993 global $OUTPUT;
995 debugging('print_container_start() is deprecated. Please use $OUTPUT->container_start() instead.', DEBUG_DEVELOPER);
997 if ($clearfix) {
998 $classes .= ' clearfix';
1000 $output = $OUTPUT->container_start($classes, $idbase);
1001 if ($return) {
1002 return $output;
1003 } else {
1004 echo $output;
1009 * Simple function to end a container (see above)
1011 * @deprecated use $OUTPUT->container_end() instead.
1012 * @todo final deprecation of this function in MDL-40607
1013 * @param boolean $return, return as string or just print it
1014 * @return string|void Based on $return
1016 function print_container_end($return=false) {
1017 global $OUTPUT;
1018 debugging('print_container_end() is deprecated. Please use $OUTPUT->container_end() instead.', DEBUG_DEVELOPER);
1019 $output = $OUTPUT->container_end();
1020 if ($return) {
1021 return $output;
1022 } else {
1023 echo $output;
1028 * Print a bold message in an optional color.
1030 * @deprecated use $OUTPUT->notification instead.
1031 * @param string $message The message to print out
1032 * @param string $style Optional style to display message text in
1033 * @param string $align Alignment option
1034 * @param bool $return whether to return an output string or echo now
1035 * @return string|bool Depending on $result
1037 function notify($message, $classes = 'notifyproblem', $align = 'center', $return = false) {
1038 global $OUTPUT;
1040 if ($classes == 'green') {
1041 debugging('Use of deprecated class name "green" in notify. Please change to "notifysuccess".', DEBUG_DEVELOPER);
1042 $classes = 'notifysuccess'; // Backward compatible with old color system
1045 $output = $OUTPUT->notification($message, $classes);
1046 if ($return) {
1047 return $output;
1048 } else {
1049 echo $output;
1054 * Print a continue button that goes to a particular URL.
1056 * @deprecated use $OUTPUT->continue_button() instead.
1057 * @todo final deprecation of this function in MDL-40607
1059 * @param string $link The url to create a link to.
1060 * @param bool $return If set to true output is returned rather than echoed, default false
1061 * @return string|void HTML String if return=true nothing otherwise
1063 function print_continue($link, $return = false) {
1064 global $CFG, $OUTPUT;
1066 debugging('print_continue() is deprecated. Please use $OUTPUT->continue_button() instead.', DEBUG_DEVELOPER);
1068 if ($link == '') {
1069 if (!empty($_SERVER['HTTP_REFERER'])) {
1070 $link = $_SERVER['HTTP_REFERER'];
1071 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
1072 } else {
1073 $link = $CFG->wwwroot .'/';
1077 $output = $OUTPUT->continue_button($link);
1078 if ($return) {
1079 return $output;
1080 } else {
1081 echo $output;
1086 * Print a standard header
1088 * @deprecated use $PAGE methods instead.
1089 * @todo final deprecation of this function in MDL-40607
1090 * @param string $title Appears at the top of the window
1091 * @param string $heading Appears at the top of the page
1092 * @param string $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
1093 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
1094 * @param string $meta Meta tags to be added to the header
1095 * @param boolean $cache Should this page be cacheable?
1096 * @param string $button HTML code for a button (usually for module editing)
1097 * @param string $menu HTML code for a popup menu
1098 * @param boolean $usexml use XML for this page
1099 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
1100 * @param bool $return If true, return the visible elements of the header instead of echoing them.
1101 * @return string|void If return=true then string else void
1103 function print_header($title='', $heading='', $navigation='', $focus='',
1104 $meta='', $cache=true, $button='&nbsp;', $menu=null,
1105 $usexml=false, $bodytags='', $return=false) {
1106 global $PAGE, $OUTPUT;
1108 debugging('print_header() is deprecated. Please use $PAGE methods instead.', DEBUG_DEVELOPER);
1110 $PAGE->set_title($title);
1111 $PAGE->set_heading($heading);
1112 $PAGE->set_cacheable($cache);
1113 if ($button == '') {
1114 $button = '&nbsp;';
1116 $PAGE->set_button($button);
1117 $PAGE->set_headingmenu($menu);
1119 // TODO $menu
1121 if ($meta) {
1122 throw new coding_exception('The $meta parameter to print_header is no longer supported. '.
1123 'You should be able to do everything you want with $PAGE->requires and other such mechanisms.');
1125 if ($usexml) {
1126 throw new coding_exception('The $usexml parameter to print_header is no longer supported.');
1128 if ($bodytags) {
1129 throw new coding_exception('The $bodytags parameter to print_header is no longer supported.');
1132 $output = $OUTPUT->header();
1134 if ($return) {
1135 return $output;
1136 } else {
1137 echo $output;
1142 * This version of print_header is simpler because the course name does not have to be
1143 * provided explicitly in the strings. It can be used on the site page as in courses
1144 * Eventually all print_header could be replaced by print_header_simple
1146 * @deprecated use $PAGE methods instead.
1147 * @todo final deprecation of this function in MDL-40607
1148 * @param string $title Appears at the top of the window
1149 * @param string $heading Appears at the top of the page
1150 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
1151 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
1152 * @param string $meta Meta tags to be added to the header
1153 * @param boolean $cache Should this page be cacheable?
1154 * @param string $button HTML code for a button (usually for module editing)
1155 * @param string $menu HTML code for a popup menu
1156 * @param boolean $usexml use XML for this page
1157 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
1158 * @param bool $return If true, return the visible elements of the header instead of echoing them.
1159 * @return string|void If $return=true the return string else nothing
1161 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
1162 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
1164 global $COURSE, $CFG, $PAGE, $OUTPUT;
1166 debugging('print_header_simple() is deprecated. Please use $PAGE methods instead.', DEBUG_DEVELOPER);
1168 if ($meta) {
1169 throw new coding_exception('The $meta parameter to print_header is no longer supported. '.
1170 'You should be able to do everything you want with $PAGE->requires and other such mechanisms.');
1172 if ($usexml) {
1173 throw new coding_exception('The $usexml parameter to print_header is no longer supported.');
1175 if ($bodytags) {
1176 throw new coding_exception('The $bodytags parameter to print_header is no longer supported.');
1179 $PAGE->set_title($title);
1180 $PAGE->set_heading($heading);
1181 $PAGE->set_cacheable(true);
1182 $PAGE->set_button($button);
1184 $output = $OUTPUT->header();
1186 if ($return) {
1187 return $output;
1188 } else {
1189 echo $output;
1194 * Prints a nice side block with an optional header. The content can either
1195 * be a block of HTML or a list of text with optional icons.
1197 * @static int $block_id Increments for each call to the function
1198 * @param string $heading HTML for the heading. Can include full HTML or just
1199 * plain text - plain text will automatically be enclosed in the appropriate
1200 * heading tags.
1201 * @param string $content HTML for the content
1202 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1203 * @param array $icons optional icons for the things in $list.
1204 * @param string $footer Extra HTML content that gets output at the end, inside a &lt;div class="footer">
1205 * @param array $attributes an array of attribute => value pairs that are put on the
1206 * outer div of this block. If there is a class attribute ' block' gets appended to it. If there isn't
1207 * already a class, class='block' is used.
1208 * @param string $title Plain text title, as embedded in the $heading.
1209 * @deprecated use $OUTPUT->block() instead.
1210 * @todo final deprecation of this function in MDL-40607
1212 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
1213 global $OUTPUT;
1215 debugging('print_side_block() is deprecated, please use $OUTPUT->block() instead.', DEBUG_DEVELOPER);
1216 // We don't use $heading, becuse it often contains HTML that we don't want.
1217 // However, sometimes $title is not set, but $heading is.
1218 if (empty($title)) {
1219 $title = strip_tags($heading);
1222 // Render list contents to HTML if required.
1223 if (empty($content) && $list) {
1224 $content = $OUTPUT->list_block_contents($icons, $list);
1227 $bc = new block_contents();
1228 $bc->content = $content;
1229 $bc->footer = $footer;
1230 $bc->title = $title;
1232 if (isset($attributes['id'])) {
1233 $bc->id = $attributes['id'];
1234 unset($attributes['id']);
1236 $bc->attributes = $attributes;
1238 echo $OUTPUT->block($bc, BLOCK_POS_LEFT); // POS LEFT may be wrong, but no way to get a better guess here.
1242 * Prints a basic textarea field.
1244 * @deprecated since Moodle 2.0
1246 * When using this function, you should
1248 * @global object
1249 * @param bool $unused No longer used.
1250 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
1251 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
1252 * @param null $width (Deprecated) Width of the element; if a value is passed, the minimum value for $cols will be 65. Value is otherwise ignored.
1253 * @param null $height (Deprecated) Height of the element; if a value is passe, the minimum value for $rows will be 10. Value is otherwise ignored.
1254 * @param string $name Name to use for the textarea element.
1255 * @param string $value Initial content to display in the textarea.
1256 * @param int $obsolete deprecated
1257 * @param bool $return If false, will output string. If true, will return string value.
1258 * @param string $id CSS ID to add to the textarea element.
1259 * @return string|void depending on the value of $return
1261 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
1262 /// $width and height are legacy fields and no longer used as pixels like they used to be.
1263 /// However, you can set them to zero to override the mincols and minrows values below.
1265 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
1266 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
1268 global $CFG;
1270 $mincols = 65;
1271 $minrows = 10;
1272 $str = '';
1274 if ($id === '') {
1275 $id = 'edit-'.$name;
1278 if ($height && ($rows < $minrows)) {
1279 $rows = $minrows;
1281 if ($width && ($cols < $mincols)) {
1282 $cols = $mincols;
1285 editors_head_setup();
1286 $editor = editors_get_preferred_editor(FORMAT_HTML);
1287 $editor->use_editor($id, array('legacy'=>true));
1289 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
1290 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
1291 $str .= '</textarea>'."\n";
1293 if ($return) {
1294 return $str;
1296 echo $str;
1300 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
1301 * Should be used only with htmleditor or textarea.
1303 * @global object
1304 * @global object
1305 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
1306 * helpbutton.
1307 * @return string Link to help button
1309 function editorhelpbutton(){
1310 return '';
1312 /// TODO: MDL-21215
1316 * Print a help button.
1318 * Prints a special help button for html editors (htmlarea in this case)
1320 * @todo Write code into this function! detect current editor and print correct info
1321 * @global object
1322 * @return string Only returns an empty string at the moment
1324 function editorshortcutshelpbutton() {
1325 /// TODO: MDL-21215
1327 global $CFG;
1328 //TODO: detect current editor and print correct info
1329 return '';
1334 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
1335 * provide this function with the language strings for sortasc and sortdesc.
1337 * @deprecated use $OUTPUT->arrow() instead.
1338 * @todo final deprecation of this function in MDL-40607
1340 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
1342 * @global object
1343 * @param string $direction 'up' or 'down'
1344 * @param string $strsort The language string used for the alt attribute of this image
1345 * @param bool $return Whether to print directly or return the html string
1346 * @return string|void depending on $return
1349 function print_arrow($direction='up', $strsort=null, $return=false) {
1350 global $OUTPUT;
1352 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER);
1354 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
1355 return null;
1358 $return = null;
1360 switch ($direction) {
1361 case 'up':
1362 $sortdir = 'asc';
1363 break;
1364 case 'down':
1365 $sortdir = 'desc';
1366 break;
1367 case 'move':
1368 $sortdir = 'asc';
1369 break;
1370 default:
1371 $sortdir = null;
1372 break;
1375 // Prepare language string
1376 $strsort = '';
1377 if (empty($strsort) && !empty($sortdir)) {
1378 $strsort = get_string('sort' . $sortdir, 'grades');
1381 $return = ' <img src="'.$OUTPUT->pix_url('t/' . $direction) . '" alt="'.$strsort.'" /> ';
1383 if ($return) {
1384 return $return;
1385 } else {
1386 echo $return;
1391 * Given an array of values, output the HTML for a select element with those options.
1393 * @deprecated since Moodle 2.0
1395 * Normally, you only need to use the first few parameters.
1397 * @param array $options The options to offer. An array of the form
1398 * $options[{value}] = {text displayed for that option};
1399 * @param string $name the name of this form control, as in &lt;select name="..." ...
1400 * @param string $selected the option to select initially, default none.
1401 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
1402 * Set this to '' if you don't want a 'nothing is selected' option.
1403 * @param string $script if not '', then this is added to the &lt;select> element as an onchange handler.
1404 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
1405 * @param boolean $return if false (the default) the the output is printed directly, If true, the
1406 * generated HTML is returned as a string.
1407 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
1408 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
1409 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
1410 * then a suitable one is constructed.
1411 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
1412 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
1413 * $listbox is an integer, that number is used for size instead.
1414 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
1415 * when $listbox display is enabled
1416 * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
1417 * then a suitable one is constructed.
1418 * @return string|void If $return=true returns string, else echo's and returns void
1420 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1421 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
1422 $id='', $listbox=false, $multiple=false, $class='') {
1424 global $OUTPUT;
1425 debugging('choose_from_menu() has been deprecated. Please change your code to use html_writer::select().');
1427 if ($script) {
1428 debugging('The $script parameter has been deprecated. You must use component_actions instead', DEBUG_DEVELOPER);
1430 $attributes = array();
1431 $attributes['disabled'] = $disabled ? 'disabled' : null;
1432 $attributes['tabindex'] = $tabindex ? $tabindex : null;
1433 $attributes['multiple'] = $multiple ? $multiple : null;
1434 $attributes['class'] = $class ? $class : null;
1435 $attributes['id'] = $id ? $id : null;
1437 $output = html_writer::select($options, $name, $selected, array($nothingvalue=>$nothing), $attributes);
1439 if ($return) {
1440 return $output;
1441 } else {
1442 echo $output;
1447 * Prints a help button about a scale
1449 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1450 * @todo final deprecation of this function in MDL-40607
1452 * @global object
1453 * @param id $courseid
1454 * @param object $scale
1455 * @param boolean $return If set to true returns rather than echo's
1456 * @return string|bool Depending on value of $return
1458 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1459 global $OUTPUT;
1461 debugging('print_scale_menu_helpbutton() is deprecated. Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.', DEBUG_DEVELOPER);
1463 $output = $OUTPUT->help_icon_scale($courseid, $scale);
1465 if ($return) {
1466 return $output;
1467 } else {
1468 echo $output;
1473 * Display an standard html checkbox with an optional label
1475 * @deprecated use html_writer::checkbox() instead.
1476 * @todo final deprecation of this function in MDL-40607
1478 * @staticvar int $idcounter
1479 * @param string $name The name of the checkbox
1480 * @param string $value The valus that the checkbox will pass when checked
1481 * @param bool $checked The flag to tell the checkbox initial state
1482 * @param string $label The label to be showed near the checkbox
1483 * @param string $alt The info to be inserted in the alt tag
1484 * @param string $script If not '', then this is added to the checkbox element
1485 * as an onchange handler.
1486 * @param bool $return Whether this function should return a string or output
1487 * it (defaults to false)
1488 * @return string|void If $return=true returns string, else echo's and returns void
1490 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1491 global $OUTPUT;
1493 debugging('print_checkbox() is deprecated. Please use html_writer::checkbox() instead.', DEBUG_DEVELOPER);
1495 if (!empty($script)) {
1496 debugging('The use of the $script param in print_checkbox has not been migrated into html_writer::checkbox().', DEBUG_DEVELOPER);
1499 $output = html_writer::checkbox($name, $value, $checked, $label);
1501 if (empty($return)) {
1502 echo $output;
1503 } else {
1504 return $output;
1510 * Prints the 'update this xxx' button that appears on module pages.
1512 * @deprecated since Moodle 2.0
1514 * @param string $cmid the course_module id.
1515 * @param string $ignored not used any more. (Used to be courseid.)
1516 * @param string $string the module name - get_string('modulename', 'xxx')
1517 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1519 function update_module_button($cmid, $ignored, $string) {
1520 global $CFG, $OUTPUT;
1522 // debugging('update_module_button() has been deprecated. Please change your code to use $OUTPUT->update_module_button().');
1524 //NOTE: DO NOT call new output method because it needs the module name we do not have here!
1526 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1527 $string = get_string('updatethis', '', $string);
1529 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1530 return $OUTPUT->single_button($url, $string);
1531 } else {
1532 return '';
1537 * Prints breadcrumb trail of links, called in theme/-/header.html
1539 * This function has now been deprecated please use output's navbar method instead
1540 * as shown below
1542 * <code php>
1543 * echo $OUTPUT->navbar();
1544 * </code>
1546 * @deprecated use $OUTPUT->navbar() instead
1547 * @todo final deprecation of this function in MDL-40607
1548 * @param mixed $navigation deprecated
1549 * @param string $separator OBSOLETE, and now deprecated
1550 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
1551 * @return string|void String or null, depending on $return.
1553 function print_navigation ($navigation, $separator=0, $return=false) {
1554 global $OUTPUT,$PAGE;
1556 debugging('print_navigation() is deprecated, please update use $OUTPUT->navbar() instead.', DEBUG_DEVELOPER);
1558 $output = $OUTPUT->navbar();
1560 if ($return) {
1561 return $output;
1562 } else {
1563 echo $output;
1568 * This function will build the navigation string to be used by print_header
1569 * and others.
1571 * It automatically generates the site and course level (if appropriate) links.
1573 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
1574 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
1576 * If you want to add any further navigation links after the ones this function generates,
1577 * the pass an array of extra link arrays like this:
1578 * array(
1579 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
1580 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
1582 * The normal case is to just add one further link, for example 'Editing forum' after
1583 * 'General Developer Forum', with no link.
1584 * To do that, you need to pass
1585 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
1586 * However, becuase this is a very common case, you can use a shortcut syntax, and just
1587 * pass the string 'Editing forum', instead of an array as $extranavlinks.
1589 * At the moment, the link types only have limited significance. Type 'activity' is
1590 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
1591 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
1592 * This really needs to be documented better. In the mean time, try to be consistent, it will
1593 * enable people to customise the navigation more in future.
1595 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
1596 * If you get the $cm object using the function get_coursemodule_from_instance or
1597 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
1598 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
1599 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
1600 * warning is printed in developer debug mode.
1602 * @deprecated Please use $PAGE->navabar methods instead.
1603 * @todo final deprecation of this function in MDL-40607
1604 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
1605 * only want one extra item with no link, you can pass a string instead. If you don't want
1606 * any extra links, pass an empty string.
1607 * @param mixed $cm deprecated
1608 * @return array Navigation array
1610 function build_navigation($extranavlinks, $cm = null) {
1611 global $CFG, $COURSE, $DB, $SITE, $PAGE;
1613 debugging('build_navigation() is deprecated, please use $PAGE->navbar methods instead.', DEBUG_DEVELOPER);
1614 if (is_array($extranavlinks) && count($extranavlinks)>0) {
1615 foreach ($extranavlinks as $nav) {
1616 if (array_key_exists('name', $nav)) {
1617 if (array_key_exists('link', $nav) && !empty($nav['link'])) {
1618 $link = $nav['link'];
1619 } else {
1620 $link = null;
1622 $PAGE->navbar->add($nav['name'],$link);
1627 return(array('newnav' => true, 'navlinks' => array()));
1631 * @deprecated not relevant with global navigation in Moodle 2.x+
1632 * @todo remove completely in MDL-40607
1634 function navmenu($course, $cm=NULL, $targetwindow='self') {
1635 // This function has been deprecated with the creation of the global nav in
1636 // moodle 2.0
1637 debugging('navmenu() is deprecated, it is no longer relevant with global navigation.', DEBUG_DEVELOPER);
1639 return '';
1642 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1646 * Call this function to add an event to the calendar table and to call any calendar plugins
1648 * @param object $event An object representing an event from the calendar table.
1649 * The event will be identified by the id field. The object event should include the following:
1650 * <ul>
1651 * <li><b>$event->name</b> - Name for the event
1652 * <li><b>$event->description</b> - Description of the event (defaults to '')
1653 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
1654 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
1655 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
1656 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
1657 * <li><b>$event->modulename</b> - Name of the module that creates this event
1658 * <li><b>$event->instance</b> - Instance of the module that owns this event
1659 * <li><b>$event->eventtype</b> - The type info together with the module info could
1660 * be used by calendar plugins to decide how to display event
1661 * <li><b>$event->timestart</b>- Timestamp for start of event
1662 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
1663 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
1664 * </ul>
1665 * @return int|false The id number of the resulting record or false if failed
1666 * @deprecated please use calendar_event::create() instead.
1667 * @todo final deprecation of this function in MDL-40607
1669 function add_event($event) {
1670 global $CFG;
1671 require_once($CFG->dirroot.'/calendar/lib.php');
1673 debugging('add_event() is deprecated, please use calendar_event::create() instead.', DEBUG_DEVELOPER);
1674 $event = calendar_event::create($event);
1675 if ($event !== false) {
1676 return $event->id;
1678 return false;
1682 * Call this function to update an event in the calendar table
1683 * the event will be identified by the id field of the $event object.
1685 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
1686 * @return bool Success
1687 * @deprecated please calendar_event->update() instead.
1689 function update_event($event) {
1690 global $CFG;
1691 require_once($CFG->dirroot.'/calendar/lib.php');
1693 debugging('update_event() is deprecated, please use calendar_event->update() instead.', DEBUG_DEVELOPER);
1694 $event = (object)$event;
1695 $calendarevent = calendar_event::load($event->id);
1696 return $calendarevent->update($event);
1700 * Call this function to delete the event with id $id from calendar table.
1702 * @param int $id The id of an event from the 'event' table.
1703 * @return bool
1704 * @deprecated please use calendar_event->delete() instead.
1705 * @todo final deprecation of this function in MDL-40607
1707 function delete_event($id) {
1708 global $CFG;
1709 require_once($CFG->dirroot.'/calendar/lib.php');
1711 debugging('delete_event() is deprecated, please use calendar_event->delete() instead.', DEBUG_DEVELOPER);
1713 $event = calendar_event::load($id);
1714 return $event->delete();
1718 * Call this function to hide an event in the calendar table
1719 * the event will be identified by the id field of the $event object.
1721 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
1722 * @return true
1723 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1724 * @todo final deprecation of this function in MDL-40607
1726 function hide_event($event) {
1727 global $CFG;
1728 require_once($CFG->dirroot.'/calendar/lib.php');
1730 debugging('hide_event() is deprecated, please use calendar_event->toggle_visibility(false) instead.', DEBUG_DEVELOPER);
1732 $event = new calendar_event($event);
1733 return $event->toggle_visibility(false);
1737 * Call this function to unhide an event in the calendar table
1738 * the event will be identified by the id field of the $event object.
1740 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
1741 * @return true
1742 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1743 * @todo final deprecation of this function in MDL-40607
1745 function show_event($event) {
1746 global $CFG;
1747 require_once($CFG->dirroot.'/calendar/lib.php');
1749 debugging('show_event() is deprecated, please use calendar_event->toggle_visibility(true) instead.', DEBUG_DEVELOPER);
1751 $event = new calendar_event($event);
1752 return $event->toggle_visibility(true);
1756 * Original singleton helper function, please use static methods instead,
1757 * ex: core_text::convert()
1759 * @deprecated since Moodle 2.2 use core_text::xxxx() instead
1760 * @see textlib
1761 * @return textlib instance
1763 function textlib_get_instance() {
1765 debugging('textlib_get_instance() is deprecated. Please use static calling core_text::functioname() instead.', DEBUG_DEVELOPER);
1767 return new textlib();
1771 * Gets the generic section name for a courses section
1773 * The global function is deprecated. Each course format can define their own generic section name
1775 * @deprecated since 2.4
1776 * @see get_section_name()
1777 * @see format_base::get_section_name()
1779 * @param string $format Course format ID e.g. 'weeks' $course->format
1780 * @param stdClass $section Section object from database
1781 * @return Display name that the course format prefers, e.g. "Week 2"
1783 function get_generic_section_name($format, stdClass $section) {
1784 debugging('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base', DEBUG_DEVELOPER);
1785 return get_string('sectionname', "format_$format") . ' ' . $section->section;
1789 * Returns an array of sections for the requested course id
1791 * It is usually not recommended to display the list of sections used
1792 * in course because the course format may have it's own way to do it.
1794 * If you need to just display the name of the section please call:
1795 * get_section_name($course, $section)
1796 * {@link get_section_name()}
1797 * from 2.4 $section may also be just the field course_sections.section
1799 * If you need the list of all sections it is more efficient to get this data by calling
1800 * $modinfo = get_fast_modinfo($courseorid);
1801 * $sections = $modinfo->get_section_info_all()
1802 * {@link get_fast_modinfo()}
1803 * {@link course_modinfo::get_section_info_all()}
1805 * Information about one section (instance of section_info):
1806 * get_fast_modinfo($courseorid)->get_sections_info($section)
1807 * {@link course_modinfo::get_section_info()}
1809 * @deprecated since 2.4
1811 * @param int $courseid
1812 * @return array Array of section_info objects
1814 function get_all_sections($courseid) {
1815 global $DB;
1816 debugging('get_all_sections() is deprecated. See phpdocs for this function', DEBUG_DEVELOPER);
1817 return get_fast_modinfo($courseid)->get_section_info_all();
1821 * Given a full mod object with section and course already defined, adds this module to that section.
1823 * This function is deprecated, please use {@link course_add_cm_to_section()}
1824 * Note that course_add_cm_to_section() also updates field course_modules.section and
1825 * calls rebuild_course_cache()
1827 * @deprecated since 2.4
1829 * @param object $mod
1830 * @param int $beforemod An existing ID which we will insert the new module before
1831 * @return int The course_sections ID where the mod is inserted
1833 function add_mod_to_section($mod, $beforemod = null) {
1834 debugging('Function add_mod_to_section() is deprecated, please use course_add_cm_to_section()', DEBUG_DEVELOPER);
1835 global $DB;
1836 return course_add_cm_to_section($mod->course, $mod->coursemodule, $mod->section, $beforemod);
1840 * Returns a number of useful structures for course displays
1842 * Function get_all_mods() is deprecated in 2.4
1843 * Instead of:
1844 * <code>
1845 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1846 * </code>
1847 * please use:
1848 * <code>
1849 * $mods = get_fast_modinfo($courseorid)->get_cms();
1850 * $modnames = get_module_types_names();
1851 * $modnamesplural = get_module_types_names(true);
1852 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1853 * </code>
1855 * @deprecated since 2.4
1857 * @param int $courseid id of the course to get info about
1858 * @param array $mods (return) list of course modules
1859 * @param array $modnames (return) list of names of all module types installed and available
1860 * @param array $modnamesplural (return) list of names of all module types installed and available in the plural form
1861 * @param array $modnamesused (return) list of names of all module types used in the course
1863 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1864 debugging('Function get_all_mods() is deprecated. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details', DEBUG_DEVELOPER);
1866 global $COURSE;
1867 $modnames = get_module_types_names();
1868 $modnamesplural= get_module_types_names(true);
1869 $modinfo = get_fast_modinfo($courseid);
1870 $mods = $modinfo->get_cms();
1871 $modnamesused = $modinfo->get_used_module_names();
1875 * Returns course section - creates new if does not exist yet
1877 * This function is deprecated. To create a course section call:
1878 * course_create_sections_if_missing($courseorid, $sections);
1879 * to get the section call:
1880 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1882 * @see course_create_sections_if_missing()
1883 * @see get_fast_modinfo()
1884 * @deprecated since 2.4
1886 * @param int $section relative section number (field course_sections.section)
1887 * @param int $courseid
1888 * @return stdClass record from table {course_sections}
1890 function get_course_section($section, $courseid) {
1891 global $DB;
1892 debugging('Function get_course_section() is deprecated. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.', DEBUG_DEVELOPER);
1894 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
1895 return $cw;
1897 $cw = new stdClass();
1898 $cw->course = $courseid;
1899 $cw->section = $section;
1900 $cw->summary = "";
1901 $cw->summaryformat = FORMAT_HTML;
1902 $cw->sequence = "";
1903 $id = $DB->insert_record("course_sections", $cw);
1904 rebuild_course_cache($courseid, true);
1905 return $DB->get_record("course_sections", array("id"=>$id));
1909 * Return the start and end date of the week in Weekly course format
1911 * It is not recommended to use this function outside of format_weeks plugin
1913 * @deprecated since 2.4
1914 * @see format_weeks::get_section_dates()
1916 * @param stdClass $section The course_section entry from the DB
1917 * @param stdClass $course The course entry from DB
1918 * @return stdClass property start for startdate, property end for enddate
1920 function format_weeks_get_section_dates($section, $course) {
1921 debugging('Function format_weeks_get_section_dates() is deprecated. It is not recommended to'.
1922 ' use it outside of format_weeks plugin', DEBUG_DEVELOPER);
1923 if (isset($course->format) && $course->format === 'weeks') {
1924 return course_get_format($course)->get_section_dates($section);
1926 return null;
1930 * Obtains shared data that is used in print_section when displaying a
1931 * course-module entry.
1933 * Deprecated. Instead of:
1934 * list($content, $name) = get_print_section_cm_text($cm, $course);
1935 * use:
1936 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1937 * $name = $cm->get_formatted_name();
1939 * @deprecated since 2.5
1940 * @see cm_info::get_formatted_content()
1941 * @see cm_info::get_formatted_name()
1943 * This data is also used in other areas of the code.
1944 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1945 * @param object $course (argument not used)
1946 * @return array An array with the following values in this order:
1947 * $content (optional extra content for after link),
1948 * $instancename (text of link)
1950 function get_print_section_cm_text(cm_info $cm, $course) {
1951 debugging('Function get_print_section_cm_text() is deprecated. Please use '.
1952 'cm_info::get_formatted_content() and cm_info::get_formatted_name()',
1953 DEBUG_DEVELOPER);
1954 return array($cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true)),
1955 $cm->get_formatted_name());
1959 * Prints the menus to add activities and resources.
1961 * Deprecated. Please use:
1962 * $courserenderer = $PAGE->get_renderer('core', 'course');
1963 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1964 * array('inblock' => $vertical));
1965 * echo $output; // if $return argument in print_section_add_menus() set to false
1967 * @deprecated since 2.5
1968 * @see core_course_renderer::course_section_add_cm_control()
1970 * @param stdClass $course course object, must be the same as set on the page
1971 * @param int $section relative section number (field course_sections.section)
1972 * @param null|array $modnames (argument ignored) get_module_types_names() is used instead of argument
1973 * @param bool $vertical Vertical orientation
1974 * @param bool $return Return the menus or send them to output
1975 * @param int $sectionreturn The section to link back to
1976 * @return void|string depending on $return
1978 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1979 global $PAGE;
1980 debugging('Function print_section_add_menus() is deprecated. Please use course renderer '.
1981 'function course_section_add_cm_control()', DEBUG_DEVELOPER);
1982 $output = '';
1983 $courserenderer = $PAGE->get_renderer('core', 'course');
1984 $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1985 array('inblock' => $vertical));
1986 if ($return) {
1987 return $output;
1988 } else {
1989 echo $output;
1990 return !empty($output);
1995 * Produces the editing buttons for a module
1997 * Deprecated. Please use:
1998 * $courserenderer = $PAGE->get_renderer('core', 'course');
1999 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
2000 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
2002 * @deprecated since 2.5
2003 * @see course_get_cm_edit_actions()
2004 * @see core_course_renderer->course_section_cm_edit_actions()
2006 * @param stdClass $mod The module to produce editing buttons for
2007 * @param bool $absolute_ignored (argument ignored) - all links are absolute
2008 * @param bool $moveselect (argument ignored)
2009 * @param int $indent The current indenting
2010 * @param int $section The section to link back to
2011 * @return string XHTML for the editing buttons
2013 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
2014 global $PAGE;
2015 debugging('Function make_editing_buttons() is deprecated, please see PHPdocs in '.
2016 'lib/deprecatedlib.php on how to replace it', DEBUG_DEVELOPER);
2017 if (!($mod instanceof cm_info)) {
2018 $modinfo = get_fast_modinfo($mod->course);
2019 $mod = $modinfo->get_cm($mod->id);
2021 $actions = course_get_cm_edit_actions($mod, $indent, $section);
2023 $courserenderer = $PAGE->get_renderer('core', 'course');
2024 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
2025 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
2026 // the course page HTML will allow this to be removed.
2027 return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
2031 * Prints a section full of activity modules
2033 * Deprecated. Please use:
2034 * $courserenderer = $PAGE->get_renderer('core', 'course');
2035 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
2036 * array('hidecompletion' => $hidecompletion));
2038 * @deprecated since 2.5
2039 * @see core_course_renderer::course_section_cm_list()
2041 * @param stdClass $course The course
2042 * @param stdClass|section_info $section The section object containing properties id and section
2043 * @param array $mods (argument not used)
2044 * @param array $modnamesused (argument not used)
2045 * @param bool $absolute (argument not used)
2046 * @param string $width (argument not used)
2047 * @param bool $hidecompletion Hide completion status
2048 * @param int $sectionreturn The section to return to
2049 * @return void
2051 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
2052 global $PAGE;
2053 debugging('Function print_section() is deprecated. Please use course renderer function '.
2054 'course_section_cm_list() instead.', DEBUG_DEVELOPER);
2055 $displayoptions = array('hidecompletion' => $hidecompletion);
2056 $courserenderer = $PAGE->get_renderer('core', 'course');
2057 echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn, $displayoptions);
2061 * Displays the list of courses with user notes
2063 * This function is not used in core. It was replaced by block course_overview
2065 * @deprecated since 2.5
2067 * @param array $courses
2068 * @param array $remote_courses
2070 function print_overview($courses, array $remote_courses=array()) {
2071 global $CFG, $USER, $DB, $OUTPUT;
2072 debugging('Function print_overview() is deprecated. Use block course_overview to display this information', DEBUG_DEVELOPER);
2074 $htmlarray = array();
2075 if ($modules = $DB->get_records('modules')) {
2076 foreach ($modules as $mod) {
2077 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
2078 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
2079 $fname = $mod->name.'_print_overview';
2080 if (function_exists($fname)) {
2081 $fname($courses,$htmlarray);
2086 foreach ($courses as $course) {
2087 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2088 echo $OUTPUT->box_start('coursebox');
2089 $attributes = array('title' => s($fullname));
2090 if (empty($course->visible)) {
2091 $attributes['class'] = 'dimmed';
2093 echo $OUTPUT->heading(html_writer::link(
2094 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
2095 if (array_key_exists($course->id,$htmlarray)) {
2096 foreach ($htmlarray[$course->id] as $modname => $html) {
2097 echo $html;
2100 echo $OUTPUT->box_end();
2103 if (!empty($remote_courses)) {
2104 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
2106 foreach ($remote_courses as $course) {
2107 echo $OUTPUT->box_start('coursebox');
2108 $attributes = array('title' => s($course->fullname));
2109 echo $OUTPUT->heading(html_writer::link(
2110 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
2111 format_string($course->shortname),
2112 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
2113 echo $OUTPUT->box_end();
2118 * This function trawls through the logs looking for
2119 * anything new since the user's last login
2121 * This function was only used to print the content of block recent_activity
2122 * All functionality is moved into class {@link block_recent_activity}
2123 * and renderer {@link block_recent_activity_renderer}
2125 * @deprecated since 2.5
2126 * @param stdClass $course
2128 function print_recent_activity($course) {
2129 // $course is an object
2130 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
2131 debugging('Function print_recent_activity() is deprecated. It is not recommended to'.
2132 ' use it outside of block_recent_activity', DEBUG_DEVELOPER);
2134 $context = context_course::instance($course->id);
2136 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2138 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
2140 if (!isguestuser()) {
2141 if (!empty($USER->lastcourseaccess[$course->id])) {
2142 if ($USER->lastcourseaccess[$course->id] > $timestart) {
2143 $timestart = $USER->lastcourseaccess[$course->id];
2148 echo '<div class="activitydate">';
2149 echo get_string('activitysince', '', userdate($timestart));
2150 echo '</div>';
2151 echo '<div class="activityhead">';
2153 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
2155 echo "</div>\n";
2157 $content = false;
2159 /// Firstly, have there been any new enrolments?
2161 $users = get_recent_enrolments($course->id, $timestart);
2163 //Accessibility: new users now appear in an <OL> list.
2164 if ($users) {
2165 echo '<div class="newusers">';
2166 echo $OUTPUT->heading(get_string("newusers").':', 3);
2167 $content = true;
2168 echo "<ol class=\"list\">\n";
2169 foreach ($users as $user) {
2170 $fullname = fullname($user, $viewfullnames);
2171 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
2173 echo "</ol>\n</div>\n";
2176 /// Next, have there been any modifications to the course structure?
2178 $modinfo = get_fast_modinfo($course);
2180 $changelist = array();
2182 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
2183 module = 'course' AND
2184 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
2185 array($timestart, $course->id), "id ASC");
2187 if ($logs) {
2188 $actions = array('add mod', 'update mod', 'delete mod');
2189 $newgones = array(); // added and later deleted items
2190 foreach ($logs as $key => $log) {
2191 if (!in_array($log->action, $actions)) {
2192 continue;
2194 $info = explode(' ', $log->info);
2196 // note: in most cases I replaced hardcoding of label with use of
2197 // $cm->has_view() but it was not possible to do this here because
2198 // we don't necessarily have the $cm for it
2199 if ($info[0] == 'label') { // Labels are ignored in recent activity
2200 continue;
2203 if (count($info) != 2) {
2204 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
2205 continue;
2208 $modname = $info[0];
2209 $instanceid = $info[1];
2211 if ($log->action == 'delete mod') {
2212 // unfortunately we do not know if the mod was visible
2213 if (!array_key_exists($log->info, $newgones)) {
2214 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
2215 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
2217 } else {
2218 if (!isset($modinfo->instances[$modname][$instanceid])) {
2219 if ($log->action == 'add mod') {
2220 // do not display added and later deleted activities
2221 $newgones[$log->info] = true;
2223 continue;
2225 $cm = $modinfo->instances[$modname][$instanceid];
2226 if (!$cm->uservisible) {
2227 continue;
2230 if ($log->action == 'add mod') {
2231 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
2232 $changelist[$log->info] = array('operation' => 'add', 'text' => "$stradded:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
2234 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
2235 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
2236 $changelist[$log->info] = array('operation' => 'update', 'text' => "$strupdated:<br /><a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id={$cm->id}\">".format_string($cm->name, true)."</a>");
2242 if (!empty($changelist)) {
2243 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
2244 $content = true;
2245 foreach ($changelist as $changeinfo => $change) {
2246 echo '<p class="activity">'.$change['text'].'</p>';
2250 /// Now display new things from each module
2252 $usedmodules = array();
2253 foreach($modinfo->cms as $cm) {
2254 if (isset($usedmodules[$cm->modname])) {
2255 continue;
2257 if (!$cm->uservisible) {
2258 continue;
2260 $usedmodules[$cm->modname] = $cm->modname;
2263 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
2264 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
2265 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
2266 $print_recent_activity = $modname.'_print_recent_activity';
2267 if (function_exists($print_recent_activity)) {
2268 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
2269 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
2271 } else {
2272 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
2276 if (! $content) {
2277 echo '<p class="message">'.get_string('nothingnew').'</p>';
2282 * Delete a course module and any associated data at the course level (events)
2283 * Until 1.5 this function simply marked a deleted flag ... now it
2284 * deletes it completely.
2286 * @deprecated since 2.5
2288 * @param int $id the course module id
2289 * @return boolean true on success, false on failure
2291 function delete_course_module($id) {
2292 debugging('Function delete_course_module() is deprecated. Please use course_delete_module() instead.', DEBUG_DEVELOPER);
2294 global $CFG, $DB;
2296 require_once($CFG->libdir.'/gradelib.php');
2297 require_once($CFG->dirroot.'/blog/lib.php');
2299 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2300 return true;
2302 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2303 //delete events from calendar
2304 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2305 foreach($events as $event) {
2306 delete_event($event->id);
2309 //delete grade items, outcome items and grades attached to modules
2310 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2311 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2312 foreach ($grade_items as $grade_item) {
2313 $grade_item->delete('moddelete');
2316 // Delete completion and availability data; it is better to do this even if the
2317 // features are not turned on, in case they were turned on previously (these will be
2318 // very quick on an empty table)
2319 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2320 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2321 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2322 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2324 delete_context(CONTEXT_MODULE, $cm->id);
2325 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2329 * Prints the turn editing on/off button on course/index.php or course/category.php.
2331 * @deprecated since 2.5
2333 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2334 * @return string HTML of the editing button, or empty string, if this user is not allowed
2335 * to see it.
2337 function update_category_button($categoryid = 0) {
2338 global $CFG, $PAGE, $OUTPUT;
2339 debugging('Function update_category_button() is deprecated. Pages to view '.
2340 'and edit courses are now separate and no longer depend on editing mode.',
2341 DEBUG_DEVELOPER);
2343 // Check permissions.
2344 if (!can_edit_in_category($categoryid)) {
2345 return '';
2348 // Work out the appropriate action.
2349 if ($PAGE->user_is_editing()) {
2350 $label = get_string('turneditingoff');
2351 $edit = 'off';
2352 } else {
2353 $label = get_string('turneditingon');
2354 $edit = 'on';
2357 // Generate the button HTML.
2358 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2359 if ($categoryid) {
2360 $options['id'] = $categoryid;
2361 $page = 'category.php';
2362 } else {
2363 $page = 'index.php';
2365 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2369 * This function recursively travels the categories, building up a nice list
2370 * for display. It also makes an array that list all the parents for each
2371 * category.
2373 * For example, if you have a tree of categories like:
2374 * Miscellaneous (id = 1)
2375 * Subcategory (id = 2)
2376 * Sub-subcategory (id = 4)
2377 * Other category (id = 3)
2378 * Then after calling this function you will have
2379 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2380 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2381 * 3 => 'Other category');
2382 * $parents = array(2 => array(1), 4 => array(1, 2));
2384 * If you specify $requiredcapability, then only categories where the current
2385 * user has that capability will be added to $list, although all categories
2386 * will still be added to $parents, and if you only have $requiredcapability
2387 * in a child category, not the parent, then the child catgegory will still be
2388 * included.
2390 * If you specify the option $excluded, then that category, and all its children,
2391 * are omitted from the tree. This is useful when you are doing something like
2392 * moving categories, where you do not want to allow people to move a category
2393 * to be the child of itself.
2395 * This function is deprecated! For list of categories use
2396 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
2397 * For parents of one particular category use
2398 * coursecat::get($id)->get_parents()
2400 * @deprecated since 2.5
2402 * @param array $list For output, accumulates an array categoryid => full category path name
2403 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2404 * @param string/array $requiredcapability if given, only categories where the current
2405 * user has this capability will be added to $list. Can also be an array of capabilities,
2406 * in which case they are all required.
2407 * @param integer $excludeid Omit this category and its children from the lists built.
2408 * @param object $category Not used
2409 * @param string $path Not used
2411 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2412 $excludeid = 0, $category = NULL, $path = "") {
2413 global $CFG, $DB;
2414 require_once($CFG->libdir.'/coursecatlib.php');
2416 debugging('Global function make_categories_list() is deprecated. Please use '.
2417 'coursecat::make_categories_list() and coursecat::get_parents()',
2418 DEBUG_DEVELOPER);
2420 // For categories list use just this one function:
2421 if (empty($list)) {
2422 $list = array();
2424 $list += coursecat::make_categories_list($requiredcapability, $excludeid);
2426 // Building the list of all parents of all categories in the system is highly undesirable and hardly ever needed.
2427 // Usually user needs only parents for one particular category, in which case should be used:
2428 // coursecat::get($categoryid)->get_parents()
2429 if (empty($parents)) {
2430 $parents = array();
2432 $all = $DB->get_records_sql('SELECT id, parent FROM {course_categories} ORDER BY sortorder');
2433 foreach ($all as $record) {
2434 if ($record->parent) {
2435 $parents[$record->id] = array_merge($parents[$record->parent], array($record->parent));
2436 } else {
2437 $parents[$record->id] = array();
2443 * Delete category, but move contents to another category.
2445 * This function is deprecated. Please use
2446 * coursecat::get($category->id)->delete_move($newparentid, $showfeedback);
2448 * @see coursecat::delete_move()
2449 * @deprecated since 2.5
2451 * @param object $category
2452 * @param int $newparentid category id
2453 * @return bool status
2455 function category_delete_move($category, $newparentid, $showfeedback=true) {
2456 global $CFG;
2457 require_once($CFG->libdir.'/coursecatlib.php');
2459 debugging('Function category_delete_move() is deprecated. Please use coursecat::delete_move() instead.');
2461 return coursecat::get($category->id)->delete_move($newparentid, $showfeedback);
2465 * Recursively delete category including all subcategories and courses.
2467 * This function is deprecated. Please use
2468 * coursecat::get($category->id)->delete_full($showfeedback);
2470 * @see coursecat::delete_full()
2471 * @deprecated since 2.5
2473 * @param stdClass $category
2474 * @param boolean $showfeedback display some notices
2475 * @return array return deleted courses
2477 function category_delete_full($category, $showfeedback=true) {
2478 global $CFG, $DB;
2479 require_once($CFG->libdir.'/coursecatlib.php');
2481 debugging('Function category_delete_full() is deprecated. Please use coursecat::delete_full() instead.');
2483 return coursecat::get($category->id)->delete_full($showfeedback);
2487 * Efficiently moves a category - NOTE that this can have
2488 * a huge impact access-control-wise...
2490 * This function is deprecated. Please use
2491 * $coursecat = coursecat::get($category->id);
2492 * if ($coursecat->can_change_parent($newparentcat->id)) {
2493 * $coursecat->change_parent($newparentcat->id);
2496 * Alternatively you can use
2497 * $coursecat->update(array('parent' => $newparentcat->id));
2499 * Function update() also updates field course_categories.timemodified
2501 * @see coursecat::change_parent()
2502 * @see coursecat::update()
2503 * @deprecated since 2.5
2505 * @param stdClass|coursecat $category
2506 * @param stdClass|coursecat $newparentcat
2508 function move_category($category, $newparentcat) {
2509 global $CFG;
2510 require_once($CFG->libdir.'/coursecatlib.php');
2512 debugging('Function move_category() is deprecated. Please use coursecat::change_parent() instead.');
2514 return coursecat::get($category->id)->change_parent($newparentcat->id);
2518 * Hide course category and child course and subcategories
2520 * This function is deprecated. Please use
2521 * coursecat::get($category->id)->hide();
2523 * @see coursecat::hide()
2524 * @deprecated since 2.5
2526 * @param stdClass $category
2527 * @return void
2529 function course_category_hide($category) {
2530 global $CFG;
2531 require_once($CFG->libdir.'/coursecatlib.php');
2533 debugging('Function course_category_hide() is deprecated. Please use coursecat::hide() instead.');
2535 coursecat::get($category->id)->hide();
2539 * Show course category and child course and subcategories
2541 * This function is deprecated. Please use
2542 * coursecat::get($category->id)->show();
2544 * @see coursecat::show()
2545 * @deprecated since 2.5
2547 * @param stdClass $category
2548 * @return void
2550 function course_category_show($category) {
2551 global $CFG;
2552 require_once($CFG->libdir.'/coursecatlib.php');
2554 debugging('Function course_category_show() is deprecated. Please use coursecat::show() instead.');
2556 coursecat::get($category->id)->show();
2560 * Return specified category, default if given does not exist
2562 * This function is deprecated.
2563 * To get the category with the specified it please use:
2564 * coursecat::get($catid, IGNORE_MISSING);
2565 * or
2566 * coursecat::get($catid, MUST_EXIST);
2568 * To get the first available category please use
2569 * coursecat::get_default();
2571 * class coursecat will also make sure that at least one category exists in DB
2573 * @deprecated since 2.5
2574 * @see coursecat::get()
2575 * @see coursecat::get_default()
2577 * @param int $catid course category id
2578 * @return object caregory
2580 function get_course_category($catid=0) {
2581 global $DB;
2583 debugging('Function get_course_category() is deprecated. Please use coursecat::get(), see phpdocs for more details');
2585 $category = false;
2587 if (!empty($catid)) {
2588 $category = $DB->get_record('course_categories', array('id'=>$catid));
2591 if (!$category) {
2592 // the first category is considered default for now
2593 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
2594 $category = reset($category);
2596 } else {
2597 $cat = new stdClass();
2598 $cat->name = get_string('miscellaneous');
2599 $cat->depth = 1;
2600 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
2601 $cat->timemodified = time();
2602 $catid = $DB->insert_record('course_categories', $cat);
2603 // make sure category context exists
2604 context_coursecat::instance($catid);
2605 mark_context_dirty('/'.SYSCONTEXTID);
2606 fix_course_sortorder(); // Required to build course_categories.depth and .path.
2607 $category = $DB->get_record('course_categories', array('id'=>$catid));
2611 return $category;
2615 * Create a new course category and marks the context as dirty
2617 * This function does not set the sortorder for the new category and
2618 * {@link fix_course_sortorder()} should be called after creating a new course
2619 * category
2621 * Please note that this function does not verify access control.
2623 * This function is deprecated. It is replaced with the method create() in class coursecat.
2624 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
2626 * @deprecated since 2.5
2628 * @param object $category All of the data required for an entry in the course_categories table
2629 * @return object new course category
2631 function create_course_category($category) {
2632 global $DB;
2634 debugging('Function create_course_category() is deprecated. Please use coursecat::create(), see phpdocs for more details', DEBUG_DEVELOPER);
2636 $category->timemodified = time();
2637 $category->id = $DB->insert_record('course_categories', $category);
2638 $category = $DB->get_record('course_categories', array('id' => $category->id));
2640 // We should mark the context as dirty
2641 $category->context = context_coursecat::instance($category->id);
2642 $category->context->mark_dirty();
2644 return $category;
2648 * Returns an array of category ids of all the subcategories for a given
2649 * category.
2651 * This function is deprecated.
2653 * To get visible children categories of the given category use:
2654 * coursecat::get($categoryid)->get_children();
2655 * This function will return the array or coursecat objects, on each of them
2656 * you can call get_children() again
2658 * @see coursecat::get()
2659 * @see coursecat::get_children()
2661 * @deprecated since 2.5
2663 * @global object
2664 * @param int $catid - The id of the category whose subcategories we want to find.
2665 * @return array of category ids.
2667 function get_all_subcategories($catid) {
2668 global $DB;
2670 debugging('Function get_all_subcategories() is deprecated. Please use appropriate methods() of coursecat class. See phpdocs for more details',
2671 DEBUG_DEVELOPER);
2673 $subcats = array();
2675 if ($categories = $DB->get_records('course_categories', array('parent' => $catid))) {
2676 foreach ($categories as $cat) {
2677 array_push($subcats, $cat->id);
2678 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
2681 return $subcats;
2685 * Gets the child categories of a given courses category
2687 * This function is deprecated. Please use functions in class coursecat:
2688 * - coursecat::get($parentid)->has_children()
2689 * tells if the category has children (visible or not to the current user)
2691 * - coursecat::get($parentid)->get_children()
2692 * returns an array of coursecat objects, each of them represents a children category visible
2693 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
2695 * - coursecat::get($parentid)->get_children_count()
2696 * returns number of children categories visible to the current user
2698 * - coursecat::count_all()
2699 * returns total count of all categories in the system (both visible and not)
2701 * - coursecat::get_default()
2702 * returns the first category (usually to be used if count_all() == 1)
2704 * @deprecated since 2.5
2706 * @param int $parentid the id of a course category.
2707 * @return array all the child course categories.
2709 function get_child_categories($parentid) {
2710 global $DB;
2711 debugging('Function get_child_categories() is deprecated. Use coursecat::get_children() or see phpdocs for more details.',
2712 DEBUG_DEVELOPER);
2714 $rv = array();
2715 $sql = context_helper::get_preload_record_columns_sql('ctx');
2716 $records = $DB->get_records_sql("SELECT c.*, $sql FROM {course_categories} c ".
2717 "JOIN {context} ctx on ctx.instanceid = c.id AND ctx.contextlevel = ? WHERE c.parent = ? ORDER BY c.sortorder",
2718 array(CONTEXT_COURSECAT, $parentid));
2719 foreach ($records as $category) {
2720 context_helper::preload_from_record($category);
2721 if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($category->id))) {
2722 continue;
2724 $rv[] = $category;
2726 return $rv;
2730 * Returns a sorted list of categories.
2732 * When asking for $parent='none' it will return all the categories, regardless
2733 * of depth. Wheen asking for a specific parent, the default is to return
2734 * a "shallow" resultset. Pass false to $shallow and it will return all
2735 * the child categories as well.
2737 * @deprecated since 2.5
2739 * This function is deprecated. Use appropriate functions from class coursecat.
2740 * Examples:
2742 * coursecat::get($categoryid)->get_children()
2743 * - returns all children of the specified category as instances of class
2744 * coursecat, which means on each of them method get_children() can be called again.
2745 * Only categories visible to the current user are returned.
2747 * coursecat::get(0)->get_children()
2748 * - returns all top-level categories visible to the current user.
2750 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
2752 * coursecat::make_categories_list()
2753 * - returns an array of all categories id/names in the system.
2754 * Also only returns categories visible to current user and can additionally be
2755 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
2757 * make_categories_options()
2758 * - Returns full course categories tree to be used in html_writer::select()
2760 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
2761 * {@link coursecat::get_default()}
2763 * The code of this deprecated function is left as it is because coursecat::get_children()
2764 * returns categories as instances of coursecat and not stdClass. Also there is no
2765 * substitute for retrieving the category with all it's subcategories. Plugin developers
2766 * may re-use the code/queries from this function in their plugins if really necessary.
2768 * @param string $parent The parent category if any
2769 * @param string $sort the sortorder
2770 * @param bool $shallow - set to false to get the children too
2771 * @return array of categories
2773 function get_categories($parent='none', $sort=NULL, $shallow=true) {
2774 global $DB;
2776 debugging('Function get_categories() is deprecated. Please use coursecat::get_children() or see phpdocs for other alternatives',
2777 DEBUG_DEVELOPER);
2779 if ($sort === NULL) {
2780 $sort = 'ORDER BY cc.sortorder ASC';
2781 } elseif ($sort ==='') {
2782 // leave it as empty
2783 } else {
2784 $sort = "ORDER BY $sort";
2787 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
2789 if ($parent === 'none') {
2790 $sql = "SELECT cc.* $ccselect
2791 FROM {course_categories} cc
2792 $ccjoin
2793 $sort";
2794 $params = array();
2796 } elseif ($shallow) {
2797 $sql = "SELECT cc.* $ccselect
2798 FROM {course_categories} cc
2799 $ccjoin
2800 WHERE cc.parent=?
2801 $sort";
2802 $params = array($parent);
2804 } else {
2805 $sql = "SELECT cc.* $ccselect
2806 FROM {course_categories} cc
2807 $ccjoin
2808 JOIN {course_categories} ccp
2809 ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
2810 WHERE ccp.id=?
2811 $sort";
2812 $params = array($parent);
2814 $categories = array();
2816 $rs = $DB->get_recordset_sql($sql, $params);
2817 foreach($rs as $cat) {
2818 context_helper::preload_from_record($cat);
2819 $catcontext = context_coursecat::instance($cat->id);
2820 if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
2821 $categories[$cat->id] = $cat;
2824 $rs->close();
2825 return $categories;
2829 * Displays a course search form
2831 * This function is deprecated, please use course renderer:
2832 * $renderer = $PAGE->get_renderer('core', 'course');
2833 * echo $renderer->course_search_form($value, $format);
2835 * @deprecated since 2.5
2837 * @param string $value default value to populate the search field
2838 * @param bool $return if true returns the value, if false - outputs
2839 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
2840 * @return null|string
2842 function print_course_search($value="", $return=false, $format="plain") {
2843 global $PAGE;
2844 debugging('Function print_course_search() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2845 $renderer = $PAGE->get_renderer('core', 'course');
2846 if ($return) {
2847 return $renderer->course_search_form($value, $format);
2848 } else {
2849 echo $renderer->course_search_form($value, $format);
2854 * Prints custom user information on the home page
2856 * This function is deprecated, please use:
2857 * $renderer = $PAGE->get_renderer('core', 'course');
2858 * echo $renderer->frontpage_my_courses()
2860 * @deprecated since 2.5
2862 function print_my_moodle() {
2863 global $PAGE;
2864 debugging('Function print_my_moodle() is deprecated, please use course renderer function frontpage_my_courses()', DEBUG_DEVELOPER);
2866 $renderer = $PAGE->get_renderer('core', 'course');
2867 echo $renderer->frontpage_my_courses();
2871 * Prints information about one remote course
2873 * This function is deprecated, it is replaced with protected function
2874 * {@link core_course_renderer::frontpage_remote_course()}
2875 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
2877 * @deprecated since 2.5
2879 function print_remote_course($course, $width="100%") {
2880 global $CFG, $USER;
2881 debugging('Function print_remote_course() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2883 $linkcss = '';
2885 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2887 echo '<div class="coursebox remotecoursebox clearfix">';
2888 echo '<div class="info">';
2889 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2890 $linkcss.' href="'.$url.'">'
2891 . format_string($course->fullname) .'</a><br />'
2892 . format_string($course->hostname) . ' : '
2893 . format_string($course->cat_name) . ' : '
2894 . format_string($course->shortname). '</div>';
2895 echo '</div><div class="summary">';
2896 $options = new stdClass();
2897 $options->noclean = true;
2898 $options->para = false;
2899 $options->overflowdiv = true;
2900 echo format_text($course->summary, $course->summaryformat, $options);
2901 echo '</div>';
2902 echo '</div>';
2906 * Prints information about one remote host
2908 * This function is deprecated, it is replaced with protected function
2909 * {@link core_course_renderer::frontpage_remote_host()}
2910 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
2912 * @deprecated since 2.5
2914 function print_remote_host($host, $width="100%") {
2915 global $OUTPUT;
2916 debugging('Function print_remote_host() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2918 $linkcss = '';
2920 echo '<div class="coursebox clearfix">';
2921 echo '<div class="info">';
2922 echo '<div class="name">';
2923 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2924 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2925 . s($host['name']).'</a> - ';
2926 echo $host['count'] . ' ' . get_string('courses');
2927 echo '</div>';
2928 echo '</div>';
2929 echo '</div>';
2933 * Recursive function to print out all the categories in a nice format
2934 * with or without courses included
2936 * @deprecated since 2.5
2938 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
2940 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
2941 global $PAGE;
2942 debugging('Function print_whole_category_list() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2944 $renderer = $PAGE->get_renderer('core', 'course');
2945 if ($showcourses && $category) {
2946 echo $renderer->course_category($category);
2947 } else if ($showcourses) {
2948 echo $renderer->frontpage_combo_list();
2949 } else {
2950 echo $renderer->frontpage_categories_list();
2955 * Prints the category information.
2957 * @deprecated since 2.5
2959 * This function was only used by {@link print_whole_category_list()} but now
2960 * all course category rendering is moved to core_course_renderer.
2962 * @param stdClass $category
2963 * @param int $depth The depth of the category.
2964 * @param bool $showcourses If set to true course information will also be printed.
2965 * @param array|null $courses An array of courses belonging to the category, or null if you don't have it yet.
2967 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
2968 global $PAGE;
2969 debugging('Function print_category_info() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2971 $renderer = $PAGE->get_renderer('core', 'course');
2972 echo $renderer->course_category($category);
2976 * This function generates a structured array of courses and categories.
2978 * @deprecated since 2.5
2980 * This function is not used any more in moodle core and course renderer does not have render function for it.
2981 * Combo list on the front page is displayed as:
2982 * $renderer = $PAGE->get_renderer('core', 'course');
2983 * echo $renderer->frontpage_combo_list()
2985 * The new class {@link coursecat} stores the information about course category tree
2986 * To get children categories use:
2987 * coursecat::get($id)->get_children()
2988 * To get list of courses use:
2989 * coursecat::get($id)->get_courses()
2991 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
2993 * @param int $id
2994 * @param int $depth
2996 function get_course_category_tree($id = 0, $depth = 0) {
2997 global $DB, $CFG;
2998 if (!$depth) {
2999 debugging('Function get_course_category_tree() is deprecated, please use course renderer or coursecat class, see function phpdocs for more info', DEBUG_DEVELOPER);
3002 $categories = array();
3003 $categoryids = array();
3004 $sql = context_helper::get_preload_record_columns_sql('ctx');
3005 $records = $DB->get_records_sql("SELECT c.*, $sql FROM {course_categories} c ".
3006 "JOIN {context} ctx on ctx.instanceid = c.id AND ctx.contextlevel = ? WHERE c.parent = ? ORDER BY c.sortorder",
3007 array(CONTEXT_COURSECAT, $id));
3008 foreach ($records as $category) {
3009 context_helper::preload_from_record($category);
3010 if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($category->id))) {
3011 continue;
3013 $categories[] = $category;
3014 $categoryids[$category->id] = $category;
3015 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
3016 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
3017 foreach ($subcategories as $subid=>$subcat) {
3018 $categoryids[$subid] = $subcat;
3020 $category->courses = array();
3024 if ($depth > 0) {
3025 // This is a recursive call so return the required array
3026 return array($categories, $categoryids);
3029 if (empty($categoryids)) {
3030 // No categories available (probably all hidden).
3031 return array();
3034 // The depth is 0 this function has just been called so we can finish it off
3036 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
3037 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
3038 $sql = "SELECT
3039 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
3040 $ccselect
3041 FROM {course} c
3042 $ccjoin
3043 WHERE c.category $catsql ORDER BY c.sortorder ASC";
3044 if ($courses = $DB->get_records_sql($sql, $catparams)) {
3045 // loop throught them
3046 foreach ($courses as $course) {
3047 if ($course->id == SITEID) {
3048 continue;
3050 context_helper::preload_from_record($course);
3051 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
3052 $categoryids[$course->category]->courses[$course->id] = $course;
3056 return $categories;
3060 * Print courses in category. If category is 0 then all courses are printed.
3062 * @deprecated since 2.5
3064 * To print a generic list of courses use:
3065 * $renderer = $PAGE->get_renderer('core', 'course');
3066 * echo $renderer->courses_list($courses);
3068 * To print list of all courses:
3069 * $renderer = $PAGE->get_renderer('core', 'course');
3070 * echo $renderer->frontpage_available_courses();
3072 * To print list of courses inside category:
3073 * $renderer = $PAGE->get_renderer('core', 'course');
3074 * echo $renderer->course_category($category); // this will also print subcategories
3076 * @param int|stdClass $category category object or id.
3077 * @return bool true if courses found and printed, else false.
3079 function print_courses($category) {
3080 global $CFG, $OUTPUT, $PAGE;
3081 require_once($CFG->libdir. '/coursecatlib.php');
3082 debugging('Function print_courses() is deprecated, please use course renderer', DEBUG_DEVELOPER);
3084 if (!is_object($category) && $category==0) {
3085 $courses = coursecat::get(0)->get_courses(array('recursive' => true, 'summary' => true, 'coursecontacts' => true));
3086 } else {
3087 $courses = coursecat::get($category->id)->get_courses(array('summary' => true, 'coursecontacts' => true));
3090 if ($courses) {
3091 $renderer = $PAGE->get_renderer('core', 'course');
3092 echo $renderer->courses_list($courses);
3093 } else {
3094 echo $OUTPUT->heading(get_string("nocoursesyet"));
3095 $context = context_system::instance();
3096 if (has_capability('moodle/course:create', $context)) {
3097 $options = array();
3098 if (!empty($category->id)) {
3099 $options['category'] = $category->id;
3100 } else {
3101 $options['category'] = $CFG->defaultrequestcategory;
3103 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
3104 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
3105 echo html_writer::end_tag('div');
3106 return false;
3109 return true;
3113 * Print a description of a course, suitable for browsing in a list.
3115 * @deprecated since 2.5
3117 * Please use course renderer to display a course information box.
3118 * $renderer = $PAGE->get_renderer('core', 'course');
3119 * echo $renderer->courses_list($courses); // will print list of courses
3120 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
3122 * @param object $course the course object.
3123 * @param string $highlightterms Ignored in this deprecated function!
3125 function print_course($course, $highlightterms = '') {
3126 global $PAGE;
3128 debugging('Function print_course() is deprecated, please use course renderer', DEBUG_DEVELOPER);
3129 $renderer = $PAGE->get_renderer('core', 'course');
3130 // Please note, correct would be to use $renderer->coursecat_coursebox() but this function is protected.
3131 // To print list of courses use $renderer->courses_list();
3132 echo $renderer->course_info_box($course);
3136 * Gets an array whose keys are category ids and whose values are arrays of courses in the corresponding category.
3138 * @deprecated since 2.5
3140 * This function is not used any more in moodle core and course renderer does not have render function for it.
3141 * Combo list on the front page is displayed as:
3142 * $renderer = $PAGE->get_renderer('core', 'course');
3143 * echo $renderer->frontpage_combo_list()
3145 * The new class {@link coursecat} stores the information about course category tree
3146 * To get children categories use:
3147 * coursecat::get($id)->get_children()
3148 * To get list of courses use:
3149 * coursecat::get($id)->get_courses()
3151 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
3153 * @param int $categoryid
3154 * @return array
3156 function get_category_courses_array($categoryid = 0) {
3157 debugging('Function get_category_courses_array() is deprecated, please use methods of coursecat class', DEBUG_DEVELOPER);
3158 $tree = get_course_category_tree($categoryid);
3159 $flattened = array();
3160 foreach ($tree as $category) {
3161 get_category_courses_array_recursively($flattened, $category);
3163 return $flattened;
3167 * Recursive function to help flatten the course category tree.
3169 * @deprecated since 2.5
3171 * Was intended to be called from {@link get_category_courses_array()}
3173 * @param array &$flattened An array passed by reference in which to store courses for each category.
3174 * @param stdClass $category The category to get courses for.
3176 function get_category_courses_array_recursively(array &$flattened, $category) {
3177 debugging('Function get_category_courses_array_recursively() is deprecated, please use methods of coursecat class', DEBUG_DEVELOPER);
3178 $flattened[$category->id] = $category->courses;
3179 foreach ($category->categories as $childcategory) {
3180 get_category_courses_array_recursively($flattened, $childcategory);
3185 * Returns a URL based on the context of the current page.
3186 * This URL points to blog/index.php and includes filter parameters appropriate for the current page.
3188 * @param stdclass $context
3189 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
3190 * @todo Remove this in 2.7
3191 * @return string
3193 function blog_get_context_url($context=null) {
3194 global $CFG;
3196 debugging('Function blog_get_context_url() is deprecated, getting params from context is not reliable for blogs.', DEBUG_DEVELOPER);
3197 $viewblogentriesurl = new moodle_url('/blog/index.php');
3199 if (empty($context)) {
3200 global $PAGE;
3201 $context = $PAGE->context;
3204 // Change contextlevel to SYSTEM if viewing the site course
3205 if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
3206 $context = context_system::instance();
3209 $filterparam = '';
3210 $strlevel = '';
3212 switch ($context->contextlevel) {
3213 case CONTEXT_SYSTEM:
3214 case CONTEXT_BLOCK:
3215 case CONTEXT_COURSECAT:
3216 break;
3217 case CONTEXT_COURSE:
3218 $filterparam = 'courseid';
3219 $strlevel = get_string('course');
3220 break;
3221 case CONTEXT_MODULE:
3222 $filterparam = 'modid';
3223 $strlevel = $context->get_context_name();
3224 break;
3225 case CONTEXT_USER:
3226 $filterparam = 'userid';
3227 $strlevel = get_string('user');
3228 break;
3231 if (!empty($filterparam)) {
3232 $viewblogentriesurl->param($filterparam, $context->instanceid);
3235 return $viewblogentriesurl;
3239 * Retrieve course records with the course managers and other related records
3240 * that we need for print_course(). This allows print_courses() to do its job
3241 * in a constant number of DB queries, regardless of the number of courses,
3242 * role assignments, etc.
3244 * The returned array is indexed on c.id, and each course will have
3245 * - $course->managers - array containing RA objects that include a $user obj
3246 * with the minimal fields needed for fullname()
3248 * @deprecated since 2.5
3250 * To get list of all courses with course contacts ('managers') use
3251 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
3253 * To get list of courses inside particular category use
3254 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
3256 * Additionally you can specify sort order, offset and maximum number of courses,
3257 * see {@link coursecat::get_courses()}
3259 * Please note that code of this function is not changed to use coursecat class because
3260 * coursecat::get_courses() returns result in slightly different format. Also note that
3261 * get_courses_wmanagers() DOES NOT check that users are enrolled in the course and
3262 * coursecat::get_courses() does.
3264 * @global object
3265 * @global object
3266 * @global object
3267 * @uses CONTEXT_COURSE
3268 * @uses CONTEXT_SYSTEM
3269 * @uses CONTEXT_COURSECAT
3270 * @uses SITEID
3271 * @param int|string $categoryid Either the categoryid for the courses or 'all'
3272 * @param string $sort A SQL sort field and direction
3273 * @param array $fields An array of additional fields to fetch
3274 * @return array
3276 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
3278 * The plan is to
3280 * - Grab the courses JOINed w/context
3282 * - Grab the interesting course-manager RAs
3283 * JOINed with a base user obj and add them to each course
3285 * So as to do all the work in 2 DB queries. The RA+user JOIN
3286 * ends up being pretty expensive if it happens over _all_
3287 * courses on a large site. (Are we surprised!?)
3289 * So this should _never_ get called with 'all' on a large site.
3292 global $USER, $CFG, $DB;
3293 debugging('Function get_courses_wmanagers() is deprecated, please use coursecat::get_courses()', DEBUG_DEVELOPER);
3295 $params = array();
3296 $allcats = false; // bool flag
3297 if ($categoryid === 'all') {
3298 $categoryclause = '';
3299 $allcats = true;
3300 } elseif (is_numeric($categoryid)) {
3301 $categoryclause = "c.category = :catid";
3302 $params['catid'] = $categoryid;
3303 } else {
3304 debugging("Could not recognise categoryid = $categoryid");
3305 $categoryclause = '';
3308 $basefields = array('id', 'category', 'sortorder',
3309 'shortname', 'fullname', 'idnumber',
3310 'startdate', 'visible',
3311 'newsitems', 'groupmode', 'groupmodeforce');
3313 if (!is_null($fields) && is_string($fields)) {
3314 if (empty($fields)) {
3315 $fields = $basefields;
3316 } else {
3317 // turn the fields from a string to an array that
3318 // get_user_courses_bycap() will like...
3319 $fields = explode(',',$fields);
3320 $fields = array_map('trim', $fields);
3321 $fields = array_unique(array_merge($basefields, $fields));
3323 } elseif (is_array($fields)) {
3324 $fields = array_merge($basefields,$fields);
3326 $coursefields = 'c.' .join(',c.', $fields);
3328 if (empty($sort)) {
3329 $sortstatement = "";
3330 } else {
3331 $sortstatement = "ORDER BY $sort";
3334 $where = 'WHERE c.id != ' . SITEID;
3335 if ($categoryclause !== ''){
3336 $where = "$where AND $categoryclause";
3339 // pull out all courses matching the cat
3340 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
3341 $sql = "SELECT $coursefields $ccselect
3342 FROM {course} c
3343 $ccjoin
3344 $where
3345 $sortstatement";
3347 $catpaths = array();
3348 $catpath = NULL;
3349 if ($courses = $DB->get_records_sql($sql, $params)) {
3350 // loop on courses materialising
3351 // the context, and prepping data to fetch the
3352 // managers efficiently later...
3353 foreach ($courses as $k => $course) {
3354 context_helper::preload_from_record($course);
3355 $coursecontext = context_course::instance($course->id);
3356 $courses[$k] = $course;
3357 $courses[$k]->managers = array();
3358 if ($allcats === false) {
3359 // single cat, so take just the first one...
3360 if ($catpath === NULL) {
3361 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
3363 } else {
3364 // chop off the contextid of the course itself
3365 // like dirname() does...
3366 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
3369 } else {
3370 return array(); // no courses!
3373 $CFG->coursecontact = trim($CFG->coursecontact);
3374 if (empty($CFG->coursecontact)) {
3375 return $courses;
3378 $managerroles = explode(',', $CFG->coursecontact);
3379 $catctxids = '';
3380 if (count($managerroles)) {
3381 if ($allcats === true) {
3382 $catpaths = array_unique($catpaths);
3383 $ctxids = array();
3384 foreach ($catpaths as $cpath) {
3385 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
3387 $ctxids = array_unique($ctxids);
3388 $catctxids = implode( ',' , $ctxids);
3389 unset($catpaths);
3390 unset($cpath);
3391 } else {
3392 // take the ctx path from the first course
3393 // as all categories will be the same...
3394 $catpath = substr($catpath,1);
3395 $catpath = preg_replace(':/\d+$:','',$catpath);
3396 $catctxids = str_replace('/',',',$catpath);
3398 if ($categoryclause !== '') {
3399 $categoryclause = "AND $categoryclause";
3402 * Note: Here we use a LEFT OUTER JOIN that can
3403 * "optionally" match to avoid passing a ton of context
3404 * ids in an IN() clause. Perhaps a subselect is faster.
3406 * In any case, this SQL is not-so-nice over large sets of
3407 * courses with no $categoryclause.
3410 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
3411 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
3412 rn.name AS rolecoursealias, u.id AS userid, u.firstname, u.lastname
3413 FROM {role_assignments} ra
3414 JOIN {context} ctx ON ra.contextid = ctx.id
3415 JOIN {user} u ON ra.userid = u.id
3416 JOIN {role} r ON ra.roleid = r.id
3417 LEFT JOIN {role_names} rn ON (rn.contextid = ctx.id AND rn.roleid = r.id)
3418 LEFT OUTER JOIN {course} c
3419 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
3420 WHERE ( c.id IS NOT NULL";
3421 // under certain conditions, $catctxids is NULL
3422 if($catctxids == NULL){
3423 $sql .= ") ";
3424 }else{
3425 $sql .= " OR ra.contextid IN ($catctxids) )";
3428 $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
3429 $categoryclause
3430 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
3431 $rs = $DB->get_recordset_sql($sql, $params);
3433 // This loop is fairly stupid as it stands - might get better
3434 // results doing an initial pass clustering RAs by path.
3435 foreach($rs as $ra) {
3436 $user = new stdClass;
3437 $user->id = $ra->userid; unset($ra->userid);
3438 $user->firstname = $ra->firstname; unset($ra->firstname);
3439 $user->lastname = $ra->lastname; unset($ra->lastname);
3440 $ra->user = $user;
3441 if ($ra->contextlevel == CONTEXT_SYSTEM) {
3442 foreach ($courses as $k => $course) {
3443 $courses[$k]->managers[] = $ra;
3445 } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
3446 if ($allcats === false) {
3447 // It always applies
3448 foreach ($courses as $k => $course) {
3449 $courses[$k]->managers[] = $ra;
3451 } else {
3452 foreach ($courses as $k => $course) {
3453 $coursecontext = context_course::instance($course->id);
3454 // Note that strpos() returns 0 as "matched at pos 0"
3455 if (strpos($coursecontext->path, $ra->path.'/') === 0) {
3456 // Only add it to subpaths
3457 $courses[$k]->managers[] = $ra;
3461 } else { // course-level
3462 if (!array_key_exists($ra->instanceid, $courses)) {
3463 //this course is not in a list, probably a frontpage course
3464 continue;
3466 $courses[$ra->instanceid]->managers[] = $ra;
3469 $rs->close();
3472 return $courses;
3476 * Converts a nested array tree into HTML ul:li [recursive]
3478 * @deprecated since 2.5
3480 * @param array $tree A tree array to convert
3481 * @param int $row Used in identifying the iteration level and in ul classes
3482 * @return string HTML structure
3484 function convert_tree_to_html($tree, $row=0) {
3485 debugging('Function convert_tree_to_html() is deprecated since Moodle 2.5. Consider using class tabtree and core_renderer::render_tabtree()', DEBUG_DEVELOPER);
3487 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
3489 $first = true;
3490 $count = count($tree);
3492 foreach ($tree as $tab) {
3493 $count--; // countdown to zero
3495 $liclass = '';
3497 if ($first && ($count == 0)) { // Just one in the row
3498 $liclass = 'first last';
3499 $first = false;
3500 } else if ($first) {
3501 $liclass = 'first';
3502 $first = false;
3503 } else if ($count == 0) {
3504 $liclass = 'last';
3507 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3508 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
3511 if ($tab->inactive || $tab->active || $tab->selected) {
3512 if ($tab->selected) {
3513 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
3514 } else if ($tab->active) {
3515 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
3519 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
3521 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
3522 // The a tag is used for styling
3523 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
3524 } else {
3525 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
3528 if (!empty($tab->subtree)) {
3529 $str .= convert_tree_to_html($tab->subtree, $row+1);
3530 } else if ($tab->selected) {
3531 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
3534 $str .= ' </li>'."\n";
3536 $str .= '</ul>'."\n";
3538 return $str;
3542 * Convert nested tabrows to a nested array
3544 * @deprecated since 2.5
3546 * @param array $tabrows A [nested] array of tab row objects
3547 * @param string $selected The tabrow to select (by id)
3548 * @param array $inactive An array of tabrow id's to make inactive
3549 * @param array $activated An array of tabrow id's to make active
3550 * @return array The nested array
3552 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
3554 debugging('Function convert_tabrows_to_tree() is deprecated since Moodle 2.5. Consider using class tabtree', DEBUG_DEVELOPER);
3556 // Work backwards through the rows (bottom to top) collecting the tree as we go.
3557 $tabrows = array_reverse($tabrows);
3559 $subtree = array();
3561 foreach ($tabrows as $row) {
3562 $tree = array();
3564 foreach ($row as $tab) {
3565 $tab->inactive = in_array((string)$tab->id, $inactive);
3566 $tab->active = in_array((string)$tab->id, $activated);
3567 $tab->selected = (string)$tab->id == $selected;
3569 if ($tab->active || $tab->selected) {
3570 if ($subtree) {
3571 $tab->subtree = $subtree;
3574 $tree[] = $tab;
3576 $subtree = $tree;
3579 return $subtree;
3583 * Can handle rotated text. Whether it is safe to use the trickery in textrotate.js.
3585 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
3586 * @return bool True for yes, false for no
3588 function can_use_rotated_text() {
3589 debugging('can_use_rotated_text() is deprecated since Moodle 2.5. JS feature detection is used automatically.', DEBUG_DEVELOPER);
3590 return true;
3594 * Get the context instance as an object. This function will create the
3595 * context instance if it does not exist yet.
3597 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
3598 * @todo This will be deleted in Moodle 2.8, refer MDL-34472
3599 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
3600 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
3601 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
3602 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
3603 * MUST_EXIST means throw exception if no record or multiple records found
3604 * @return context The context object.
3606 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
3608 debugging('get_context_instance() is deprecated, please use context_xxxx::instance() instead.', DEBUG_DEVELOPER);
3610 $instances = (array)$instance;
3611 $contexts = array();
3613 $classname = context_helper::get_class_for_level($contextlevel);
3615 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
3616 foreach ($instances as $inst) {
3617 $contexts[$inst] = $classname::instance($inst, $strictness);
3620 if (is_array($instance)) {
3621 return $contexts;
3622 } else {
3623 return $contexts[$instance];
3628 * Get a context instance as an object, from a given context id.
3630 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
3631 * @todo MDL-34550 This will be deleted in Moodle 2.8
3632 * @see context::instance_by_id($id)
3633 * @param int $id context id
3634 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
3635 * MUST_EXIST means throw exception if no record or multiple records found
3636 * @return context|bool the context object or false if not found.
3638 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
3639 debugging('get_context_instance_by_id() is deprecated, please use context::instance_by_id($id) instead.', DEBUG_DEVELOPER);
3640 return context::instance_by_id($id, $strictness);
3644 * Returns system context or null if can not be created yet.
3646 * @see context_system::instance()
3647 * @deprecated since 2.2
3648 * @param bool $cache use caching
3649 * @return context system context (null if context table not created yet)
3651 function get_system_context($cache = true) {
3652 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
3653 return context_system::instance(0, IGNORE_MISSING, $cache);
3657 * Recursive function which, given a context, find all parent context ids,
3658 * and return the array in reverse order, i.e. parent first, then grand
3659 * parent, etc.
3661 * @see context::get_parent_context_ids()
3662 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
3663 * @param context $context
3664 * @param bool $includeself optional, defaults to false
3665 * @return array
3667 function get_parent_contexts(context $context, $includeself = false) {
3668 debugging('get_parent_contexts() is deprecated, please use $context->get_parent_context_ids() instead.', DEBUG_DEVELOPER);
3669 return $context->get_parent_context_ids($includeself);
3673 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3674 * is the site context.)
3676 * @deprecated since Moodle 2.2
3677 * @see context::get_parent_context()
3678 * @param context $context
3679 * @return integer the id of the parent context.
3681 function get_parent_contextid(context $context) {
3682 debugging('get_parent_contextid() is deprecated, please use $context->get_parent_context() instead.', DEBUG_DEVELOPER);
3684 if ($parent = $context->get_parent_context()) {
3685 return $parent->id;
3686 } else {
3687 return false;
3692 * Recursive function which, given a context, find all its children contexts.
3694 * For course category contexts it will return immediate children only categories and courses.
3695 * It will NOT recurse into courses or child categories.
3696 * If you want to do that, call it on the returned courses/categories.
3698 * When called for a course context, it will return the modules and blocks
3699 * displayed in the course page.
3701 * If called on a user/course/module context it _will_ populate the cache with the appropriate
3702 * contexts ;-)
3704 * @see context::get_child_contexts()
3705 * @deprecated since 2.2
3706 * @param context $context
3707 * @return array Array of child records
3709 function get_child_contexts(context $context) {
3710 debugging('get_child_contexts() is deprecated, please use $context->get_child_contexts() instead.', DEBUG_DEVELOPER);
3711 return $context->get_child_contexts();
3715 * Precreates all contexts including all parents.
3717 * @see context_helper::create_instances()
3718 * @deprecated since 2.2
3719 * @param int $contextlevel empty means all
3720 * @param bool $buildpaths update paths and depths
3721 * @return void
3723 function create_contexts($contextlevel = null, $buildpaths = true) {
3724 debugging('create_contexts() is deprecated, please use context_helper::create_instances() instead.', DEBUG_DEVELOPER);
3725 context_helper::create_instances($contextlevel, $buildpaths);
3729 * Remove stale context records.
3731 * @see context_helper::cleanup_instances()
3732 * @deprecated since 2.2
3733 * @return bool
3735 function cleanup_contexts() {
3736 debugging('cleanup_contexts() is deprecated, please use context_helper::cleanup_instances() instead.', DEBUG_DEVELOPER);
3737 context_helper::cleanup_instances();
3738 return true;
3742 * Populate context.path and context.depth where missing.
3744 * @see context_helper::build_all_paths()
3745 * @deprecated since 2.2
3746 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
3747 * @return void
3749 function build_context_path($force = false) {
3750 debugging('build_context_path() is deprecated, please use context_helper::build_all_paths() instead.', DEBUG_DEVELOPER);
3751 context_helper::build_all_paths($force);
3755 * Rebuild all related context depth and path caches.
3757 * @see context::reset_paths()
3758 * @deprecated since 2.2
3759 * @param array $fixcontexts array of contexts, strongtyped
3760 * @return void
3762 function rebuild_contexts(array $fixcontexts) {
3763 debugging('rebuild_contexts() is deprecated, please use $context->reset_paths(true) instead.', DEBUG_DEVELOPER);
3764 foreach ($fixcontexts as $fixcontext) {
3765 $fixcontext->reset_paths(false);
3767 context_helper::build_all_paths(false);
3771 * Preloads all contexts relating to a course: course, modules. Block contexts
3772 * are no longer loaded here. The contexts for all the blocks on the current
3773 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
3775 * @deprecated since Moodle 2.2
3776 * @see context_helper::preload_course()
3777 * @param int $courseid Course ID
3778 * @return void
3780 function preload_course_contexts($courseid) {
3781 debugging('preload_course_contexts() is deprecated, please use context_helper::preload_course() instead.', DEBUG_DEVELOPER);
3782 context_helper::preload_course($courseid);
3786 * Update the path field of the context and all dep. subcontexts that follow
3788 * Update the path field of the context and
3789 * all the dependent subcontexts that follow
3790 * the move.
3792 * The most important thing here is to be as
3793 * DB efficient as possible. This op can have a
3794 * massive impact in the DB.
3796 * @deprecated since Moodle 2.2
3797 * @see context::update_moved()
3798 * @param context $context context obj
3799 * @param context $newparent new parent obj
3800 * @return void
3802 function context_moved(context $context, context $newparent) {
3803 debugging('context_moved() is deprecated, please use context::update_moved() instead.', DEBUG_DEVELOPER);
3804 $context->update_moved($newparent);
3808 * Extracts the relevant capabilities given a contextid.
3809 * All case based, example an instance of forum context.
3810 * Will fetch all forum related capabilities, while course contexts
3811 * Will fetch all capabilities
3813 * capabilities
3814 * `name` varchar(150) NOT NULL,
3815 * `captype` varchar(50) NOT NULL,
3816 * `contextlevel` int(10) NOT NULL,
3817 * `component` varchar(100) NOT NULL,
3819 * @see context::get_capabilities()
3820 * @deprecated since 2.2
3821 * @param context $context
3822 * @return array
3824 function fetch_context_capabilities(context $context) {
3825 debugging('fetch_context_capabilities() is deprecated, please use $context->get_capabilities() instead.', DEBUG_DEVELOPER);
3826 return $context->get_capabilities();
3830 * Preloads context information from db record and strips the cached info.
3831 * The db request has to contain both the $join and $select from context_instance_preload_sql()
3833 * @deprecated since 2.2
3834 * @see context_helper::preload_from_record()
3835 * @param stdClass $rec
3836 * @return void (modifies $rec)
3838 function context_instance_preload(stdClass $rec) {
3839 debugging('context_instance_preload() is deprecated, please use context_helper::preload_from_record() instead.', DEBUG_DEVELOPER);
3840 context_helper::preload_from_record($rec);
3844 * Returns context level name
3846 * @deprecated since 2.2
3847 * @see context_helper::get_level_name()
3848 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
3849 * @return string the name for this type of context.
3851 function get_contextlevel_name($contextlevel) {
3852 debugging('get_contextlevel_name() is deprecated, please use context_helper::get_level_name() instead.', DEBUG_DEVELOPER);
3853 return context_helper::get_level_name($contextlevel);
3857 * Prints human readable context identifier.
3859 * @deprecated since 2.2
3860 * @see context::get_context_name()
3861 * @param context $context the context.
3862 * @param boolean $withprefix whether to prefix the name of the context with the
3863 * type of context, e.g. User, Course, Forum, etc.
3864 * @param boolean $short whether to user the short name of the thing. Only applies
3865 * to course contexts
3866 * @return string the human readable context name.
3868 function print_context_name(context $context, $withprefix = true, $short = false) {
3869 debugging('print_context_name() is deprecated, please use $context->get_context_name() instead.', DEBUG_DEVELOPER);
3870 return $context->get_context_name($withprefix, $short);
3874 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
3876 * @deprecated since 2.2, use $context->mark_dirty() instead
3877 * @see context::mark_dirty()
3878 * @param string $path context path
3880 function mark_context_dirty($path) {
3881 global $CFG, $USER, $ACCESSLIB_PRIVATE;
3882 debugging('mark_context_dirty() is deprecated, please use $context->mark_dirty() instead.', DEBUG_DEVELOPER);
3884 if (during_initial_install()) {
3885 return;
3888 // only if it is a non-empty string
3889 if (is_string($path) && $path !== '') {
3890 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
3891 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
3892 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
3893 } else {
3894 if (CLI_SCRIPT) {
3895 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
3896 } else {
3897 if (isset($USER->access['time'])) {
3898 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
3899 } else {
3900 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
3902 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
3909 * Remove a context record and any dependent entries,
3910 * removes context from static context cache too
3912 * @deprecated since Moodle 2.2
3913 * @see context_helper::delete_instance() or context::delete_content()
3914 * @param int $contextlevel
3915 * @param int $instanceid
3916 * @param bool $deleterecord false means keep record for now
3917 * @return bool returns true or throws an exception
3919 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
3920 if ($deleterecord) {
3921 debugging('delete_context() is deprecated, please use context_helper::delete_instance() instead.', DEBUG_DEVELOPER);
3922 context_helper::delete_instance($contextlevel, $instanceid);
3923 } else {
3924 debugging('delete_context() is deprecated, please use $context->delete_content() instead.', DEBUG_DEVELOPER);
3925 $classname = context_helper::get_class_for_level($contextlevel);
3926 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
3927 $context->delete_content();
3931 return true;
3935 * Get a URL for a context, if there is a natural one. For example, for
3936 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
3937 * user profile page.
3939 * @deprecated since 2.2
3940 * @see context::get_url()
3941 * @param context $context the context
3942 * @return moodle_url
3944 function get_context_url(context $context) {
3945 debugging('get_context_url() is deprecated, please use $context->get_url() instead.', DEBUG_DEVELOPER);
3946 return $context->get_url();
3950 * Is this context part of any course? if yes return course context,
3951 * if not return null or throw exception.
3953 * @deprecated since 2.2
3954 * @see context::get_course_context()
3955 * @param context $context
3956 * @return course_context context of the enclosing course, null if not found or exception
3958 function get_course_context(context $context) {
3959 debugging('get_course_context() is deprecated, please use $context->get_course_context(true) instead.', DEBUG_DEVELOPER);
3960 return $context->get_course_context(true);
3964 * Get an array of courses where cap requested is available
3965 * and user is enrolled, this can be relatively slow.
3967 * @deprecated since 2.2
3968 * @see enrol_get_users_courses()
3969 * @param int $userid A user id. By default (null) checks the permissions of the current user.
3970 * @param string $cap - name of the capability
3971 * @param array $accessdata_ignored
3972 * @param bool $doanything_ignored
3973 * @param string $sort - sorting fields - prefix each fieldname with "c."
3974 * @param array $fields - additional fields you are interested in...
3975 * @param int $limit_ignored
3976 * @return array $courses - ordered array of course objects - see notes above
3978 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
3980 debugging('get_user_courses_bycap() is deprecated, please use enrol_get_users_courses() instead.', DEBUG_DEVELOPER);
3981 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
3982 foreach ($courses as $id=>$course) {
3983 $context = context_course::instance($id);
3984 if (!has_capability($cap, $context, $userid)) {
3985 unset($courses[$id]);
3989 return $courses;
3993 * This is really slow!!! do not use above course context level
3995 * @deprecated since Moodle 2.2
3996 * @param int $roleid
3997 * @param context $context
3998 * @return array
4000 function get_role_context_caps($roleid, context $context) {
4001 global $DB;
4002 debugging('get_role_context_caps() is deprecated, it is really slow. Don\'t use it.', DEBUG_DEVELOPER);
4004 // This is really slow!!!! - do not use above course context level.
4005 $result = array();
4006 $result[$context->id] = array();
4008 // First emulate the parent context capabilities merging into context.
4009 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
4010 foreach ($searchcontexts as $cid) {
4011 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
4012 foreach ($capabilities as $cap) {
4013 if (!array_key_exists($cap->capability, $result[$context->id])) {
4014 $result[$context->id][$cap->capability] = 0;
4016 $result[$context->id][$cap->capability] += $cap->permission;
4021 // Now go through the contexts below given context.
4022 $searchcontexts = array_keys($context->get_child_contexts());
4023 foreach ($searchcontexts as $cid) {
4024 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
4025 foreach ($capabilities as $cap) {
4026 if (!array_key_exists($cap->contextid, $result)) {
4027 $result[$cap->contextid] = array();
4029 $result[$cap->contextid][$cap->capability] = $cap->permission;
4034 return $result;
4038 * Returns current course id or false if outside of course based on context parameter.
4040 * @see context::get_course_context()
4041 * @deprecated since 2.2
4042 * @param context $context
4043 * @return int|bool related course id or false
4045 function get_courseid_from_context(context $context) {
4046 debugging('get_courseid_from_context() is deprecated, please use $context->get_course_context(false) instead.', DEBUG_DEVELOPER);
4047 if ($coursecontext = $context->get_course_context(false)) {
4048 return $coursecontext->instanceid;
4049 } else {
4050 return false;
4055 * Preloads context information together with instances.
4056 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
4058 * If you are using this methid, you should have something like this:
4060 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
4062 * To prevent the use of this deprecated function, replace the line above with something similar to this:
4064 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
4066 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
4067 * ^ ^ ^ ^
4068 * $params = array('contextlevel' => CONTEXT_COURSE);
4070 * @see context_helper:;get_preload_record_columns_sql()
4071 * @deprecated since 2.2
4072 * @param string $joinon for example 'u.id'
4073 * @param string $contextlevel context level of instance in $joinon
4074 * @param string $tablealias context table alias
4075 * @return array with two values - select and join part
4077 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
4078 debugging('context_instance_preload_sql() is deprecated, please use context_helper::get_preload_record_columns_sql() instead.', DEBUG_DEVELOPER);
4079 $select = ", " . context_helper::get_preload_record_columns_sql($tablealias);
4080 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
4081 return array($select, $join);
4085 * Gets a string for sql calls, searching for stuff in this context or above.
4087 * @deprecated since 2.2
4088 * @see context::get_parent_context_ids()
4089 * @param context $context
4090 * @return string
4092 function get_related_contexts_string(context $context) {
4093 debugging('get_related_contexts_string() is deprecated, please use $context->get_parent_context_ids(true) instead.', DEBUG_DEVELOPER);
4094 if ($parents = $context->get_parent_context_ids()) {
4095 return (' IN ('.$context->id.','.implode(',', $parents).')');
4096 } else {
4097 return (' ='.$context->id);
4102 * Get a list of all the plugins of a given type that contain a particular file.
4104 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
4105 * @param string $file the name of file that must be present in the plugin.
4106 * (e.g. 'view.php', 'db/install.xml').
4107 * @param bool $include if true (default false), the file will be include_once-ed if found.
4108 * @return array with plugin name as keys (e.g. 'forum', 'courselist') and the path
4109 * to the file relative to dirroot as value (e.g. "$CFG->dirroot/mod/forum/view.php").
4110 * @deprecated since 2.6
4111 * @see core_component::get_plugin_list_with_file()
4113 function get_plugin_list_with_file($plugintype, $file, $include = false) {
4114 debugging('get_plugin_list_with_file() is deprecated, please use core_component::get_plugin_list_with_file() instead.',
4115 DEBUG_DEVELOPER);
4116 return core_component::get_plugin_list_with_file($plugintype, $file, $include);
4120 * Checks to see if is the browser operating system matches the specified brand.
4122 * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
4124 * @deprecated since 2.6
4125 * @param string $brand The operating system identifier being tested
4126 * @return bool true if the given brand below to the detected operating system
4128 function check_browser_operating_system($brand) {
4129 debugging('check_browser_operating_system has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4130 return core_useragent::check_browser_operating_system($brand);
4134 * Checks to see if is a browser matches the specified
4135 * brand and is equal or better version.
4137 * @deprecated since 2.6
4138 * @param string $brand The browser identifier being tested
4139 * @param int $version The version of the browser, if not specified any version (except 5.5 for IE for BC reasons)
4140 * @return bool true if the given version is below that of the detected browser
4142 function check_browser_version($brand, $version = null) {
4143 debugging('check_browser_version has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4144 return core_useragent::check_browser_version($brand, $version);
4148 * Returns whether a device/browser combination is mobile, tablet, legacy, default or the result of
4149 * an optional admin specified regular expression. If enabledevicedetection is set to no or not set
4150 * it returns default
4152 * @deprecated since 2.6
4153 * @return string device type
4155 function get_device_type() {
4156 debugging('get_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4157 return core_useragent::get_device_type();
4161 * Returns a list of the device types supporting by Moodle
4163 * @deprecated since 2.6
4164 * @param boolean $incusertypes includes types specified using the devicedetectregex admin setting
4165 * @return array $types
4167 function get_device_type_list($incusertypes = true) {
4168 debugging('get_device_type_list has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4169 return core_useragent::get_device_type_list($incusertypes);
4173 * Returns the theme selected for a particular device or false if none selected.
4175 * @deprecated since 2.6
4176 * @param string $devicetype
4177 * @return string|false The name of the theme to use for the device or the false if not set
4179 function get_selected_theme_for_device_type($devicetype = null) {
4180 debugging('get_selected_theme_for_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4181 return core_useragent::get_device_type_theme($devicetype);
4185 * Returns the name of the device type theme var in $CFG because there is not a convention to allow backwards compatibility.
4187 * @deprecated since 2.6
4188 * @param string $devicetype
4189 * @return string The config variable to use to determine the theme
4191 function get_device_cfg_var_name($devicetype = null) {
4192 debugging('get_device_cfg_var_name has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4193 return core_useragent::get_device_type_cfg_var_name($devicetype);
4197 * Allows the user to switch the device they are seeing the theme for.
4198 * This allows mobile users to switch back to the default theme, or theme for any other device.
4200 * @deprecated since 2.6
4201 * @param string $newdevice The device the user is currently using.
4202 * @return string The device the user has switched to
4204 function set_user_device_type($newdevice) {
4205 debugging('set_user_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4206 return core_useragent::set_user_device_type($newdevice);
4210 * Returns the device the user is currently using, or if the user has chosen to switch devices
4211 * for the current device type the type they have switched to.
4213 * @deprecated since 2.6
4214 * @return string The device the user is currently using or wishes to use
4216 function get_user_device_type() {
4217 debugging('get_user_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4218 return core_useragent::get_user_device_type();
4222 * Returns one or several CSS class names that match the user's browser. These can be put
4223 * in the body tag of the page to apply browser-specific rules without relying on CSS hacks
4225 * @deprecated since 2.6
4226 * @return array An array of browser version classes
4228 function get_browser_version_classes() {
4229 debugging('get_browser_version_classes has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
4230 return core_useragent::get_browser_version_classes();
4234 * Generate a fake user for emails based on support settings
4236 * @deprecated since Moodle 2.6
4237 * @see core_user::get_support_user()
4238 * @return stdClass user info
4240 function generate_email_supportuser() {
4241 debugging('generate_email_supportuser is deprecated, please use core_user::get_support_user');
4242 return core_user::get_support_user();
4246 * Get issued badge details for assertion URL
4248 * @deprecated since Moodle 2.6
4249 * @param string $hash Unique hash of a badge
4250 * @return array Information about issued badge.
4252 function badges_get_issued_badge_info($hash) {
4253 debugging('Function badges_get_issued_badge_info() is deprecated. Please use core_badges_assertion class and methods to generate badge assertion.', DEBUG_DEVELOPER);
4254 $assertion = new core_badges_assertion($hash);
4255 return $assertion->get_badge_assertion();
4259 * Does the user want and can edit using rich text html editor?
4260 * This function does not make sense anymore because a user can directly choose their preferred editor.
4262 * @deprecated since 2.6
4263 * @return bool
4265 function can_use_html_editor() {
4266 debugging('can_use_html_editor has been deprecated please update your code to assume it returns true.', DEBUG_DEVELOPER);
4267 return true;