MDL-50806 questions: Allow more memory when doing a question import
[moodle.git] / lib / deprecatedlib.php
blob963c818c8abd5e83aa1948571906600be36cd229
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 * Convert region timezone to php supported timezone
36 * @deprecated since Moodle 2.9
37 * @param string $tz value from ical file
38 * @return string $tz php supported timezone
40 function calendar_normalize_tz($tz) {
41 debugging('calendar_normalize_tz() is deprecated, use core_date::normalise_timezone() instead', DEBUG_DEVELOPER);
42 return core_date::normalise_timezone($tz);
45 /**
46 * Returns a float which represents the user's timezone difference from GMT in hours
47 * Checks various settings and picks the most dominant of those which have a value
48 * @deprecated since Moodle 2.9
49 * @param float|int|string $tz timezone user timezone
50 * @return float
52 function get_user_timezone_offset($tz = 99) {
53 debugging('get_user_timezone_offset() is deprecated, use PHP DateTimeZone instead', DEBUG_DEVELOPER);
54 $tz = core_date::get_user_timezone($tz);
55 $date = new DateTime('now', new DateTimeZone($tz));
56 return ($date->getOffset() - dst_offset_on(time(), $tz)) / (3600.0);
59 /**
60 * Returns an int which represents the systems's timezone difference from GMT in seconds
61 * @deprecated since Moodle 2.9
62 * @param float|int|string $tz timezone for which offset is required.
63 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
64 * @return int|bool if found, false is timezone 99 or error
66 function get_timezone_offset($tz) {
67 debugging('get_timezone_offset() is deprecated, use PHP DateTimeZone instead', DEBUG_DEVELOPER);
68 $date = new DateTime('now', new DateTimeZone(core_date::normalise_timezone($tz)));
69 return $date->getOffset() - dst_offset_on(time(), $tz);
72 /**
73 * Returns a list of timezones in the current language.
74 * @deprecated since Moodle 2.9
75 * @return array
77 function get_list_of_timezones() {
78 debugging('get_list_of_timezones() is deprecated, use core_date::get_list_of_timezones() instead', DEBUG_DEVELOPER);
79 return core_date::get_list_of_timezones();
82 /**
83 * Previous internal API, it was not supposed to be used anywhere.
84 * @deprecated since Moodle 2.9
85 * @param array $timezones
87 function update_timezone_records($timezones) {
88 debugging('update_timezone_records() is not available any more, use standard PHP date/time code', DEBUG_DEVELOPER);
91 /**
92 * Previous internal API, it was not supposed to be used anywhere.
93 * @deprecated since Moodle 2.9
94 * @param int $fromyear
95 * @param int $toyear
96 * @param mixed $strtimezone
97 * @return bool
99 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
100 debugging('calculate_user_dst_table() is not available any more, use standard PHP date/time code', DEBUG_DEVELOPER);
101 return false;
105 * Previous internal API, it was not supposed to be used anywhere.
106 * @deprecated since Moodle 2.9
107 * @param int|string $year
108 * @param mixed $timezone
109 * @return null
111 function dst_changes_for_year($year, $timezone) {
112 debugging('dst_changes_for_year() is not available any more, use standard PHP date/time code', DEBUG_DEVELOPER);
113 return null;
117 * Previous internal API, it was not supposed to be used anywhere.
118 * @deprecated since Moodle 2.9
119 * @param string $timezonename
120 * @return array
122 function get_timezone_record($timezonename) {
123 debugging('get_timezone_record() is not available any more, use standard PHP date/time code', DEBUG_DEVELOPER);
124 return array();
128 * Add an entry to the legacy log table.
130 * @deprecated since 2.7 use new events instead
132 * @param int $courseid The course id
133 * @param string $module The module name e.g. forum, journal, resource, course, user etc
134 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
135 * @param string $url The file and parameters used to see the results of the action
136 * @param string $info Additional description information
137 * @param int $cm The course_module->id if there is one
138 * @param int|stdClass $user If log regards $user other than $USER
139 * @return void
141 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
142 debugging('add_to_log() has been deprecated, please rewrite your code to the new events API', DEBUG_DEVELOPER);
144 // This is a nasty hack that allows us to put all the legacy stuff into legacy storage,
145 // this way we may move all the legacy settings there too.
146 $manager = get_log_manager();
147 if (method_exists($manager, 'legacy_add_to_log')) {
148 $manager->legacy_add_to_log($courseid, $module, $action, $url, $info, $cm, $user);
153 * Adds a file upload to the log table so that clam can resolve the filename to the user later if necessary
155 * @deprecated since 2.7 - use new file picker instead
158 function clam_log_upload($newfilepath, $course=null, $nourl=false) {
159 throw new coding_exception('clam_log_upload() can not be used any more, please use file picker instead');
163 * This function logs to error_log and to the log table that an infected file has been found and what's happened to it.
165 * @deprecated since 2.7 - use new file picker instead
168 function clam_log_infected($oldfilepath='', $newfilepath='', $userid=0) {
169 throw new coding_exception('clam_log_infected() can not be used any more, please use file picker instead');
173 * Some of the modules allow moving attachments (glossary), in which case we need to hunt down an original log and change the path.
175 * @deprecated since 2.7 - use new file picker instead
178 function clam_change_log($oldpath, $newpath, $update=true) {
179 throw new coding_exception('clam_change_log() can not be used any more, please use file picker instead');
183 * Replaces the given file with a string.
185 * @deprecated since 2.7 - infected files are now deleted in file picker
188 function clam_replace_infected_file($file) {
189 throw new coding_exception('clam_replace_infected_file() can not be used any more, please use file picker instead');
193 * Deals with an infected file - either moves it to a quarantinedir
194 * (specified in CFG->quarantinedir) or deletes it.
196 * If moving it fails, it deletes it.
198 * @deprecated since 2.7
200 function clam_handle_infected_file($file, $userid=0, $basiconly=false) {
201 throw new coding_exception('clam_handle_infected_file() can not be used any more, please use file picker instead');
205 * If $CFG->runclamonupload is set, we scan a given file. (called from {@link preprocess_files()})
207 * @deprecated since 2.7
209 function clam_scan_moodle_file(&$file, $course) {
210 throw new coding_exception('clam_scan_moodle_file() can not be used any more, please use file picker instead');
215 * Checks whether the password compatibility library will work with the current
216 * version of PHP. This cannot be done using PHP version numbers since the fix
217 * has been backported to earlier versions in some distributions.
219 * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
221 * @deprecated since 2.7 PHP 5.4.x should be always compatible.
223 * @return bool always returns false
225 function password_compat_not_supported() {
226 debugging('Do not use password_compat_not_supported() - bcrypt is now always available', DEBUG_DEVELOPER);
227 return false;
231 * Factory method that was returning moodle_session object.
233 * @deprecated since 2.6
234 * @return \core\session\manager
236 function session_get_instance() {
237 // Note: the new session manager includes all methods from the original session class.
238 static $deprecatedinstance = null;
240 debugging('session_get_instance() is deprecated, use \core\session\manager instead', DEBUG_DEVELOPER);
242 if (!$deprecatedinstance) {
243 $deprecatedinstance = new \core\session\manager();
246 return $deprecatedinstance;
250 * Returns true if legacy session used.
252 * @deprecated since 2.6
253 * @return bool
255 function session_is_legacy() {
256 debugging('session_is_legacy() is deprecated, do not use any more', DEBUG_DEVELOPER);
257 return false;
261 * Terminates all sessions, auth hooks are not executed.
262 * Useful in upgrade scripts.
264 * @deprecated since 2.6
266 function session_kill_all() {
267 debugging('session_kill_all() is deprecated, use \core\session\manager::kill_all_sessions() instead', DEBUG_DEVELOPER);
268 \core\session\manager::kill_all_sessions();
272 * Mark session as accessed, prevents timeouts.
274 * @deprecated since 2.6
275 * @param string $sid
277 function session_touch($sid) {
278 debugging('session_touch() is deprecated, use \core\session\manager::touch_session() instead', DEBUG_DEVELOPER);
279 \core\session\manager::touch_session($sid);
283 * Terminates one sessions, auth hooks are not executed.
285 * @deprecated since 2.6
286 * @param string $sid session id
288 function session_kill($sid) {
289 debugging('session_kill() is deprecated, use \core\session\manager::kill_session() instead', DEBUG_DEVELOPER);
290 \core\session\manager::kill_session($sid);
294 * Terminates all sessions of one user, auth hooks are not executed.
295 * NOTE: This can not work for file based sessions!
297 * @deprecated since 2.6
298 * @param int $userid user id
300 function session_kill_user($userid) {
301 debugging('session_kill_user() is deprecated, use \core\session\manager::kill_user_sessions() instead', DEBUG_DEVELOPER);
302 \core\session\manager::kill_user_sessions($userid);
306 * Setup $USER object - called during login, loginas, etc.
308 * Call sync_user_enrolments() manually after log-in, or log-in-as.
310 * @deprecated since 2.6
311 * @param stdClass $user full user record object
312 * @return void
314 function session_set_user($user) {
315 debugging('session_set_user() is deprecated, use \core\session\manager::set_user() instead', DEBUG_DEVELOPER);
316 \core\session\manager::set_user($user);
320 * Is current $USER logged-in-as somebody else?
321 * @deprecated since 2.6
322 * @return bool
324 function session_is_loggedinas() {
325 debugging('session_is_loggedinas() is deprecated, use \core\session\manager::is_loggedinas() instead', DEBUG_DEVELOPER);
326 return \core\session\manager::is_loggedinas();
330 * Returns the $USER object ignoring current login-as session
331 * @deprecated since 2.6
332 * @return stdClass user object
334 function session_get_realuser() {
335 debugging('session_get_realuser() is deprecated, use \core\session\manager::get_realuser() instead', DEBUG_DEVELOPER);
336 return \core\session\manager::get_realuser();
340 * Login as another user - no security checks here.
341 * @deprecated since 2.6
342 * @param int $userid
343 * @param stdClass $context
344 * @return void
346 function session_loginas($userid, $context) {
347 debugging('session_loginas() is deprecated, use \core\session\manager::loginas() instead', DEBUG_DEVELOPER);
348 \core\session\manager::loginas($userid, $context);
352 * Minify JavaScript files.
354 * @deprecated since 2.6
356 * @param array $files
357 * @return string
359 function js_minify($files) {
360 debugging('js_minify() is deprecated, use core_minify::js_files() or core_minify::js() instead.');
361 return core_minify::js_files($files);
365 * Minify CSS files.
367 * @deprecated since 2.6
369 * @param array $files
370 * @return string
372 function css_minify_css($files) {
373 debugging('css_minify_css() is deprecated, use core_minify::css_files() or core_minify::css() instead.');
374 return core_minify::css_files($files);
378 * Function to call all event handlers when triggering an event
380 * @deprecated since 2.6
382 * @param string $eventname name of the event
383 * @param mixed $eventdata event data object
384 * @return int number of failed events
386 function events_trigger($eventname, $eventdata) {
387 debugging('events_trigger() is deprecated, please use new events instead', DEBUG_DEVELOPER);
388 return events_trigger_legacy($eventname, $eventdata);
392 * List all core subsystems and their location
394 * This is a whitelist of components that are part of the core and their
395 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
396 * plugin is not listed here and it does not have proper plugintype prefix,
397 * then it is considered as course activity module.
399 * The location is optionally dirroot relative path. NULL means there is no special
400 * directory for this subsystem. If the location is set, the subsystem's
401 * renderer.php is expected to be there.
403 * @deprecated since 2.6, use core_component::get_core_subsystems()
405 * @param bool $fullpaths false means relative paths from dirroot, use true for performance reasons
406 * @return array of (string)name => (string|null)location
408 function get_core_subsystems($fullpaths = false) {
409 global $CFG;
411 // NOTE: do not add any other debugging here, keep forever.
413 $subsystems = core_component::get_core_subsystems();
415 if ($fullpaths) {
416 return $subsystems;
419 debugging('Short paths are deprecated when using get_core_subsystems(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
421 $dlength = strlen($CFG->dirroot);
423 foreach ($subsystems as $k => $v) {
424 if ($v === null) {
425 continue;
427 $subsystems[$k] = substr($v, $dlength+1);
430 return $subsystems;
434 * Lists all plugin types.
436 * @deprecated since 2.6, use core_component::get_plugin_types()
438 * @param bool $fullpaths false means relative paths from dirroot
439 * @return array Array of strings - name=>location
441 function get_plugin_types($fullpaths = true) {
442 global $CFG;
444 // NOTE: do not add any other debugging here, keep forever.
446 $types = core_component::get_plugin_types();
448 if ($fullpaths) {
449 return $types;
452 debugging('Short paths are deprecated when using get_plugin_types(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
454 $dlength = strlen($CFG->dirroot);
456 foreach ($types as $k => $v) {
457 if ($k === 'theme') {
458 $types[$k] = 'theme';
459 continue;
461 $types[$k] = substr($v, $dlength+1);
464 return $types;
468 * Use when listing real plugins of one type.
470 * @deprecated since 2.6, use core_component::get_plugin_list()
472 * @param string $plugintype type of plugin
473 * @return array name=>fulllocation pairs of plugins of given type
475 function get_plugin_list($plugintype) {
477 // NOTE: do not add any other debugging here, keep forever.
479 if ($plugintype === '') {
480 $plugintype = 'mod';
483 return core_component::get_plugin_list($plugintype);
487 * Get a list of all the plugins of a given type that define a certain class
488 * in a certain file. The plugin component names and class names are returned.
490 * @deprecated since 2.6, use core_component::get_plugin_list_with_class()
492 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
493 * @param string $class the part of the name of the class after the
494 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
495 * names like report_courselist_thing. If you are looking for classes with
496 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
497 * @param string $file the name of file within the plugin that defines the class.
498 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
499 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
501 function get_plugin_list_with_class($plugintype, $class, $file) {
503 // NOTE: do not add any other debugging here, keep forever.
505 return core_component::get_plugin_list_with_class($plugintype, $class, $file);
509 * Returns the exact absolute path to plugin directory.
511 * @deprecated since 2.6, use core_component::get_plugin_directory()
513 * @param string $plugintype type of plugin
514 * @param string $name name of the plugin
515 * @return string full path to plugin directory; NULL if not found
517 function get_plugin_directory($plugintype, $name) {
519 // NOTE: do not add any other debugging here, keep forever.
521 if ($plugintype === '') {
522 $plugintype = 'mod';
525 return core_component::get_plugin_directory($plugintype, $name);
529 * Normalize the component name using the "frankenstyle" names.
531 * @deprecated since 2.6, use core_component::normalize_component()
533 * @param string $component
534 * @return array as (string)$type => (string)$plugin
536 function normalize_component($component) {
538 // NOTE: do not add any other debugging here, keep forever.
540 return core_component::normalize_component($component);
544 * Return exact absolute path to a plugin directory.
546 * @deprecated since 2.6, use core_component::normalize_component()
548 * @param string $component name such as 'moodle', 'mod_forum'
549 * @return string full path to component directory; NULL if not found
551 function get_component_directory($component) {
553 // NOTE: do not add any other debugging here, keep forever.
555 return core_component::get_component_directory($component);
559 // === Deprecated before 2.6.0 ===
562 * Hack to find out the GD version by parsing phpinfo output
564 * @return int GD version (1, 2, or 0)
566 function check_gd_version() {
567 // TODO: delete function in Moodle 2.7
568 debugging('check_gd_version() is deprecated, GD extension is always available now');
570 $gdversion = 0;
572 if (function_exists('gd_info')){
573 $gd_info = gd_info();
574 if (substr_count($gd_info['GD Version'], '2.')) {
575 $gdversion = 2;
576 } else if (substr_count($gd_info['GD Version'], '1.')) {
577 $gdversion = 1;
580 } else {
581 ob_start();
582 phpinfo(INFO_MODULES);
583 $phpinfo = ob_get_contents();
584 ob_end_clean();
586 $phpinfo = explode("\n", $phpinfo);
589 foreach ($phpinfo as $text) {
590 $parts = explode('</td>', $text);
591 foreach ($parts as $key => $val) {
592 $parts[$key] = trim(strip_tags($val));
594 if ($parts[0] == 'GD Version') {
595 if (substr_count($parts[1], '2.0')) {
596 $parts[1] = '2.0';
598 $gdversion = intval($parts[1]);
603 return $gdversion; // 1, 2 or 0
607 * Not used any more, the account lockout handling is now
608 * part of authenticate_user_login().
609 * @deprecated
611 function update_login_count() {
612 // TODO: delete function in Moodle 2.6
613 debugging('update_login_count() is deprecated, all calls need to be removed');
617 * Not used any more, replaced by proper account lockout.
618 * @deprecated
620 function reset_login_count() {
621 // TODO: delete function in Moodle 2.6
622 debugging('reset_login_count() is deprecated, all calls need to be removed');
626 * Insert or update log display entry. Entry may already exist.
627 * $module, $action must be unique
628 * @deprecated
630 * @param string $module
631 * @param string $action
632 * @param string $mtable
633 * @param string $field
634 * @return void
637 function update_log_display_entry($module, $action, $mtable, $field) {
638 global $DB;
640 debugging('The update_log_display_entry() is deprecated, please use db/log.php description file instead.');
644 * @deprecated use the text formatting in a standard way instead (http://docs.moodle.org/dev/Output_functions)
645 * this was abused mostly for embedding of attachments
647 function filter_text($text, $courseid = NULL) {
648 throw new coding_exception('filter_text() can not be used anymore, use format_text(), format_string() etc instead.');
652 * @deprecated use $PAGE->https_required() instead
654 function httpsrequired() {
655 throw new coding_exception('httpsrequired() can not be used any more use $PAGE->https_required() instead.');
659 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
661 * @deprecated use moodle_url factory methods instead
663 * @param string $path Physical path to a file
664 * @param array $options associative array of GET variables to append to the URL
665 * @param string $type (questionfile|rssfile|httpscoursefile|coursefile)
666 * @return string URL to file
668 function get_file_url($path, $options=null, $type='coursefile') {
669 global $CFG;
671 $path = str_replace('//', '/', $path);
672 $path = trim($path, '/'); // no leading and trailing slashes
674 // type of file
675 switch ($type) {
676 case 'questionfile':
677 $url = $CFG->wwwroot."/question/exportfile.php";
678 break;
679 case 'rssfile':
680 $url = $CFG->wwwroot."/rss/file.php";
681 break;
682 case 'httpscoursefile':
683 $url = $CFG->httpswwwroot."/file.php";
684 break;
685 case 'coursefile':
686 default:
687 $url = $CFG->wwwroot."/file.php";
690 if ($CFG->slasharguments) {
691 $parts = explode('/', $path);
692 foreach ($parts as $key => $part) {
693 /// anchor dash character should not be encoded
694 $subparts = explode('#', $part);
695 $subparts = array_map('rawurlencode', $subparts);
696 $parts[$key] = implode('#', $subparts);
698 $path = implode('/', $parts);
699 $ffurl = $url.'/'.$path;
700 $separator = '?';
701 } else {
702 $path = rawurlencode('/'.$path);
703 $ffurl = $url.'?file='.$path;
704 $separator = '&amp;';
707 if ($options) {
708 foreach ($options as $name=>$value) {
709 $ffurl = $ffurl.$separator.$name.'='.$value;
710 $separator = '&amp;';
714 return $ffurl;
718 * @deprecated use get_enrolled_users($context) instead.
720 function get_course_participants($courseid) {
721 throw new coding_exception('get_course_participants() can not be used any more, use get_enrolled_users() instead.');
725 * @deprecated use is_enrolled($context, $userid) instead.
727 function is_course_participant($userid, $courseid) {
728 throw new coding_exception('is_course_participant() can not be used any more, use is_enrolled() instead.');
732 * Searches logs to find all enrolments since a certain date
734 * used to print recent activity
736 * @param int $courseid The course in question.
737 * @param int $timestart The date to check forward of
738 * @return object|false {@link $USER} records or false if error.
740 function get_recent_enrolments($courseid, $timestart) {
741 global $DB;
743 debugging('get_recent_enrolments() is deprecated as it returned inaccurate results.', DEBUG_DEVELOPER);
745 $context = context_course::instance($courseid);
746 $sql = "SELECT u.id, u.firstname, u.lastname, MAX(l.time)
747 FROM {user} u, {role_assignments} ra, {log} l
748 WHERE l.time > ?
749 AND l.course = ?
750 AND l.module = 'course'
751 AND l.action = 'enrol'
752 AND ".$DB->sql_cast_char2int('l.info')." = u.id
753 AND u.id = ra.userid
754 AND ra.contextid ".get_related_contexts_string($context)."
755 GROUP BY u.id, u.firstname, u.lastname
756 ORDER BY MAX(l.time) ASC";
757 $params = array($timestart, $courseid);
758 return $DB->get_records_sql($sql, $params);
762 * @deprecated use clean_param($string, PARAM_FILE) instead.
764 function detect_munged_arguments($string, $allowdots=1) {
765 throw new coding_exception('detect_munged_arguments() can not be used any more, please use clean_param(,PARAM_FILE) instead.');
770 * Unzip one zip file to a destination dir
771 * Both parameters must be FULL paths
772 * If destination isn't specified, it will be the
773 * SAME directory where the zip file resides.
775 * @global object
776 * @param string $zipfile The zip file to unzip
777 * @param string $destination The location to unzip to
778 * @param bool $showstatus_ignored Unused
780 function unzip_file($zipfile, $destination = '', $showstatus_ignored = true) {
781 global $CFG;
783 //Extract everything from zipfile
784 $path_parts = pathinfo(cleardoubleslashes($zipfile));
785 $zippath = $path_parts["dirname"]; //The path of the zip file
786 $zipfilename = $path_parts["basename"]; //The name of the zip file
787 $extension = $path_parts["extension"]; //The extension of the file
789 //If no file, error
790 if (empty($zipfilename)) {
791 return false;
794 //If no extension, error
795 if (empty($extension)) {
796 return false;
799 //Clear $zipfile
800 $zipfile = cleardoubleslashes($zipfile);
802 //Check zipfile exists
803 if (!file_exists($zipfile)) {
804 return false;
807 //If no destination, passed let's go with the same directory
808 if (empty($destination)) {
809 $destination = $zippath;
812 //Clear $destination
813 $destpath = rtrim(cleardoubleslashes($destination), "/");
815 //Check destination path exists
816 if (!is_dir($destpath)) {
817 return false;
820 $packer = get_file_packer('application/zip');
822 $result = $packer->extract_to_pathname($zipfile, $destpath);
824 if ($result === false) {
825 return false;
828 foreach ($result as $status) {
829 if ($status !== true) {
830 return false;
834 return true;
838 * Zip an array of files/dirs to a destination zip file
839 * Both parameters must be FULL paths to the files/dirs
841 * @global object
842 * @param array $originalfiles Files to zip
843 * @param string $destination The destination path
844 * @return bool Outcome
846 function zip_files ($originalfiles, $destination) {
847 global $CFG;
849 //Extract everything from destination
850 $path_parts = pathinfo(cleardoubleslashes($destination));
851 $destpath = $path_parts["dirname"]; //The path of the zip file
852 $destfilename = $path_parts["basename"]; //The name of the zip file
853 $extension = $path_parts["extension"]; //The extension of the file
855 //If no file, error
856 if (empty($destfilename)) {
857 return false;
860 //If no extension, add it
861 if (empty($extension)) {
862 $extension = 'zip';
863 $destfilename = $destfilename.'.'.$extension;
866 //Check destination path exists
867 if (!is_dir($destpath)) {
868 return false;
871 //Check destination path is writable. TODO!!
873 //Clean destination filename
874 $destfilename = clean_filename($destfilename);
876 //Now check and prepare every file
877 $files = array();
878 $origpath = NULL;
880 foreach ($originalfiles as $file) { //Iterate over each file
881 //Check for every file
882 $tempfile = cleardoubleslashes($file); // no doubleslashes!
883 //Calculate the base path for all files if it isn't set
884 if ($origpath === NULL) {
885 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
887 //See if the file is readable
888 if (!is_readable($tempfile)) { //Is readable
889 continue;
891 //See if the file/dir is in the same directory than the rest
892 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
893 continue;
895 //Add the file to the array
896 $files[] = $tempfile;
899 $zipfiles = array();
900 $start = strlen($origpath)+1;
901 foreach($files as $file) {
902 $zipfiles[substr($file, $start)] = $file;
905 $packer = get_file_packer('application/zip');
907 return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename);
911 * @deprecated use groups_get_all_groups() instead.
913 function mygroupid($courseid) {
914 throw new coding_exception('mygroupid() can not be used any more, please use groups_get_all_groups() instead.');
919 * Returns the current group mode for a given course or activity module
921 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
923 * @param object $course Course Object
924 * @param object $cm Course Manager Object
925 * @return mixed $course->groupmode
927 function groupmode($course, $cm=null) {
929 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
930 return $cm->groupmode;
932 return $course->groupmode;
936 * Sets the current group in the session variable
937 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
938 * Sets currentgroup[$courseid] in the session variable appropriately.
939 * Does not do any permission checking.
941 * @global object
942 * @param int $courseid The course being examined - relates to id field in
943 * 'course' table.
944 * @param int $groupid The group being examined.
945 * @return int Current group id which was set by this function
947 function set_current_group($courseid, $groupid) {
948 global $SESSION;
949 return $SESSION->currentgroup[$courseid] = $groupid;
954 * Gets the current group - either from the session variable or from the database.
956 * @global object
957 * @param int $courseid The course being examined - relates to id field in
958 * 'course' table.
959 * @param bool $full If true, the return value is a full record object.
960 * If false, just the id of the record.
961 * @return int|bool
963 function get_current_group($courseid, $full = false) {
964 global $SESSION;
966 if (isset($SESSION->currentgroup[$courseid])) {
967 if ($full) {
968 return groups_get_group($SESSION->currentgroup[$courseid]);
969 } else {
970 return $SESSION->currentgroup[$courseid];
974 $mygroupid = mygroupid($courseid);
975 if (is_array($mygroupid)) {
976 $mygroupid = array_shift($mygroupid);
977 set_current_group($courseid, $mygroupid);
978 if ($full) {
979 return groups_get_group($mygroupid);
980 } else {
981 return $mygroupid;
985 if ($full) {
986 return false;
987 } else {
988 return 0;
993 * Filter a user list and return only the users that can see the course module based on
994 * groups/permissions etc. It is assumed that the users are pre-filtered to those who are enrolled in the course.
996 * @category group
997 * @param stdClass|cm_info $cm The course module
998 * @param array $users An array of users, indexed by userid
999 * @return array A filtered list of users that can see the module, indexed by userid.
1000 * @deprecated Since Moodle 2.8
1002 function groups_filter_users_by_course_module_visible($cm, $users) {
1003 debugging('groups_filter_users_by_course_module_visible() is deprecated. ' .
1004 'Replace with a call to \core_availability\info_module::filter_user_list(), ' .
1005 'which does basically the same thing but includes other restrictions such ' .
1006 'as profile restrictions.', DEBUG_DEVELOPER);
1007 if (empty($users)) {
1008 return $users;
1010 // Since this function allows stdclass, let's play it safe and ensure we
1011 // do have a cm_info.
1012 if (!($cm instanceof cm_info)) {
1013 $modinfo = get_fast_modinfo($cm->course);
1014 $cm = $modinfo->get_cm($cm->id);
1016 $info = new \core_availability\info_module($cm);
1017 return $info->filter_user_list($users);
1021 * Determine if a course module is currently visible to a user
1023 * Deprecated (it was never very useful as it only took into account the
1024 * groupmembersonly option and no other way of hiding activities). Always
1025 * returns true.
1027 * @category group
1028 * @param stdClass|cm_info $cm The course module
1029 * @param int $userid The user to check against the group.
1030 * @return bool True
1031 * @deprecated Since Moodle 2.8
1033 function groups_course_module_visible($cm, $userid=null) {
1034 debugging('groups_course_module_visible() is deprecated and always returns ' .
1035 'true; use $cm->uservisible to decide whether the current user can ' .
1036 'access an activity.', DEBUG_DEVELOPER);
1037 return true;
1041 * Inndicates fatal error. This function was originally printing the
1042 * error message directly, since 2.0 it is throwing exception instead.
1043 * The error printing is handled in default exception handler.
1045 * Old method, don't call directly in new code - use print_error instead.
1047 * @param string $message The message to display to the user about the error.
1048 * @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.
1049 * @return void, always throws moodle_exception
1051 function error($message, $link='') {
1052 throw new moodle_exception('notlocalisederrormessage', 'error', $link, $message, 'error() is a deprecated function, please call print_error() instead of error()');
1057 * @deprecated use $PAGE->theme->name instead.
1059 function current_theme() {
1060 throw new coding_exception('current_theme() can not be used any more, please use $PAGE->theme->name instead');
1064 * Prints some red text using echo
1066 * @deprecated
1067 * @param string $error The text to be displayed in red
1069 function formerr($error) {
1070 debugging('formerr() has been deprecated. Please change your code to use $OUTPUT->error_text($string).');
1071 global $OUTPUT;
1072 echo $OUTPUT->error_text($error);
1076 * @deprecated use $OUTPUT->skip_link_target() in instead.
1078 function skip_main_destination() {
1079 throw new coding_exception('skip_main_destination() can not be used any more, please use $OUTPUT->skip_link_target() instead.');
1083 * @deprecated use $OUTPUT->container() instead.
1085 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
1086 throw new coding_exception('print_container() can not be used any more. Please use $OUTPUT->container() instead.');
1090 * @deprecated use $OUTPUT->container_start() instead.
1092 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
1093 throw new coding_exception('print_container_start() can not be used any more. Please use $OUTPUT->container_start() instead.');
1097 * @deprecated use $OUTPUT->container_end() instead.
1099 function print_container_end($return=false) {
1100 throw new coding_exception('print_container_end() can not be used any more. Please use $OUTPUT->container_end() instead.');
1104 * Print a bold message in an optional color.
1106 * @deprecated use $OUTPUT->notification instead.
1107 * @param string $message The message to print out
1108 * @param string $style Optional style to display message text in
1109 * @param string $align Alignment option
1110 * @param bool $return whether to return an output string or echo now
1111 * @return string|bool Depending on $result
1113 function notify($message, $classes = 'notifyproblem', $align = 'center', $return = false) {
1114 global $OUTPUT;
1116 if ($classes == 'green') {
1117 debugging('Use of deprecated class name "green" in notify. Please change to "notifysuccess".', DEBUG_DEVELOPER);
1118 $classes = 'notifysuccess'; // Backward compatible with old color system
1121 $output = $OUTPUT->notification($message, $classes);
1122 if ($return) {
1123 return $output;
1124 } else {
1125 echo $output;
1130 * @deprecated use $OUTPUT->continue_button() instead.
1132 function print_continue($link, $return = false) {
1133 throw new coding_exception('print_continue() can not be used any more. Please use $OUTPUT->continue_button() instead.');
1137 * @deprecated use $PAGE methods instead.
1139 function print_header($title='', $heading='', $navigation='', $focus='',
1140 $meta='', $cache=true, $button='&nbsp;', $menu=null,
1141 $usexml=false, $bodytags='', $return=false) {
1143 throw new coding_exception('print_header() can not be used any more. Please use $PAGE methods instead.');
1147 * @deprecated use $PAGE methods instead.
1149 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
1150 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
1152 throw new coding_exception('print_header_simple() can not be used any more. Please use $PAGE methods instead.');
1156 * @deprecated use $OUTPUT->block() instead.
1158 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
1159 throw new coding_exception('print_side_block() can not be used any more, please use $OUTPUT->block() instead.');
1163 * Prints a basic textarea field.
1165 * @deprecated since Moodle 2.0
1167 * When using this function, you should
1169 * @global object
1170 * @param bool $unused No longer used.
1171 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
1172 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
1173 * @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.
1174 * @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.
1175 * @param string $name Name to use for the textarea element.
1176 * @param string $value Initial content to display in the textarea.
1177 * @param int $obsolete deprecated
1178 * @param bool $return If false, will output string. If true, will return string value.
1179 * @param string $id CSS ID to add to the textarea element.
1180 * @return string|void depending on the value of $return
1182 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
1183 /// $width and height are legacy fields and no longer used as pixels like they used to be.
1184 /// However, you can set them to zero to override the mincols and minrows values below.
1186 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
1187 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
1189 global $CFG;
1191 $mincols = 65;
1192 $minrows = 10;
1193 $str = '';
1195 if ($id === '') {
1196 $id = 'edit-'.$name;
1199 if ($height && ($rows < $minrows)) {
1200 $rows = $minrows;
1202 if ($width && ($cols < $mincols)) {
1203 $cols = $mincols;
1206 editors_head_setup();
1207 $editor = editors_get_preferred_editor(FORMAT_HTML);
1208 $editor->use_editor($id, array('legacy'=>true));
1210 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
1211 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
1212 $str .= '</textarea>'."\n";
1214 if ($return) {
1215 return $str;
1217 echo $str;
1221 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
1222 * Should be used only with htmleditor or textarea.
1224 * @global object
1225 * @global object
1226 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
1227 * helpbutton.
1228 * @return string Link to help button
1230 function editorhelpbutton(){
1231 return '';
1233 /// TODO: MDL-21215
1237 * Print a help button.
1239 * Prints a special help button for html editors (htmlarea in this case)
1241 * @todo Write code into this function! detect current editor and print correct info
1242 * @global object
1243 * @return string Only returns an empty string at the moment
1245 function editorshortcutshelpbutton() {
1246 /// TODO: MDL-21215
1248 global $CFG;
1249 //TODO: detect current editor and print correct info
1250 return '';
1255 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
1256 * provide this function with the language strings for sortasc and sortdesc.
1258 * @deprecated use $OUTPUT->arrow() instead.
1259 * @todo final deprecation of this function once MDL-45448 is resolved
1261 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
1263 * @global object
1264 * @param string $direction 'up' or 'down'
1265 * @param string $strsort The language string used for the alt attribute of this image
1266 * @param bool $return Whether to print directly or return the html string
1267 * @return string|void depending on $return
1270 function print_arrow($direction='up', $strsort=null, $return=false) {
1271 global $OUTPUT;
1273 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER);
1275 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
1276 return null;
1279 $return = null;
1281 switch ($direction) {
1282 case 'up':
1283 $sortdir = 'asc';
1284 break;
1285 case 'down':
1286 $sortdir = 'desc';
1287 break;
1288 case 'move':
1289 $sortdir = 'asc';
1290 break;
1291 default:
1292 $sortdir = null;
1293 break;
1296 // Prepare language string
1297 $strsort = '';
1298 if (empty($strsort) && !empty($sortdir)) {
1299 $strsort = get_string('sort' . $sortdir, 'grades');
1302 $return = ' <img src="'.$OUTPUT->pix_url('t/' . $direction) . '" alt="'.$strsort.'" /> ';
1304 if ($return) {
1305 return $return;
1306 } else {
1307 echo $return;
1312 * Given an array of values, output the HTML for a select element with those options.
1314 * @deprecated since Moodle 2.0
1316 * Normally, you only need to use the first few parameters.
1318 * @param array $options The options to offer. An array of the form
1319 * $options[{value}] = {text displayed for that option};
1320 * @param string $name the name of this form control, as in &lt;select name="..." ...
1321 * @param string $selected the option to select initially, default none.
1322 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
1323 * Set this to '' if you don't want a 'nothing is selected' option.
1324 * @param string $script if not '', then this is added to the &lt;select> element as an onchange handler.
1325 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
1326 * @param boolean $return if false (the default) the the output is printed directly, If true, the
1327 * generated HTML is returned as a string.
1328 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
1329 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
1330 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
1331 * then a suitable one is constructed.
1332 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
1333 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
1334 * $listbox is an integer, that number is used for size instead.
1335 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
1336 * when $listbox display is enabled
1337 * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
1338 * then a suitable one is constructed.
1339 * @return string|void If $return=true returns string, else echo's and returns void
1341 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1342 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
1343 $id='', $listbox=false, $multiple=false, $class='') {
1345 global $OUTPUT;
1346 debugging('choose_from_menu() has been deprecated. Please change your code to use html_writer::select().');
1348 if ($script) {
1349 debugging('The $script parameter has been deprecated. You must use component_actions instead', DEBUG_DEVELOPER);
1351 $attributes = array();
1352 $attributes['disabled'] = $disabled ? 'disabled' : null;
1353 $attributes['tabindex'] = $tabindex ? $tabindex : null;
1354 $attributes['multiple'] = $multiple ? $multiple : null;
1355 $attributes['class'] = $class ? $class : null;
1356 $attributes['id'] = $id ? $id : null;
1358 $output = html_writer::select($options, $name, $selected, array($nothingvalue=>$nothing), $attributes);
1360 if ($return) {
1361 return $output;
1362 } else {
1363 echo $output;
1368 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1370 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1371 throw new coding_exception('print_scale_menu_helpbutton() can not be used any more. '.
1372 'Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.');
1376 * @deprecated use html_writer::checkbox() instead.
1378 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1379 throw new coding_exception('print_checkbox() can not be used any more. Please use html_writer::checkbox() instead.');
1383 * Prints the 'update this xxx' button that appears on module pages.
1385 * @deprecated since Moodle 2.0
1387 * @param string $cmid the course_module id.
1388 * @param string $ignored not used any more. (Used to be courseid.)
1389 * @param string $string the module name - get_string('modulename', 'xxx')
1390 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1392 function update_module_button($cmid, $ignored, $string) {
1393 global $CFG, $OUTPUT;
1395 // debugging('update_module_button() has been deprecated. Please change your code to use $OUTPUT->update_module_button().');
1397 //NOTE: DO NOT call new output method because it needs the module name we do not have here!
1399 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1400 $string = get_string('updatethis', '', $string);
1402 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1403 return $OUTPUT->single_button($url, $string);
1404 } else {
1405 return '';
1410 * @deprecated use $OUTPUT->navbar() instead
1412 function print_navigation ($navigation, $separator=0, $return=false) {
1413 throw new coding_exception('print_navigation() can not be used any more, please update use $OUTPUT->navbar() instead.');
1417 * @deprecated Please use $PAGE->navabar methods instead.
1419 function build_navigation($extranavlinks, $cm = null) {
1420 throw new coding_exception('build_navigation() can not be used any more, please use $PAGE->navbar methods instead.');
1424 * @deprecated not relevant with global navigation in Moodle 2.x+
1426 function navmenu($course, $cm=NULL, $targetwindow='self') {
1427 throw new coding_exception('navmenu() can not be used any more, it is no longer relevant with global navigation.');
1430 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1434 * @deprecated please use calendar_event::create() instead.
1436 function add_event($event) {
1437 throw new coding_exception('add_event() can not be used any more, please use calendar_event::create() instead.');
1441 * Call this function to update an event in the calendar table
1442 * the event will be identified by the id field of the $event object.
1444 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
1445 * @return bool Success
1446 * @deprecated please calendar_event->update() instead.
1448 function update_event($event) {
1449 global $CFG;
1450 require_once($CFG->dirroot.'/calendar/lib.php');
1452 debugging('update_event() is deprecated, please use calendar_event->update() instead.', DEBUG_DEVELOPER);
1453 $event = (object)$event;
1454 $calendarevent = calendar_event::load($event->id);
1455 return $calendarevent->update($event);
1459 * @deprecated please use calendar_event->delete() instead.
1461 function delete_event($id) {
1462 throw new coding_exception('delete_event() can not be used any more, please use '.
1463 'calendar_event->delete() instead.');
1467 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1469 function hide_event($event) {
1470 throw new coding_exception('hide_event() can not be used any more, please use '.
1471 'calendar_event->toggle_visibility(false) instead.');
1475 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1477 function show_event($event) {
1478 throw new coding_exception('show_event() can not be used any more, please use '.
1479 'calendar_event->toggle_visibility(true) instead.');
1483 * Original singleton helper function, please use static methods instead,
1484 * ex: core_text::convert().
1486 * @deprecated since Moodle 2.2 use core_text::xxxx() instead.
1487 * @see core_text
1489 function textlib_get_instance() {
1490 throw new coding_exception('textlib_get_instance() can not be used any more, please use '.
1491 'core_text::functioname() instead.');
1495 * Gets the generic section name for a courses section
1497 * The global function is deprecated. Each course format can define their own generic section name
1499 * @deprecated since 2.4
1500 * @see get_section_name()
1501 * @see format_base::get_section_name()
1503 * @param string $format Course format ID e.g. 'weeks' $course->format
1504 * @param stdClass $section Section object from database
1505 * @return Display name that the course format prefers, e.g. "Week 2"
1507 function get_generic_section_name($format, stdClass $section) {
1508 debugging('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base', DEBUG_DEVELOPER);
1509 return get_string('sectionname', "format_$format") . ' ' . $section->section;
1513 * Returns an array of sections for the requested course id
1515 * It is usually not recommended to display the list of sections used
1516 * in course because the course format may have it's own way to do it.
1518 * If you need to just display the name of the section please call:
1519 * get_section_name($course, $section)
1520 * {@link get_section_name()}
1521 * from 2.4 $section may also be just the field course_sections.section
1523 * If you need the list of all sections it is more efficient to get this data by calling
1524 * $modinfo = get_fast_modinfo($courseorid);
1525 * $sections = $modinfo->get_section_info_all()
1526 * {@link get_fast_modinfo()}
1527 * {@link course_modinfo::get_section_info_all()}
1529 * Information about one section (instance of section_info):
1530 * get_fast_modinfo($courseorid)->get_sections_info($section)
1531 * {@link course_modinfo::get_section_info()}
1533 * @deprecated since 2.4
1535 * @param int $courseid
1536 * @return array Array of section_info objects
1538 function get_all_sections($courseid) {
1539 global $DB;
1540 debugging('get_all_sections() is deprecated. See phpdocs for this function', DEBUG_DEVELOPER);
1541 return get_fast_modinfo($courseid)->get_section_info_all();
1545 * Given a full mod object with section and course already defined, adds this module to that section.
1547 * This function is deprecated, please use {@link course_add_cm_to_section()}
1548 * Note that course_add_cm_to_section() also updates field course_modules.section and
1549 * calls rebuild_course_cache()
1551 * @deprecated since 2.4
1553 * @param object $mod
1554 * @param int $beforemod An existing ID which we will insert the new module before
1555 * @return int The course_sections ID where the mod is inserted
1557 function add_mod_to_section($mod, $beforemod = null) {
1558 debugging('Function add_mod_to_section() is deprecated, please use course_add_cm_to_section()', DEBUG_DEVELOPER);
1559 global $DB;
1560 return course_add_cm_to_section($mod->course, $mod->coursemodule, $mod->section, $beforemod);
1564 * Returns a number of useful structures for course displays
1566 * Function get_all_mods() is deprecated in 2.4
1567 * Instead of:
1568 * <code>
1569 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1570 * </code>
1571 * please use:
1572 * <code>
1573 * $mods = get_fast_modinfo($courseorid)->get_cms();
1574 * $modnames = get_module_types_names();
1575 * $modnamesplural = get_module_types_names(true);
1576 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1577 * </code>
1579 * @deprecated since 2.4
1581 * @param int $courseid id of the course to get info about
1582 * @param array $mods (return) list of course modules
1583 * @param array $modnames (return) list of names of all module types installed and available
1584 * @param array $modnamesplural (return) list of names of all module types installed and available in the plural form
1585 * @param array $modnamesused (return) list of names of all module types used in the course
1587 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1588 debugging('Function get_all_mods() is deprecated. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details', DEBUG_DEVELOPER);
1590 global $COURSE;
1591 $modnames = get_module_types_names();
1592 $modnamesplural= get_module_types_names(true);
1593 $modinfo = get_fast_modinfo($courseid);
1594 $mods = $modinfo->get_cms();
1595 $modnamesused = $modinfo->get_used_module_names();
1599 * Returns course section - creates new if does not exist yet
1601 * This function is deprecated. To create a course section call:
1602 * course_create_sections_if_missing($courseorid, $sections);
1603 * to get the section call:
1604 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1606 * @see course_create_sections_if_missing()
1607 * @see get_fast_modinfo()
1608 * @deprecated since 2.4
1610 * @param int $section relative section number (field course_sections.section)
1611 * @param int $courseid
1612 * @return stdClass record from table {course_sections}
1614 function get_course_section($section, $courseid) {
1615 global $DB;
1616 debugging('Function get_course_section() is deprecated. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.', DEBUG_DEVELOPER);
1618 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
1619 return $cw;
1621 $cw = new stdClass();
1622 $cw->course = $courseid;
1623 $cw->section = $section;
1624 $cw->summary = "";
1625 $cw->summaryformat = FORMAT_HTML;
1626 $cw->sequence = "";
1627 $id = $DB->insert_record("course_sections", $cw);
1628 rebuild_course_cache($courseid, true);
1629 return $DB->get_record("course_sections", array("id"=>$id));
1633 * Return the start and end date of the week in Weekly course format
1635 * It is not recommended to use this function outside of format_weeks plugin
1637 * @deprecated since 2.4
1638 * @see format_weeks::get_section_dates()
1640 * @param stdClass $section The course_section entry from the DB
1641 * @param stdClass $course The course entry from DB
1642 * @return stdClass property start for startdate, property end for enddate
1644 function format_weeks_get_section_dates($section, $course) {
1645 debugging('Function format_weeks_get_section_dates() is deprecated. It is not recommended to'.
1646 ' use it outside of format_weeks plugin', DEBUG_DEVELOPER);
1647 if (isset($course->format) && $course->format === 'weeks') {
1648 return course_get_format($course)->get_section_dates($section);
1650 return null;
1654 * Obtains shared data that is used in print_section when displaying a
1655 * course-module entry.
1657 * Deprecated. Instead of:
1658 * list($content, $name) = get_print_section_cm_text($cm, $course);
1659 * use:
1660 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1661 * $name = $cm->get_formatted_name();
1663 * @deprecated since 2.5
1664 * @see cm_info::get_formatted_content()
1665 * @see cm_info::get_formatted_name()
1667 * This data is also used in other areas of the code.
1668 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1669 * @param object $course (argument not used)
1670 * @return array An array with the following values in this order:
1671 * $content (optional extra content for after link),
1672 * $instancename (text of link)
1674 function get_print_section_cm_text(cm_info $cm, $course) {
1675 debugging('Function get_print_section_cm_text() is deprecated. Please use '.
1676 'cm_info::get_formatted_content() and cm_info::get_formatted_name()',
1677 DEBUG_DEVELOPER);
1678 return array($cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true)),
1679 $cm->get_formatted_name());
1683 * Prints the menus to add activities and resources.
1685 * Deprecated. Please use:
1686 * $courserenderer = $PAGE->get_renderer('core', 'course');
1687 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1688 * array('inblock' => $vertical));
1689 * echo $output; // if $return argument in print_section_add_menus() set to false
1691 * @deprecated since 2.5
1692 * @see core_course_renderer::course_section_add_cm_control()
1694 * @param stdClass $course course object, must be the same as set on the page
1695 * @param int $section relative section number (field course_sections.section)
1696 * @param null|array $modnames (argument ignored) get_module_types_names() is used instead of argument
1697 * @param bool $vertical Vertical orientation
1698 * @param bool $return Return the menus or send them to output
1699 * @param int $sectionreturn The section to link back to
1700 * @return void|string depending on $return
1702 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1703 global $PAGE;
1704 debugging('Function print_section_add_menus() is deprecated. Please use course renderer '.
1705 'function course_section_add_cm_control()', DEBUG_DEVELOPER);
1706 $output = '';
1707 $courserenderer = $PAGE->get_renderer('core', 'course');
1708 $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1709 array('inblock' => $vertical));
1710 if ($return) {
1711 return $output;
1712 } else {
1713 echo $output;
1714 return !empty($output);
1719 * Produces the editing buttons for a module
1721 * Deprecated. Please use:
1722 * $courserenderer = $PAGE->get_renderer('core', 'course');
1723 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
1724 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1726 * @deprecated since 2.5
1727 * @see course_get_cm_edit_actions()
1728 * @see core_course_renderer->course_section_cm_edit_actions()
1730 * @param stdClass $mod The module to produce editing buttons for
1731 * @param bool $absolute_ignored (argument ignored) - all links are absolute
1732 * @param bool $moveselect (argument ignored)
1733 * @param int $indent The current indenting
1734 * @param int $section The section to link back to
1735 * @return string XHTML for the editing buttons
1737 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
1738 global $PAGE;
1739 debugging('Function make_editing_buttons() is deprecated, please see PHPdocs in '.
1740 'lib/deprecatedlib.php on how to replace it', DEBUG_DEVELOPER);
1741 if (!($mod instanceof cm_info)) {
1742 $modinfo = get_fast_modinfo($mod->course);
1743 $mod = $modinfo->get_cm($mod->id);
1745 $actions = course_get_cm_edit_actions($mod, $indent, $section);
1747 $courserenderer = $PAGE->get_renderer('core', 'course');
1748 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
1749 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
1750 // the course page HTML will allow this to be removed.
1751 return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1755 * Prints a section full of activity modules
1757 * Deprecated. Please use:
1758 * $courserenderer = $PAGE->get_renderer('core', 'course');
1759 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
1760 * array('hidecompletion' => $hidecompletion));
1762 * @deprecated since 2.5
1763 * @see core_course_renderer::course_section_cm_list()
1765 * @param stdClass $course The course
1766 * @param stdClass|section_info $section The section object containing properties id and section
1767 * @param array $mods (argument not used)
1768 * @param array $modnamesused (argument not used)
1769 * @param bool $absolute (argument not used)
1770 * @param string $width (argument not used)
1771 * @param bool $hidecompletion Hide completion status
1772 * @param int $sectionreturn The section to return to
1773 * @return void
1775 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1776 global $PAGE;
1777 debugging('Function print_section() is deprecated. Please use course renderer function '.
1778 'course_section_cm_list() instead.', DEBUG_DEVELOPER);
1779 $displayoptions = array('hidecompletion' => $hidecompletion);
1780 $courserenderer = $PAGE->get_renderer('core', 'course');
1781 echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn, $displayoptions);
1785 * Displays the list of courses with user notes
1787 * This function is not used in core. It was replaced by block course_overview
1789 * @deprecated since 2.5
1791 * @param array $courses
1792 * @param array $remote_courses
1794 function print_overview($courses, array $remote_courses=array()) {
1795 global $CFG, $USER, $DB, $OUTPUT;
1796 debugging('Function print_overview() is deprecated. Use block course_overview to display this information', DEBUG_DEVELOPER);
1798 $htmlarray = array();
1799 if ($modules = $DB->get_records('modules')) {
1800 foreach ($modules as $mod) {
1801 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
1802 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
1803 $fname = $mod->name.'_print_overview';
1804 if (function_exists($fname)) {
1805 $fname($courses,$htmlarray);
1810 foreach ($courses as $course) {
1811 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1812 echo $OUTPUT->box_start('coursebox');
1813 $attributes = array('title' => s($fullname));
1814 if (empty($course->visible)) {
1815 $attributes['class'] = 'dimmed';
1817 echo $OUTPUT->heading(html_writer::link(
1818 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
1819 if (array_key_exists($course->id,$htmlarray)) {
1820 foreach ($htmlarray[$course->id] as $modname => $html) {
1821 echo $html;
1824 echo $OUTPUT->box_end();
1827 if (!empty($remote_courses)) {
1828 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
1830 foreach ($remote_courses as $course) {
1831 echo $OUTPUT->box_start('coursebox');
1832 $attributes = array('title' => s($course->fullname));
1833 echo $OUTPUT->heading(html_writer::link(
1834 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
1835 format_string($course->shortname),
1836 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
1837 echo $OUTPUT->box_end();
1842 * This function trawls through the logs looking for
1843 * anything new since the user's last login
1845 * This function was only used to print the content of block recent_activity
1846 * All functionality is moved into class {@link block_recent_activity}
1847 * and renderer {@link block_recent_activity_renderer}
1849 * @deprecated since 2.5
1850 * @param stdClass $course
1852 function print_recent_activity($course) {
1853 // $course is an object
1854 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
1855 debugging('Function print_recent_activity() is deprecated. It is not recommended to'.
1856 ' use it outside of block_recent_activity', DEBUG_DEVELOPER);
1858 $context = context_course::instance($course->id);
1860 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
1862 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
1864 if (!isguestuser()) {
1865 if (!empty($USER->lastcourseaccess[$course->id])) {
1866 if ($USER->lastcourseaccess[$course->id] > $timestart) {
1867 $timestart = $USER->lastcourseaccess[$course->id];
1872 echo '<div class="activitydate">';
1873 echo get_string('activitysince', '', userdate($timestart));
1874 echo '</div>';
1875 echo '<div class="activityhead">';
1877 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
1879 echo "</div>\n";
1881 $content = false;
1883 /// Firstly, have there been any new enrolments?
1885 $users = get_recent_enrolments($course->id, $timestart);
1887 //Accessibility: new users now appear in an <OL> list.
1888 if ($users) {
1889 echo '<div class="newusers">';
1890 echo $OUTPUT->heading(get_string("newusers").':', 3);
1891 $content = true;
1892 echo "<ol class=\"list\">\n";
1893 foreach ($users as $user) {
1894 $fullname = fullname($user, $viewfullnames);
1895 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
1897 echo "</ol>\n</div>\n";
1900 /// Next, have there been any modifications to the course structure?
1902 $modinfo = get_fast_modinfo($course);
1904 $changelist = array();
1906 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
1907 module = 'course' AND
1908 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
1909 array($timestart, $course->id), "id ASC");
1911 if ($logs) {
1912 $actions = array('add mod', 'update mod', 'delete mod');
1913 $newgones = array(); // added and later deleted items
1914 foreach ($logs as $key => $log) {
1915 if (!in_array($log->action, $actions)) {
1916 continue;
1918 $info = explode(' ', $log->info);
1920 // note: in most cases I replaced hardcoding of label with use of
1921 // $cm->has_view() but it was not possible to do this here because
1922 // we don't necessarily have the $cm for it
1923 if ($info[0] == 'label') { // Labels are ignored in recent activity
1924 continue;
1927 if (count($info) != 2) {
1928 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
1929 continue;
1932 $modname = $info[0];
1933 $instanceid = $info[1];
1935 if ($log->action == 'delete mod') {
1936 // unfortunately we do not know if the mod was visible
1937 if (!array_key_exists($log->info, $newgones)) {
1938 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
1939 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
1941 } else {
1942 if (!isset($modinfo->instances[$modname][$instanceid])) {
1943 if ($log->action == 'add mod') {
1944 // do not display added and later deleted activities
1945 $newgones[$log->info] = true;
1947 continue;
1949 $cm = $modinfo->instances[$modname][$instanceid];
1950 if (!$cm->uservisible) {
1951 continue;
1954 if ($log->action == 'add mod') {
1955 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
1956 $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>");
1958 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
1959 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
1960 $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>");
1966 if (!empty($changelist)) {
1967 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
1968 $content = true;
1969 foreach ($changelist as $changeinfo => $change) {
1970 echo '<p class="activity">'.$change['text'].'</p>';
1974 /// Now display new things from each module
1976 $usedmodules = array();
1977 foreach($modinfo->cms as $cm) {
1978 if (isset($usedmodules[$cm->modname])) {
1979 continue;
1981 if (!$cm->uservisible) {
1982 continue;
1984 $usedmodules[$cm->modname] = $cm->modname;
1987 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1988 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1989 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1990 $print_recent_activity = $modname.'_print_recent_activity';
1991 if (function_exists($print_recent_activity)) {
1992 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1993 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1995 } else {
1996 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
2000 if (! $content) {
2001 echo '<p class="message">'.get_string('nothingnew').'</p>';
2006 * Delete a course module and any associated data at the course level (events)
2007 * Until 1.5 this function simply marked a deleted flag ... now it
2008 * deletes it completely.
2010 * @deprecated since 2.5
2012 * @param int $id the course module id
2013 * @return boolean true on success, false on failure
2015 function delete_course_module($id) {
2016 debugging('Function delete_course_module() is deprecated. Please use course_delete_module() instead.', DEBUG_DEVELOPER);
2018 global $CFG, $DB;
2020 require_once($CFG->libdir.'/gradelib.php');
2021 require_once($CFG->dirroot.'/blog/lib.php');
2023 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2024 return true;
2026 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2027 //delete events from calendar
2028 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2029 foreach($events as $event) {
2030 delete_event($event->id);
2033 //delete grade items, outcome items and grades attached to modules
2034 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2035 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2036 foreach ($grade_items as $grade_item) {
2037 $grade_item->delete('moddelete');
2040 // Delete completion and availability data; it is better to do this even if the
2041 // features are not turned on, in case they were turned on previously (these will be
2042 // very quick on an empty table)
2043 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2044 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2045 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2047 delete_context(CONTEXT_MODULE, $cm->id);
2048 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2052 * Prints the turn editing on/off button on course/index.php or course/category.php.
2054 * @deprecated since 2.5
2056 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2057 * @return string HTML of the editing button, or empty string, if this user is not allowed
2058 * to see it.
2060 function update_category_button($categoryid = 0) {
2061 global $CFG, $PAGE, $OUTPUT;
2062 debugging('Function update_category_button() is deprecated. Pages to view '.
2063 'and edit courses are now separate and no longer depend on editing mode.',
2064 DEBUG_DEVELOPER);
2066 // Check permissions.
2067 if (!can_edit_in_category($categoryid)) {
2068 return '';
2071 // Work out the appropriate action.
2072 if ($PAGE->user_is_editing()) {
2073 $label = get_string('turneditingoff');
2074 $edit = 'off';
2075 } else {
2076 $label = get_string('turneditingon');
2077 $edit = 'on';
2080 // Generate the button HTML.
2081 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2082 if ($categoryid) {
2083 $options['id'] = $categoryid;
2084 $page = 'category.php';
2085 } else {
2086 $page = 'index.php';
2088 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2092 * This function recursively travels the categories, building up a nice list
2093 * for display. It also makes an array that list all the parents for each
2094 * category.
2096 * For example, if you have a tree of categories like:
2097 * Miscellaneous (id = 1)
2098 * Subcategory (id = 2)
2099 * Sub-subcategory (id = 4)
2100 * Other category (id = 3)
2101 * Then after calling this function you will have
2102 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
2103 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2104 * 3 => 'Other category');
2105 * $parents = array(2 => array(1), 4 => array(1, 2));
2107 * If you specify $requiredcapability, then only categories where the current
2108 * user has that capability will be added to $list, although all categories
2109 * will still be added to $parents, and if you only have $requiredcapability
2110 * in a child category, not the parent, then the child catgegory will still be
2111 * included.
2113 * If you specify the option $excluded, then that category, and all its children,
2114 * are omitted from the tree. This is useful when you are doing something like
2115 * moving categories, where you do not want to allow people to move a category
2116 * to be the child of itself.
2118 * This function is deprecated! For list of categories use
2119 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
2120 * For parents of one particular category use
2121 * coursecat::get($id)->get_parents()
2123 * @deprecated since 2.5
2125 * @param array $list For output, accumulates an array categoryid => full category path name
2126 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
2127 * @param string/array $requiredcapability if given, only categories where the current
2128 * user has this capability will be added to $list. Can also be an array of capabilities,
2129 * in which case they are all required.
2130 * @param integer $excludeid Omit this category and its children from the lists built.
2131 * @param object $category Not used
2132 * @param string $path Not used
2134 function make_categories_list(&$list, &$parents, $requiredcapability = '',
2135 $excludeid = 0, $category = NULL, $path = "") {
2136 global $CFG, $DB;
2137 require_once($CFG->libdir.'/coursecatlib.php');
2139 debugging('Global function make_categories_list() is deprecated. Please use '.
2140 'coursecat::make_categories_list() and coursecat::get_parents()',
2141 DEBUG_DEVELOPER);
2143 // For categories list use just this one function:
2144 if (empty($list)) {
2145 $list = array();
2147 $list += coursecat::make_categories_list($requiredcapability, $excludeid);
2149 // Building the list of all parents of all categories in the system is highly undesirable and hardly ever needed.
2150 // Usually user needs only parents for one particular category, in which case should be used:
2151 // coursecat::get($categoryid)->get_parents()
2152 if (empty($parents)) {
2153 $parents = array();
2155 $all = $DB->get_records_sql('SELECT id, parent FROM {course_categories} ORDER BY sortorder');
2156 foreach ($all as $record) {
2157 if ($record->parent) {
2158 $parents[$record->id] = array_merge($parents[$record->parent], array($record->parent));
2159 } else {
2160 $parents[$record->id] = array();
2166 * Delete category, but move contents to another category.
2168 * This function is deprecated. Please use
2169 * coursecat::get($category->id)->delete_move($newparentid, $showfeedback);
2171 * @see coursecat::delete_move()
2172 * @deprecated since 2.5
2174 * @param object $category
2175 * @param int $newparentid category id
2176 * @return bool status
2178 function category_delete_move($category, $newparentid, $showfeedback=true) {
2179 global $CFG;
2180 require_once($CFG->libdir.'/coursecatlib.php');
2182 debugging('Function category_delete_move() is deprecated. Please use coursecat::delete_move() instead.');
2184 return coursecat::get($category->id)->delete_move($newparentid, $showfeedback);
2188 * Recursively delete category including all subcategories and courses.
2190 * This function is deprecated. Please use
2191 * coursecat::get($category->id)->delete_full($showfeedback);
2193 * @see coursecat::delete_full()
2194 * @deprecated since 2.5
2196 * @param stdClass $category
2197 * @param boolean $showfeedback display some notices
2198 * @return array return deleted courses
2200 function category_delete_full($category, $showfeedback=true) {
2201 global $CFG, $DB;
2202 require_once($CFG->libdir.'/coursecatlib.php');
2204 debugging('Function category_delete_full() is deprecated. Please use coursecat::delete_full() instead.');
2206 return coursecat::get($category->id)->delete_full($showfeedback);
2210 * Efficiently moves a category - NOTE that this can have
2211 * a huge impact access-control-wise...
2213 * This function is deprecated. Please use
2214 * $coursecat = coursecat::get($category->id);
2215 * if ($coursecat->can_change_parent($newparentcat->id)) {
2216 * $coursecat->change_parent($newparentcat->id);
2219 * Alternatively you can use
2220 * $coursecat->update(array('parent' => $newparentcat->id));
2222 * Function update() also updates field course_categories.timemodified
2224 * @see coursecat::change_parent()
2225 * @see coursecat::update()
2226 * @deprecated since 2.5
2228 * @param stdClass|coursecat $category
2229 * @param stdClass|coursecat $newparentcat
2231 function move_category($category, $newparentcat) {
2232 global $CFG;
2233 require_once($CFG->libdir.'/coursecatlib.php');
2235 debugging('Function move_category() is deprecated. Please use coursecat::change_parent() instead.');
2237 return coursecat::get($category->id)->change_parent($newparentcat->id);
2241 * Hide course category and child course and subcategories
2243 * This function is deprecated. Please use
2244 * coursecat::get($category->id)->hide();
2246 * @see coursecat::hide()
2247 * @deprecated since 2.5
2249 * @param stdClass $category
2250 * @return void
2252 function course_category_hide($category) {
2253 global $CFG;
2254 require_once($CFG->libdir.'/coursecatlib.php');
2256 debugging('Function course_category_hide() is deprecated. Please use coursecat::hide() instead.');
2258 coursecat::get($category->id)->hide();
2262 * Show course category and child course and subcategories
2264 * This function is deprecated. Please use
2265 * coursecat::get($category->id)->show();
2267 * @see coursecat::show()
2268 * @deprecated since 2.5
2270 * @param stdClass $category
2271 * @return void
2273 function course_category_show($category) {
2274 global $CFG;
2275 require_once($CFG->libdir.'/coursecatlib.php');
2277 debugging('Function course_category_show() is deprecated. Please use coursecat::show() instead.');
2279 coursecat::get($category->id)->show();
2283 * Return specified category, default if given does not exist
2285 * This function is deprecated.
2286 * To get the category with the specified it please use:
2287 * coursecat::get($catid, IGNORE_MISSING);
2288 * or
2289 * coursecat::get($catid, MUST_EXIST);
2291 * To get the first available category please use
2292 * coursecat::get_default();
2294 * class coursecat will also make sure that at least one category exists in DB
2296 * @deprecated since 2.5
2297 * @see coursecat::get()
2298 * @see coursecat::get_default()
2300 * @param int $catid course category id
2301 * @return object caregory
2303 function get_course_category($catid=0) {
2304 global $DB;
2306 debugging('Function get_course_category() is deprecated. Please use coursecat::get(), see phpdocs for more details');
2308 $category = false;
2310 if (!empty($catid)) {
2311 $category = $DB->get_record('course_categories', array('id'=>$catid));
2314 if (!$category) {
2315 // the first category is considered default for now
2316 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
2317 $category = reset($category);
2319 } else {
2320 $cat = new stdClass();
2321 $cat->name = get_string('miscellaneous');
2322 $cat->depth = 1;
2323 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
2324 $cat->timemodified = time();
2325 $catid = $DB->insert_record('course_categories', $cat);
2326 // make sure category context exists
2327 context_coursecat::instance($catid);
2328 mark_context_dirty('/'.SYSCONTEXTID);
2329 fix_course_sortorder(); // Required to build course_categories.depth and .path.
2330 $category = $DB->get_record('course_categories', array('id'=>$catid));
2334 return $category;
2338 * Create a new course category and marks the context as dirty
2340 * This function does not set the sortorder for the new category and
2341 * {@link fix_course_sortorder()} should be called after creating a new course
2342 * category
2344 * Please note that this function does not verify access control.
2346 * This function is deprecated. It is replaced with the method create() in class coursecat.
2347 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
2349 * @deprecated since 2.5
2351 * @param object $category All of the data required for an entry in the course_categories table
2352 * @return object new course category
2354 function create_course_category($category) {
2355 global $DB;
2357 debugging('Function create_course_category() is deprecated. Please use coursecat::create(), see phpdocs for more details', DEBUG_DEVELOPER);
2359 $category->timemodified = time();
2360 $category->id = $DB->insert_record('course_categories', $category);
2361 $category = $DB->get_record('course_categories', array('id' => $category->id));
2363 // We should mark the context as dirty
2364 $category->context = context_coursecat::instance($category->id);
2365 $category->context->mark_dirty();
2367 return $category;
2371 * Returns an array of category ids of all the subcategories for a given
2372 * category.
2374 * This function is deprecated.
2376 * To get visible children categories of the given category use:
2377 * coursecat::get($categoryid)->get_children();
2378 * This function will return the array or coursecat objects, on each of them
2379 * you can call get_children() again
2381 * @see coursecat::get()
2382 * @see coursecat::get_children()
2384 * @deprecated since 2.5
2386 * @global object
2387 * @param int $catid - The id of the category whose subcategories we want to find.
2388 * @return array of category ids.
2390 function get_all_subcategories($catid) {
2391 global $DB;
2393 debugging('Function get_all_subcategories() is deprecated. Please use appropriate methods() of coursecat class. See phpdocs for more details',
2394 DEBUG_DEVELOPER);
2396 $subcats = array();
2398 if ($categories = $DB->get_records('course_categories', array('parent' => $catid))) {
2399 foreach ($categories as $cat) {
2400 array_push($subcats, $cat->id);
2401 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
2404 return $subcats;
2408 * Gets the child categories of a given courses category
2410 * This function is deprecated. Please use functions in class coursecat:
2411 * - coursecat::get($parentid)->has_children()
2412 * tells if the category has children (visible or not to the current user)
2414 * - coursecat::get($parentid)->get_children()
2415 * returns an array of coursecat objects, each of them represents a children category visible
2416 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
2418 * - coursecat::get($parentid)->get_children_count()
2419 * returns number of children categories visible to the current user
2421 * - coursecat::count_all()
2422 * returns total count of all categories in the system (both visible and not)
2424 * - coursecat::get_default()
2425 * returns the first category (usually to be used if count_all() == 1)
2427 * @deprecated since 2.5
2429 * @param int $parentid the id of a course category.
2430 * @return array all the child course categories.
2432 function get_child_categories($parentid) {
2433 global $DB;
2434 debugging('Function get_child_categories() is deprecated. Use coursecat::get_children() or see phpdocs for more details.',
2435 DEBUG_DEVELOPER);
2437 $rv = array();
2438 $sql = context_helper::get_preload_record_columns_sql('ctx');
2439 $records = $DB->get_records_sql("SELECT c.*, $sql FROM {course_categories} c ".
2440 "JOIN {context} ctx on ctx.instanceid = c.id AND ctx.contextlevel = ? WHERE c.parent = ? ORDER BY c.sortorder",
2441 array(CONTEXT_COURSECAT, $parentid));
2442 foreach ($records as $category) {
2443 context_helper::preload_from_record($category);
2444 if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($category->id))) {
2445 continue;
2447 $rv[] = $category;
2449 return $rv;
2453 * Returns a sorted list of categories.
2455 * When asking for $parent='none' it will return all the categories, regardless
2456 * of depth. Wheen asking for a specific parent, the default is to return
2457 * a "shallow" resultset. Pass false to $shallow and it will return all
2458 * the child categories as well.
2460 * @deprecated since 2.5
2462 * This function is deprecated. Use appropriate functions from class coursecat.
2463 * Examples:
2465 * coursecat::get($categoryid)->get_children()
2466 * - returns all children of the specified category as instances of class
2467 * coursecat, which means on each of them method get_children() can be called again.
2468 * Only categories visible to the current user are returned.
2470 * coursecat::get(0)->get_children()
2471 * - returns all top-level categories visible to the current user.
2473 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
2475 * coursecat::make_categories_list()
2476 * - returns an array of all categories id/names in the system.
2477 * Also only returns categories visible to current user and can additionally be
2478 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
2480 * make_categories_options()
2481 * - Returns full course categories tree to be used in html_writer::select()
2483 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
2484 * {@link coursecat::get_default()}
2486 * The code of this deprecated function is left as it is because coursecat::get_children()
2487 * returns categories as instances of coursecat and not stdClass. Also there is no
2488 * substitute for retrieving the category with all it's subcategories. Plugin developers
2489 * may re-use the code/queries from this function in their plugins if really necessary.
2491 * @param string $parent The parent category if any
2492 * @param string $sort the sortorder
2493 * @param bool $shallow - set to false to get the children too
2494 * @return array of categories
2496 function get_categories($parent='none', $sort=NULL, $shallow=true) {
2497 global $DB;
2499 debugging('Function get_categories() is deprecated. Please use coursecat::get_children() or see phpdocs for other alternatives',
2500 DEBUG_DEVELOPER);
2502 if ($sort === NULL) {
2503 $sort = 'ORDER BY cc.sortorder ASC';
2504 } elseif ($sort ==='') {
2505 // leave it as empty
2506 } else {
2507 $sort = "ORDER BY $sort";
2510 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
2512 if ($parent === 'none') {
2513 $sql = "SELECT cc.* $ccselect
2514 FROM {course_categories} cc
2515 $ccjoin
2516 $sort";
2517 $params = array();
2519 } elseif ($shallow) {
2520 $sql = "SELECT cc.* $ccselect
2521 FROM {course_categories} cc
2522 $ccjoin
2523 WHERE cc.parent=?
2524 $sort";
2525 $params = array($parent);
2527 } else {
2528 $sql = "SELECT cc.* $ccselect
2529 FROM {course_categories} cc
2530 $ccjoin
2531 JOIN {course_categories} ccp
2532 ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
2533 WHERE ccp.id=?
2534 $sort";
2535 $params = array($parent);
2537 $categories = array();
2539 $rs = $DB->get_recordset_sql($sql, $params);
2540 foreach($rs as $cat) {
2541 context_helper::preload_from_record($cat);
2542 $catcontext = context_coursecat::instance($cat->id);
2543 if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
2544 $categories[$cat->id] = $cat;
2547 $rs->close();
2548 return $categories;
2552 * Displays a course search form
2554 * This function is deprecated, please use course renderer:
2555 * $renderer = $PAGE->get_renderer('core', 'course');
2556 * echo $renderer->course_search_form($value, $format);
2558 * @deprecated since 2.5
2560 * @param string $value default value to populate the search field
2561 * @param bool $return if true returns the value, if false - outputs
2562 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
2563 * @return null|string
2565 function print_course_search($value="", $return=false, $format="plain") {
2566 global $PAGE;
2567 debugging('Function print_course_search() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2568 $renderer = $PAGE->get_renderer('core', 'course');
2569 if ($return) {
2570 return $renderer->course_search_form($value, $format);
2571 } else {
2572 echo $renderer->course_search_form($value, $format);
2577 * Prints custom user information on the home page
2579 * This function is deprecated, please use:
2580 * $renderer = $PAGE->get_renderer('core', 'course');
2581 * echo $renderer->frontpage_my_courses()
2583 * @deprecated since 2.5
2585 function print_my_moodle() {
2586 global $PAGE;
2587 debugging('Function print_my_moodle() is deprecated, please use course renderer function frontpage_my_courses()', DEBUG_DEVELOPER);
2589 $renderer = $PAGE->get_renderer('core', 'course');
2590 echo $renderer->frontpage_my_courses();
2594 * Prints information about one remote course
2596 * This function is deprecated, it is replaced with protected function
2597 * {@link core_course_renderer::frontpage_remote_course()}
2598 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
2600 * @deprecated since 2.5
2602 function print_remote_course($course, $width="100%") {
2603 global $CFG, $USER;
2604 debugging('Function print_remote_course() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2606 $linkcss = '';
2608 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2610 echo '<div class="coursebox remotecoursebox clearfix">';
2611 echo '<div class="info">';
2612 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2613 $linkcss.' href="'.$url.'">'
2614 . format_string($course->fullname) .'</a><br />'
2615 . format_string($course->hostname) . ' : '
2616 . format_string($course->cat_name) . ' : '
2617 . format_string($course->shortname). '</div>';
2618 echo '</div><div class="summary">';
2619 $options = new stdClass();
2620 $options->noclean = true;
2621 $options->para = false;
2622 $options->overflowdiv = true;
2623 echo format_text($course->summary, $course->summaryformat, $options);
2624 echo '</div>';
2625 echo '</div>';
2629 * Prints information about one remote host
2631 * This function is deprecated, it is replaced with protected function
2632 * {@link core_course_renderer::frontpage_remote_host()}
2633 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
2635 * @deprecated since 2.5
2637 function print_remote_host($host, $width="100%") {
2638 global $OUTPUT;
2639 debugging('Function print_remote_host() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2641 $linkcss = '';
2643 echo '<div class="coursebox clearfix">';
2644 echo '<div class="info">';
2645 echo '<div class="name">';
2646 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2647 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2648 . s($host['name']).'</a> - ';
2649 echo $host['count'] . ' ' . get_string('courses');
2650 echo '</div>';
2651 echo '</div>';
2652 echo '</div>';
2656 * Recursive function to print out all the categories in a nice format
2657 * with or without courses included
2659 * @deprecated since 2.5
2661 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
2663 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
2664 global $PAGE;
2665 debugging('Function print_whole_category_list() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2667 $renderer = $PAGE->get_renderer('core', 'course');
2668 if ($showcourses && $category) {
2669 echo $renderer->course_category($category);
2670 } else if ($showcourses) {
2671 echo $renderer->frontpage_combo_list();
2672 } else {
2673 echo $renderer->frontpage_categories_list();
2678 * Prints the category information.
2680 * @deprecated since 2.5
2682 * This function was only used by {@link print_whole_category_list()} but now
2683 * all course category rendering is moved to core_course_renderer.
2685 * @param stdClass $category
2686 * @param int $depth The depth of the category.
2687 * @param bool $showcourses If set to true course information will also be printed.
2688 * @param array|null $courses An array of courses belonging to the category, or null if you don't have it yet.
2690 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
2691 global $PAGE;
2692 debugging('Function print_category_info() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2694 $renderer = $PAGE->get_renderer('core', 'course');
2695 echo $renderer->course_category($category);
2699 * This function generates a structured array of courses and categories.
2701 * @deprecated since 2.5
2703 * This function is not used any more in moodle core and course renderer does not have render function for it.
2704 * Combo list on the front page is displayed as:
2705 * $renderer = $PAGE->get_renderer('core', 'course');
2706 * echo $renderer->frontpage_combo_list()
2708 * The new class {@link coursecat} stores the information about course category tree
2709 * To get children categories use:
2710 * coursecat::get($id)->get_children()
2711 * To get list of courses use:
2712 * coursecat::get($id)->get_courses()
2714 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
2716 * @param int $id
2717 * @param int $depth
2719 function get_course_category_tree($id = 0, $depth = 0) {
2720 global $DB, $CFG;
2721 if (!$depth) {
2722 debugging('Function get_course_category_tree() is deprecated, please use course renderer or coursecat class, see function phpdocs for more info', DEBUG_DEVELOPER);
2725 $categories = array();
2726 $categoryids = array();
2727 $sql = context_helper::get_preload_record_columns_sql('ctx');
2728 $records = $DB->get_records_sql("SELECT c.*, $sql FROM {course_categories} c ".
2729 "JOIN {context} ctx on ctx.instanceid = c.id AND ctx.contextlevel = ? WHERE c.parent = ? ORDER BY c.sortorder",
2730 array(CONTEXT_COURSECAT, $id));
2731 foreach ($records as $category) {
2732 context_helper::preload_from_record($category);
2733 if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($category->id))) {
2734 continue;
2736 $categories[] = $category;
2737 $categoryids[$category->id] = $category;
2738 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2739 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2740 foreach ($subcategories as $subid=>$subcat) {
2741 $categoryids[$subid] = $subcat;
2743 $category->courses = array();
2747 if ($depth > 0) {
2748 // This is a recursive call so return the required array
2749 return array($categories, $categoryids);
2752 if (empty($categoryids)) {
2753 // No categories available (probably all hidden).
2754 return array();
2757 // The depth is 0 this function has just been called so we can finish it off
2759 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2760 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2761 $sql = "SELECT
2762 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2763 $ccselect
2764 FROM {course} c
2765 $ccjoin
2766 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2767 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2768 // loop throught them
2769 foreach ($courses as $course) {
2770 if ($course->id == SITEID) {
2771 continue;
2773 context_helper::preload_from_record($course);
2774 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
2775 $categoryids[$course->category]->courses[$course->id] = $course;
2779 return $categories;
2783 * Print courses in category. If category is 0 then all courses are printed.
2785 * @deprecated since 2.5
2787 * To print a generic list of courses use:
2788 * $renderer = $PAGE->get_renderer('core', 'course');
2789 * echo $renderer->courses_list($courses);
2791 * To print list of all courses:
2792 * $renderer = $PAGE->get_renderer('core', 'course');
2793 * echo $renderer->frontpage_available_courses();
2795 * To print list of courses inside category:
2796 * $renderer = $PAGE->get_renderer('core', 'course');
2797 * echo $renderer->course_category($category); // this will also print subcategories
2799 * @param int|stdClass $category category object or id.
2800 * @return bool true if courses found and printed, else false.
2802 function print_courses($category) {
2803 global $CFG, $OUTPUT, $PAGE;
2804 require_once($CFG->libdir. '/coursecatlib.php');
2805 debugging('Function print_courses() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2807 if (!is_object($category) && $category==0) {
2808 $courses = coursecat::get(0)->get_courses(array('recursive' => true, 'summary' => true, 'coursecontacts' => true));
2809 } else {
2810 $courses = coursecat::get($category->id)->get_courses(array('summary' => true, 'coursecontacts' => true));
2813 if ($courses) {
2814 $renderer = $PAGE->get_renderer('core', 'course');
2815 echo $renderer->courses_list($courses);
2816 } else {
2817 echo $OUTPUT->heading(get_string("nocoursesyet"));
2818 $context = context_system::instance();
2819 if (has_capability('moodle/course:create', $context)) {
2820 $options = array();
2821 if (!empty($category->id)) {
2822 $options['category'] = $category->id;
2823 } else {
2824 $options['category'] = $CFG->defaultrequestcategory;
2826 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2827 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2828 echo html_writer::end_tag('div');
2829 return false;
2832 return true;
2836 * Print a description of a course, suitable for browsing in a list.
2838 * @deprecated since 2.5
2840 * Please use course renderer to display a course information box.
2841 * $renderer = $PAGE->get_renderer('core', 'course');
2842 * echo $renderer->courses_list($courses); // will print list of courses
2843 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
2845 * @param object $course the course object.
2846 * @param string $highlightterms Ignored in this deprecated function!
2848 function print_course($course, $highlightterms = '') {
2849 global $PAGE;
2851 debugging('Function print_course() is deprecated, please use course renderer', DEBUG_DEVELOPER);
2852 $renderer = $PAGE->get_renderer('core', 'course');
2853 // Please note, correct would be to use $renderer->coursecat_coursebox() but this function is protected.
2854 // To print list of courses use $renderer->courses_list();
2855 echo $renderer->course_info_box($course);
2859 * Gets an array whose keys are category ids and whose values are arrays of courses in the corresponding category.
2861 * @deprecated since 2.5
2863 * This function is not used any more in moodle core and course renderer does not have render function for it.
2864 * Combo list on the front page is displayed as:
2865 * $renderer = $PAGE->get_renderer('core', 'course');
2866 * echo $renderer->frontpage_combo_list()
2868 * The new class {@link coursecat} stores the information about course category tree
2869 * To get children categories use:
2870 * coursecat::get($id)->get_children()
2871 * To get list of courses use:
2872 * coursecat::get($id)->get_courses()
2874 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
2876 * @param int $categoryid
2877 * @return array
2879 function get_category_courses_array($categoryid = 0) {
2880 debugging('Function get_category_courses_array() is deprecated, please use methods of coursecat class', DEBUG_DEVELOPER);
2881 $tree = get_course_category_tree($categoryid);
2882 $flattened = array();
2883 foreach ($tree as $category) {
2884 get_category_courses_array_recursively($flattened, $category);
2886 return $flattened;
2890 * Recursive function to help flatten the course category tree.
2892 * @deprecated since 2.5
2894 * Was intended to be called from {@link get_category_courses_array()}
2896 * @param array &$flattened An array passed by reference in which to store courses for each category.
2897 * @param stdClass $category The category to get courses for.
2899 function get_category_courses_array_recursively(array &$flattened, $category) {
2900 debugging('Function get_category_courses_array_recursively() is deprecated, please use methods of coursecat class', DEBUG_DEVELOPER);
2901 $flattened[$category->id] = $category->courses;
2902 foreach ($category->categories as $childcategory) {
2903 get_category_courses_array_recursively($flattened, $childcategory);
2908 * Returns a URL based on the context of the current page.
2909 * This URL points to blog/index.php and includes filter parameters appropriate for the current page.
2911 * @param stdclass $context
2912 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
2913 * @todo Remove this in 2.7
2914 * @return string
2916 function blog_get_context_url($context=null) {
2917 global $CFG;
2919 debugging('Function blog_get_context_url() is deprecated, getting params from context is not reliable for blogs.', DEBUG_DEVELOPER);
2920 $viewblogentriesurl = new moodle_url('/blog/index.php');
2922 if (empty($context)) {
2923 global $PAGE;
2924 $context = $PAGE->context;
2927 // Change contextlevel to SYSTEM if viewing the site course
2928 if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
2929 $context = context_system::instance();
2932 $filterparam = '';
2933 $strlevel = '';
2935 switch ($context->contextlevel) {
2936 case CONTEXT_SYSTEM:
2937 case CONTEXT_BLOCK:
2938 case CONTEXT_COURSECAT:
2939 break;
2940 case CONTEXT_COURSE:
2941 $filterparam = 'courseid';
2942 $strlevel = get_string('course');
2943 break;
2944 case CONTEXT_MODULE:
2945 $filterparam = 'modid';
2946 $strlevel = $context->get_context_name();
2947 break;
2948 case CONTEXT_USER:
2949 $filterparam = 'userid';
2950 $strlevel = get_string('user');
2951 break;
2954 if (!empty($filterparam)) {
2955 $viewblogentriesurl->param($filterparam, $context->instanceid);
2958 return $viewblogentriesurl;
2962 * Retrieve course records with the course managers and other related records
2963 * that we need for print_course(). This allows print_courses() to do its job
2964 * in a constant number of DB queries, regardless of the number of courses,
2965 * role assignments, etc.
2967 * The returned array is indexed on c.id, and each course will have
2968 * - $course->managers - array containing RA objects that include a $user obj
2969 * with the minimal fields needed for fullname()
2971 * @deprecated since 2.5
2973 * To get list of all courses with course contacts ('managers') use
2974 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
2976 * To get list of courses inside particular category use
2977 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
2979 * Additionally you can specify sort order, offset and maximum number of courses,
2980 * see {@link coursecat::get_courses()}
2982 * Please note that code of this function is not changed to use coursecat class because
2983 * coursecat::get_courses() returns result in slightly different format. Also note that
2984 * get_courses_wmanagers() DOES NOT check that users are enrolled in the course and
2985 * coursecat::get_courses() does.
2987 * @global object
2988 * @global object
2989 * @global object
2990 * @uses CONTEXT_COURSE
2991 * @uses CONTEXT_SYSTEM
2992 * @uses CONTEXT_COURSECAT
2993 * @uses SITEID
2994 * @param int|string $categoryid Either the categoryid for the courses or 'all'
2995 * @param string $sort A SQL sort field and direction
2996 * @param array $fields An array of additional fields to fetch
2997 * @return array
2999 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
3001 * The plan is to
3003 * - Grab the courses JOINed w/context
3005 * - Grab the interesting course-manager RAs
3006 * JOINed with a base user obj and add them to each course
3008 * So as to do all the work in 2 DB queries. The RA+user JOIN
3009 * ends up being pretty expensive if it happens over _all_
3010 * courses on a large site. (Are we surprised!?)
3012 * So this should _never_ get called with 'all' on a large site.
3015 global $USER, $CFG, $DB;
3016 debugging('Function get_courses_wmanagers() is deprecated, please use coursecat::get_courses()', DEBUG_DEVELOPER);
3018 $params = array();
3019 $allcats = false; // bool flag
3020 if ($categoryid === 'all') {
3021 $categoryclause = '';
3022 $allcats = true;
3023 } elseif (is_numeric($categoryid)) {
3024 $categoryclause = "c.category = :catid";
3025 $params['catid'] = $categoryid;
3026 } else {
3027 debugging("Could not recognise categoryid = $categoryid");
3028 $categoryclause = '';
3031 $basefields = array('id', 'category', 'sortorder',
3032 'shortname', 'fullname', 'idnumber',
3033 'startdate', 'visible',
3034 'newsitems', 'groupmode', 'groupmodeforce');
3036 if (!is_null($fields) && is_string($fields)) {
3037 if (empty($fields)) {
3038 $fields = $basefields;
3039 } else {
3040 // turn the fields from a string to an array that
3041 // get_user_courses_bycap() will like...
3042 $fields = explode(',',$fields);
3043 $fields = array_map('trim', $fields);
3044 $fields = array_unique(array_merge($basefields, $fields));
3046 } elseif (is_array($fields)) {
3047 $fields = array_merge($basefields,$fields);
3049 $coursefields = 'c.' .join(',c.', $fields);
3051 if (empty($sort)) {
3052 $sortstatement = "";
3053 } else {
3054 $sortstatement = "ORDER BY $sort";
3057 $where = 'WHERE c.id != ' . SITEID;
3058 if ($categoryclause !== ''){
3059 $where = "$where AND $categoryclause";
3062 // pull out all courses matching the cat
3063 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
3064 $sql = "SELECT $coursefields $ccselect
3065 FROM {course} c
3066 $ccjoin
3067 $where
3068 $sortstatement";
3070 $catpaths = array();
3071 $catpath = NULL;
3072 if ($courses = $DB->get_records_sql($sql, $params)) {
3073 // loop on courses materialising
3074 // the context, and prepping data to fetch the
3075 // managers efficiently later...
3076 foreach ($courses as $k => $course) {
3077 context_helper::preload_from_record($course);
3078 $coursecontext = context_course::instance($course->id);
3079 $courses[$k] = $course;
3080 $courses[$k]->managers = array();
3081 if ($allcats === false) {
3082 // single cat, so take just the first one...
3083 if ($catpath === NULL) {
3084 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
3086 } else {
3087 // chop off the contextid of the course itself
3088 // like dirname() does...
3089 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
3092 } else {
3093 return array(); // no courses!
3096 $CFG->coursecontact = trim($CFG->coursecontact);
3097 if (empty($CFG->coursecontact)) {
3098 return $courses;
3101 $managerroles = explode(',', $CFG->coursecontact);
3102 $catctxids = '';
3103 if (count($managerroles)) {
3104 if ($allcats === true) {
3105 $catpaths = array_unique($catpaths);
3106 $ctxids = array();
3107 foreach ($catpaths as $cpath) {
3108 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
3110 $ctxids = array_unique($ctxids);
3111 $catctxids = implode( ',' , $ctxids);
3112 unset($catpaths);
3113 unset($cpath);
3114 } else {
3115 // take the ctx path from the first course
3116 // as all categories will be the same...
3117 $catpath = substr($catpath,1);
3118 $catpath = preg_replace(':/\d+$:','',$catpath);
3119 $catctxids = str_replace('/',',',$catpath);
3121 if ($categoryclause !== '') {
3122 $categoryclause = "AND $categoryclause";
3125 * Note: Here we use a LEFT OUTER JOIN that can
3126 * "optionally" match to avoid passing a ton of context
3127 * ids in an IN() clause. Perhaps a subselect is faster.
3129 * In any case, this SQL is not-so-nice over large sets of
3130 * courses with no $categoryclause.
3133 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
3134 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
3135 rn.name AS rolecoursealias, u.id AS userid, u.firstname, u.lastname
3136 FROM {role_assignments} ra
3137 JOIN {context} ctx ON ra.contextid = ctx.id
3138 JOIN {user} u ON ra.userid = u.id
3139 JOIN {role} r ON ra.roleid = r.id
3140 LEFT JOIN {role_names} rn ON (rn.contextid = ctx.id AND rn.roleid = r.id)
3141 LEFT OUTER JOIN {course} c
3142 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
3143 WHERE ( c.id IS NOT NULL";
3144 // under certain conditions, $catctxids is NULL
3145 if($catctxids == NULL){
3146 $sql .= ") ";
3147 }else{
3148 $sql .= " OR ra.contextid IN ($catctxids) )";
3151 $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
3152 $categoryclause
3153 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
3154 $rs = $DB->get_recordset_sql($sql, $params);
3156 // This loop is fairly stupid as it stands - might get better
3157 // results doing an initial pass clustering RAs by path.
3158 foreach($rs as $ra) {
3159 $user = new stdClass;
3160 $user->id = $ra->userid; unset($ra->userid);
3161 $user->firstname = $ra->firstname; unset($ra->firstname);
3162 $user->lastname = $ra->lastname; unset($ra->lastname);
3163 $ra->user = $user;
3164 if ($ra->contextlevel == CONTEXT_SYSTEM) {
3165 foreach ($courses as $k => $course) {
3166 $courses[$k]->managers[] = $ra;
3168 } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
3169 if ($allcats === false) {
3170 // It always applies
3171 foreach ($courses as $k => $course) {
3172 $courses[$k]->managers[] = $ra;
3174 } else {
3175 foreach ($courses as $k => $course) {
3176 $coursecontext = context_course::instance($course->id);
3177 // Note that strpos() returns 0 as "matched at pos 0"
3178 if (strpos($coursecontext->path, $ra->path.'/') === 0) {
3179 // Only add it to subpaths
3180 $courses[$k]->managers[] = $ra;
3184 } else { // course-level
3185 if (!array_key_exists($ra->instanceid, $courses)) {
3186 //this course is not in a list, probably a frontpage course
3187 continue;
3189 $courses[$ra->instanceid]->managers[] = $ra;
3192 $rs->close();
3195 return $courses;
3199 * Converts a nested array tree into HTML ul:li [recursive]
3201 * @deprecated since 2.5
3203 * @param array $tree A tree array to convert
3204 * @param int $row Used in identifying the iteration level and in ul classes
3205 * @return string HTML structure
3207 function convert_tree_to_html($tree, $row=0) {
3208 debugging('Function convert_tree_to_html() is deprecated since Moodle 2.5. Consider using class tabtree and core_renderer::render_tabtree()', DEBUG_DEVELOPER);
3210 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
3212 $first = true;
3213 $count = count($tree);
3215 foreach ($tree as $tab) {
3216 $count--; // countdown to zero
3218 $liclass = '';
3220 if ($first && ($count == 0)) { // Just one in the row
3221 $liclass = 'first last';
3222 $first = false;
3223 } else if ($first) {
3224 $liclass = 'first';
3225 $first = false;
3226 } else if ($count == 0) {
3227 $liclass = 'last';
3230 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
3231 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
3234 if ($tab->inactive || $tab->active || $tab->selected) {
3235 if ($tab->selected) {
3236 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
3237 } else if ($tab->active) {
3238 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
3242 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
3244 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
3245 // The a tag is used for styling
3246 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
3247 } else {
3248 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
3251 if (!empty($tab->subtree)) {
3252 $str .= convert_tree_to_html($tab->subtree, $row+1);
3253 } else if ($tab->selected) {
3254 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
3257 $str .= ' </li>'."\n";
3259 $str .= '</ul>'."\n";
3261 return $str;
3265 * Convert nested tabrows to a nested array
3267 * @deprecated since 2.5
3269 * @param array $tabrows A [nested] array of tab row objects
3270 * @param string $selected The tabrow to select (by id)
3271 * @param array $inactive An array of tabrow id's to make inactive
3272 * @param array $activated An array of tabrow id's to make active
3273 * @return array The nested array
3275 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
3277 debugging('Function convert_tabrows_to_tree() is deprecated since Moodle 2.5. Consider using class tabtree', DEBUG_DEVELOPER);
3279 // Work backwards through the rows (bottom to top) collecting the tree as we go.
3280 $tabrows = array_reverse($tabrows);
3282 $subtree = array();
3284 foreach ($tabrows as $row) {
3285 $tree = array();
3287 foreach ($row as $tab) {
3288 $tab->inactive = in_array((string)$tab->id, $inactive);
3289 $tab->active = in_array((string)$tab->id, $activated);
3290 $tab->selected = (string)$tab->id == $selected;
3292 if ($tab->active || $tab->selected) {
3293 if ($subtree) {
3294 $tab->subtree = $subtree;
3297 $tree[] = $tab;
3299 $subtree = $tree;
3302 return $subtree;
3306 * Can handle rotated text. Whether it is safe to use the trickery in textrotate.js.
3308 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
3309 * @return bool True for yes, false for no
3311 function can_use_rotated_text() {
3312 debugging('can_use_rotated_text() is deprecated since Moodle 2.5. JS feature detection is used automatically.', DEBUG_DEVELOPER);
3313 return true;
3317 * Get the context instance as an object. This function will create the
3318 * context instance if it does not exist yet.
3320 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
3321 * @todo This will be deleted in Moodle 2.8, refer MDL-34472
3322 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
3323 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
3324 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
3325 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
3326 * MUST_EXIST means throw exception if no record or multiple records found
3327 * @return context The context object.
3329 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
3331 debugging('get_context_instance() is deprecated, please use context_xxxx::instance() instead.', DEBUG_DEVELOPER);
3333 $instances = (array)$instance;
3334 $contexts = array();
3336 $classname = context_helper::get_class_for_level($contextlevel);
3338 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
3339 foreach ($instances as $inst) {
3340 $contexts[$inst] = $classname::instance($inst, $strictness);
3343 if (is_array($instance)) {
3344 return $contexts;
3345 } else {
3346 return $contexts[$instance];
3351 * Get a context instance as an object, from a given context id.
3353 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
3354 * @see context::instance_by_id($id)
3356 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
3357 throw new coding_exception('get_context_instance_by_id() is now removed, please use context::instance_by_id($id) instead.');
3361 * Returns system context or null if can not be created yet.
3363 * @see context_system::instance()
3364 * @deprecated since 2.2
3365 * @param bool $cache use caching
3366 * @return context system context (null if context table not created yet)
3368 function get_system_context($cache = true) {
3369 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
3370 return context_system::instance(0, IGNORE_MISSING, $cache);
3374 * Recursive function which, given a context, find all parent context ids,
3375 * and return the array in reverse order, i.e. parent first, then grand
3376 * parent, etc.
3378 * @see context::get_parent_context_ids()
3379 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
3380 * @param context $context
3381 * @param bool $includeself optional, defaults to false
3382 * @return array
3384 function get_parent_contexts(context $context, $includeself = false) {
3385 debugging('get_parent_contexts() is deprecated, please use $context->get_parent_context_ids() instead.', DEBUG_DEVELOPER);
3386 return $context->get_parent_context_ids($includeself);
3390 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3391 * is the site context.)
3393 * @deprecated since Moodle 2.2
3394 * @see context::get_parent_context()
3395 * @param context $context
3396 * @return integer the id of the parent context.
3398 function get_parent_contextid(context $context) {
3399 debugging('get_parent_contextid() is deprecated, please use $context->get_parent_context() instead.', DEBUG_DEVELOPER);
3401 if ($parent = $context->get_parent_context()) {
3402 return $parent->id;
3403 } else {
3404 return false;
3409 * Recursive function which, given a context, find all its children contexts.
3411 * For course category contexts it will return immediate children only categories and courses.
3412 * It will NOT recurse into courses or child categories.
3413 * If you want to do that, call it on the returned courses/categories.
3415 * When called for a course context, it will return the modules and blocks
3416 * displayed in the course page.
3418 * If called on a user/course/module context it _will_ populate the cache with the appropriate
3419 * contexts ;-)
3421 * @see context::get_child_contexts()
3422 * @deprecated since 2.2
3423 * @param context $context
3424 * @return array Array of child records
3426 function get_child_contexts(context $context) {
3427 debugging('get_child_contexts() is deprecated, please use $context->get_child_contexts() instead.', DEBUG_DEVELOPER);
3428 return $context->get_child_contexts();
3432 * Precreates all contexts including all parents.
3434 * @see context_helper::create_instances()
3435 * @deprecated since 2.2
3436 * @param int $contextlevel empty means all
3437 * @param bool $buildpaths update paths and depths
3438 * @return void
3440 function create_contexts($contextlevel = null, $buildpaths = true) {
3441 debugging('create_contexts() is deprecated, please use context_helper::create_instances() instead.', DEBUG_DEVELOPER);
3442 context_helper::create_instances($contextlevel, $buildpaths);
3446 * Remove stale context records.
3448 * @see context_helper::cleanup_instances()
3449 * @deprecated since 2.2
3450 * @return bool
3452 function cleanup_contexts() {
3453 debugging('cleanup_contexts() is deprecated, please use context_helper::cleanup_instances() instead.', DEBUG_DEVELOPER);
3454 context_helper::cleanup_instances();
3455 return true;
3459 * Populate context.path and context.depth where missing.
3461 * @see context_helper::build_all_paths()
3462 * @deprecated since 2.2
3463 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
3464 * @return void
3466 function build_context_path($force = false) {
3467 debugging('build_context_path() is deprecated, please use context_helper::build_all_paths() instead.', DEBUG_DEVELOPER);
3468 context_helper::build_all_paths($force);
3472 * Rebuild all related context depth and path caches.
3474 * @see context::reset_paths()
3475 * @deprecated since 2.2
3476 * @param array $fixcontexts array of contexts, strongtyped
3477 * @return void
3479 function rebuild_contexts(array $fixcontexts) {
3480 debugging('rebuild_contexts() is deprecated, please use $context->reset_paths(true) instead.', DEBUG_DEVELOPER);
3481 foreach ($fixcontexts as $fixcontext) {
3482 $fixcontext->reset_paths(false);
3484 context_helper::build_all_paths(false);
3488 * Preloads all contexts relating to a course: course, modules. Block contexts
3489 * are no longer loaded here. The contexts for all the blocks on the current
3490 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
3492 * @deprecated since Moodle 2.2
3493 * @see context_helper::preload_course()
3494 * @param int $courseid Course ID
3495 * @return void
3497 function preload_course_contexts($courseid) {
3498 debugging('preload_course_contexts() is deprecated, please use context_helper::preload_course() instead.', DEBUG_DEVELOPER);
3499 context_helper::preload_course($courseid);
3503 * Update the path field of the context and all dep. subcontexts that follow
3505 * Update the path field of the context and
3506 * all the dependent subcontexts that follow
3507 * the move.
3509 * The most important thing here is to be as
3510 * DB efficient as possible. This op can have a
3511 * massive impact in the DB.
3513 * @deprecated since Moodle 2.2
3514 * @see context::update_moved()
3515 * @param context $context context obj
3516 * @param context $newparent new parent obj
3517 * @return void
3519 function context_moved(context $context, context $newparent) {
3520 debugging('context_moved() is deprecated, please use context::update_moved() instead.', DEBUG_DEVELOPER);
3521 $context->update_moved($newparent);
3525 * Extracts the relevant capabilities given a contextid.
3526 * All case based, example an instance of forum context.
3527 * Will fetch all forum related capabilities, while course contexts
3528 * Will fetch all capabilities
3530 * capabilities
3531 * `name` varchar(150) NOT NULL,
3532 * `captype` varchar(50) NOT NULL,
3533 * `contextlevel` int(10) NOT NULL,
3534 * `component` varchar(100) NOT NULL,
3536 * @see context::get_capabilities()
3537 * @deprecated since 2.2
3538 * @param context $context
3539 * @return array
3541 function fetch_context_capabilities(context $context) {
3542 debugging('fetch_context_capabilities() is deprecated, please use $context->get_capabilities() instead.', DEBUG_DEVELOPER);
3543 return $context->get_capabilities();
3547 * Preloads context information from db record and strips the cached info.
3548 * The db request has to contain both the $join and $select from context_instance_preload_sql()
3550 * @deprecated since 2.2
3551 * @see context_helper::preload_from_record()
3552 * @param stdClass $rec
3553 * @return void (modifies $rec)
3555 function context_instance_preload(stdClass $rec) {
3556 debugging('context_instance_preload() is deprecated, please use context_helper::preload_from_record() instead.', DEBUG_DEVELOPER);
3557 context_helper::preload_from_record($rec);
3561 * Returns context level name
3563 * @deprecated since 2.2
3564 * @see context_helper::get_level_name()
3565 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
3566 * @return string the name for this type of context.
3568 function get_contextlevel_name($contextlevel) {
3569 debugging('get_contextlevel_name() is deprecated, please use context_helper::get_level_name() instead.', DEBUG_DEVELOPER);
3570 return context_helper::get_level_name($contextlevel);
3574 * Prints human readable context identifier.
3576 * @deprecated since 2.2
3577 * @see context::get_context_name()
3578 * @param context $context the context.
3579 * @param boolean $withprefix whether to prefix the name of the context with the
3580 * type of context, e.g. User, Course, Forum, etc.
3581 * @param boolean $short whether to user the short name of the thing. Only applies
3582 * to course contexts
3583 * @return string the human readable context name.
3585 function print_context_name(context $context, $withprefix = true, $short = false) {
3586 debugging('print_context_name() is deprecated, please use $context->get_context_name() instead.', DEBUG_DEVELOPER);
3587 return $context->get_context_name($withprefix, $short);
3591 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
3593 * @deprecated since 2.2, use $context->mark_dirty() instead
3594 * @see context::mark_dirty()
3595 * @param string $path context path
3597 function mark_context_dirty($path) {
3598 global $CFG, $USER, $ACCESSLIB_PRIVATE;
3599 debugging('mark_context_dirty() is deprecated, please use $context->mark_dirty() instead.', DEBUG_DEVELOPER);
3601 if (during_initial_install()) {
3602 return;
3605 // only if it is a non-empty string
3606 if (is_string($path) && $path !== '') {
3607 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
3608 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
3609 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
3610 } else {
3611 if (CLI_SCRIPT) {
3612 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
3613 } else {
3614 if (isset($USER->access['time'])) {
3615 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
3616 } else {
3617 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
3619 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
3626 * Remove a context record and any dependent entries,
3627 * removes context from static context cache too
3629 * @deprecated since Moodle 2.2
3630 * @see context_helper::delete_instance() or context::delete_content()
3631 * @param int $contextlevel
3632 * @param int $instanceid
3633 * @param bool $deleterecord false means keep record for now
3634 * @return bool returns true or throws an exception
3636 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
3637 if ($deleterecord) {
3638 debugging('delete_context() is deprecated, please use context_helper::delete_instance() instead.', DEBUG_DEVELOPER);
3639 context_helper::delete_instance($contextlevel, $instanceid);
3640 } else {
3641 debugging('delete_context() is deprecated, please use $context->delete_content() instead.', DEBUG_DEVELOPER);
3642 $classname = context_helper::get_class_for_level($contextlevel);
3643 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
3644 $context->delete_content();
3648 return true;
3652 * Get a URL for a context, if there is a natural one. For example, for
3653 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
3654 * user profile page.
3656 * @deprecated since 2.2
3657 * @see context::get_url()
3658 * @param context $context the context
3659 * @return moodle_url
3661 function get_context_url(context $context) {
3662 debugging('get_context_url() is deprecated, please use $context->get_url() instead.', DEBUG_DEVELOPER);
3663 return $context->get_url();
3667 * Is this context part of any course? if yes return course context,
3668 * if not return null or throw exception.
3670 * @deprecated since 2.2
3671 * @see context::get_course_context()
3672 * @param context $context
3673 * @return context_course context of the enclosing course, null if not found or exception
3675 function get_course_context(context $context) {
3676 debugging('get_course_context() is deprecated, please use $context->get_course_context(true) instead.', DEBUG_DEVELOPER);
3677 return $context->get_course_context(true);
3681 * Get an array of courses where cap requested is available
3682 * and user is enrolled, this can be relatively slow.
3684 * @deprecated since 2.2
3685 * @see enrol_get_users_courses()
3686 * @param int $userid A user id. By default (null) checks the permissions of the current user.
3687 * @param string $cap - name of the capability
3688 * @param array $accessdata_ignored
3689 * @param bool $doanything_ignored
3690 * @param string $sort - sorting fields - prefix each fieldname with "c."
3691 * @param array $fields - additional fields you are interested in...
3692 * @param int $limit_ignored
3693 * @return array $courses - ordered array of course objects - see notes above
3695 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
3697 debugging('get_user_courses_bycap() is deprecated, please use enrol_get_users_courses() instead.', DEBUG_DEVELOPER);
3698 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
3699 foreach ($courses as $id=>$course) {
3700 $context = context_course::instance($id);
3701 if (!has_capability($cap, $context, $userid)) {
3702 unset($courses[$id]);
3706 return $courses;
3710 * This is really slow!!! do not use above course context level
3712 * @deprecated since Moodle 2.2
3713 * @param int $roleid
3714 * @param context $context
3715 * @return array
3717 function get_role_context_caps($roleid, context $context) {
3718 global $DB;
3719 debugging('get_role_context_caps() is deprecated, it is really slow. Don\'t use it.', DEBUG_DEVELOPER);
3721 // This is really slow!!!! - do not use above course context level.
3722 $result = array();
3723 $result[$context->id] = array();
3725 // First emulate the parent context capabilities merging into context.
3726 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
3727 foreach ($searchcontexts as $cid) {
3728 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
3729 foreach ($capabilities as $cap) {
3730 if (!array_key_exists($cap->capability, $result[$context->id])) {
3731 $result[$context->id][$cap->capability] = 0;
3733 $result[$context->id][$cap->capability] += $cap->permission;
3738 // Now go through the contexts below given context.
3739 $searchcontexts = array_keys($context->get_child_contexts());
3740 foreach ($searchcontexts as $cid) {
3741 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
3742 foreach ($capabilities as $cap) {
3743 if (!array_key_exists($cap->contextid, $result)) {
3744 $result[$cap->contextid] = array();
3746 $result[$cap->contextid][$cap->capability] = $cap->permission;
3751 return $result;
3755 * Returns current course id or false if outside of course based on context parameter.
3757 * @see context::get_course_context()
3758 * @deprecated since 2.2
3759 * @param context $context
3760 * @return int|bool related course id or false
3762 function get_courseid_from_context(context $context) {
3763 debugging('get_courseid_from_context() is deprecated, please use $context->get_course_context(false) instead.', DEBUG_DEVELOPER);
3764 if ($coursecontext = $context->get_course_context(false)) {
3765 return $coursecontext->instanceid;
3766 } else {
3767 return false;
3772 * Preloads context information together with instances.
3773 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
3775 * If you are using this methid, you should have something like this:
3777 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
3779 * To prevent the use of this deprecated function, replace the line above with something similar to this:
3781 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
3783 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
3784 * ^ ^ ^ ^
3785 * $params = array('contextlevel' => CONTEXT_COURSE);
3787 * @see context_helper:;get_preload_record_columns_sql()
3788 * @deprecated since 2.2
3789 * @param string $joinon for example 'u.id'
3790 * @param string $contextlevel context level of instance in $joinon
3791 * @param string $tablealias context table alias
3792 * @return array with two values - select and join part
3794 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
3795 debugging('context_instance_preload_sql() is deprecated, please use context_helper::get_preload_record_columns_sql() instead.', DEBUG_DEVELOPER);
3796 $select = ", " . context_helper::get_preload_record_columns_sql($tablealias);
3797 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
3798 return array($select, $join);
3802 * Gets a string for sql calls, searching for stuff in this context or above.
3804 * @deprecated since 2.2
3805 * @see context::get_parent_context_ids()
3806 * @param context $context
3807 * @return string
3809 function get_related_contexts_string(context $context) {
3810 debugging('get_related_contexts_string() is deprecated, please use $context->get_parent_context_ids(true) instead.', DEBUG_DEVELOPER);
3811 if ($parents = $context->get_parent_context_ids()) {
3812 return (' IN ('.$context->id.','.implode(',', $parents).')');
3813 } else {
3814 return (' ='.$context->id);
3819 * Get a list of all the plugins of a given type that contain a particular file.
3821 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
3822 * @param string $file the name of file that must be present in the plugin.
3823 * (e.g. 'view.php', 'db/install.xml').
3824 * @param bool $include if true (default false), the file will be include_once-ed if found.
3825 * @return array with plugin name as keys (e.g. 'forum', 'courselist') and the path
3826 * to the file relative to dirroot as value (e.g. "$CFG->dirroot/mod/forum/view.php").
3827 * @deprecated since 2.6
3828 * @see core_component::get_plugin_list_with_file()
3830 function get_plugin_list_with_file($plugintype, $file, $include = false) {
3831 debugging('get_plugin_list_with_file() is deprecated, please use core_component::get_plugin_list_with_file() instead.',
3832 DEBUG_DEVELOPER);
3833 return core_component::get_plugin_list_with_file($plugintype, $file, $include);
3837 * Checks to see if is the browser operating system matches the specified brand.
3839 * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
3841 * @deprecated since 2.6
3842 * @param string $brand The operating system identifier being tested
3843 * @return bool true if the given brand below to the detected operating system
3845 function check_browser_operating_system($brand) {
3846 debugging('check_browser_operating_system has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3847 return core_useragent::check_browser_operating_system($brand);
3851 * Checks to see if is a browser matches the specified
3852 * brand and is equal or better version.
3854 * @deprecated since 2.6
3855 * @param string $brand The browser identifier being tested
3856 * @param int $version The version of the browser, if not specified any version (except 5.5 for IE for BC reasons)
3857 * @return bool true if the given version is below that of the detected browser
3859 function check_browser_version($brand, $version = null) {
3860 debugging('check_browser_version has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3861 return core_useragent::check_browser_version($brand, $version);
3865 * Returns whether a device/browser combination is mobile, tablet, legacy, default or the result of
3866 * an optional admin specified regular expression. If enabledevicedetection is set to no or not set
3867 * it returns default
3869 * @deprecated since 2.6
3870 * @return string device type
3872 function get_device_type() {
3873 debugging('get_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3874 return core_useragent::get_device_type();
3878 * Returns a list of the device types supporting by Moodle
3880 * @deprecated since 2.6
3881 * @param boolean $incusertypes includes types specified using the devicedetectregex admin setting
3882 * @return array $types
3884 function get_device_type_list($incusertypes = true) {
3885 debugging('get_device_type_list has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3886 return core_useragent::get_device_type_list($incusertypes);
3890 * Returns the theme selected for a particular device or false if none selected.
3892 * @deprecated since 2.6
3893 * @param string $devicetype
3894 * @return string|false The name of the theme to use for the device or the false if not set
3896 function get_selected_theme_for_device_type($devicetype = null) {
3897 debugging('get_selected_theme_for_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3898 return core_useragent::get_device_type_theme($devicetype);
3902 * Returns the name of the device type theme var in $CFG because there is not a convention to allow backwards compatibility.
3904 * @deprecated since 2.6
3905 * @param string $devicetype
3906 * @return string The config variable to use to determine the theme
3908 function get_device_cfg_var_name($devicetype = null) {
3909 debugging('get_device_cfg_var_name has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3910 return core_useragent::get_device_type_cfg_var_name($devicetype);
3914 * Allows the user to switch the device they are seeing the theme for.
3915 * This allows mobile users to switch back to the default theme, or theme for any other device.
3917 * @deprecated since 2.6
3918 * @param string $newdevice The device the user is currently using.
3919 * @return string The device the user has switched to
3921 function set_user_device_type($newdevice) {
3922 debugging('set_user_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3923 return core_useragent::set_user_device_type($newdevice);
3927 * Returns the device the user is currently using, or if the user has chosen to switch devices
3928 * for the current device type the type they have switched to.
3930 * @deprecated since 2.6
3931 * @return string The device the user is currently using or wishes to use
3933 function get_user_device_type() {
3934 debugging('get_user_device_type has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3935 return core_useragent::get_user_device_type();
3939 * Returns one or several CSS class names that match the user's browser. These can be put
3940 * in the body tag of the page to apply browser-specific rules without relying on CSS hacks
3942 * @deprecated since 2.6
3943 * @return array An array of browser version classes
3945 function get_browser_version_classes() {
3946 debugging('get_browser_version_classes has been deprecated, please update your code to use core_useragent instead.', DEBUG_DEVELOPER);
3947 return core_useragent::get_browser_version_classes();
3951 * Generate a fake user for emails based on support settings
3953 * @deprecated since Moodle 2.6
3954 * @see core_user::get_support_user()
3955 * @return stdClass user info
3957 function generate_email_supportuser() {
3958 debugging('generate_email_supportuser is deprecated, please use core_user::get_support_user');
3959 return core_user::get_support_user();
3963 * Get issued badge details for assertion URL
3965 * @deprecated since Moodle 2.6
3966 * @param string $hash Unique hash of a badge
3967 * @return array Information about issued badge.
3969 function badges_get_issued_badge_info($hash) {
3970 debugging('Function badges_get_issued_badge_info() is deprecated. Please use core_badges_assertion class and methods to generate badge assertion.', DEBUG_DEVELOPER);
3971 $assertion = new core_badges_assertion($hash);
3972 return $assertion->get_badge_assertion();
3976 * Does the user want and can edit using rich text html editor?
3977 * This function does not make sense anymore because a user can directly choose their preferred editor.
3979 * @deprecated since 2.6
3980 * @return bool
3982 function can_use_html_editor() {
3983 debugging('can_use_html_editor has been deprecated please update your code to assume it returns true.', DEBUG_DEVELOPER);
3984 return true;
3989 * Returns an object with counts of failed login attempts.
3991 * @deprecated since Moodle 2.7, use {@link user_count_login_failures()} instead.
3993 function count_login_failures($mode, $username, $lastlogin) {
3994 throw new coding_exception('count_login_failures() can not be used any more, please use user_count_login_failures().');
3998 * It should no longer be required to work without JavaScript enabled.
4000 * @deprecated since 2.7 MDL-33099/MDL-44088 - please do not use this function any more.
4002 function ajaxenabled(array $browsers = null) {
4003 throw new coding_exception('ajaxenabled() can not be used anymore. Update your code to work with JS at all times.');
4007 * Determine whether a course module is visible within a course.
4009 * @deprecated Since Moodle 2.7 MDL-44070
4011 function coursemodule_visible_for_user($cm, $userid=0) {
4012 throw new coding_exception('coursemodule_visible_for_user() can not be used any more,
4013 please use \core_availability\info_module::is_user_visible()');
4017 * Gets all the cohorts the user is able to view.
4019 * @deprecated since Moodle 2.8 MDL-36014, MDL-35618 this functionality is removed
4021 * @param course_enrolment_manager $manager
4022 * @return array
4024 function enrol_cohort_get_cohorts(course_enrolment_manager $manager) {
4025 global $CFG;
4026 debugging('Function enrol_cohort_get_cohorts() is deprecated, use enrol_cohort_search_cohorts() or '.
4027 'cohort_get_available_cohorts() instead', DEBUG_DEVELOPER);
4028 return enrol_cohort_search_cohorts($manager, 0, 0, '');
4032 * Check if cohort exists and user is allowed to enrol it.
4034 * This function is deprecated, use {@link cohort_can_view_cohort()} instead since it also
4035 * takes into account current context
4037 * @deprecated since Moodle 2.8 MDL-36014 please use cohort_can_view_cohort()
4039 * @param int $cohortid Cohort ID
4040 * @return boolean
4042 function enrol_cohort_can_view_cohort($cohortid) {
4043 global $CFG;
4044 require_once($CFG->dirroot . '/cohort/lib.php');
4045 debugging('Function enrol_cohort_can_view_cohort() is deprecated, use cohort_can_view_cohort() instead',
4046 DEBUG_DEVELOPER);
4047 return cohort_can_view_cohort($cohortid, null);
4051 * Returns list of cohorts from course parent contexts.
4053 * Note: this function does not implement any capability checks,
4054 * it means it may disclose existence of cohorts,
4055 * make sure it is displayed to users with appropriate rights only.
4057 * It is advisable to use {@link cohort_get_available_cohorts()} instead.
4059 * @deprecated since Moodle 2.8 MDL-36014 use cohort_get_available_cohorts() instead
4061 * @param stdClass $course
4062 * @param bool $onlyenrolled true means include only cohorts with enrolled users
4063 * @return array of cohort names with number of enrolled users
4065 function cohort_get_visible_list($course, $onlyenrolled=true) {
4066 global $DB;
4068 debugging('Function cohort_get_visible_list() is deprecated. Please use function cohort_get_available_cohorts() ".
4069 "that correctly checks capabilities.', DEBUG_DEVELOPER);
4071 $context = context_course::instance($course->id);
4072 list($esql, $params) = get_enrolled_sql($context);
4073 list($parentsql, $params2) = $DB->get_in_or_equal($context->get_parent_context_ids(), SQL_PARAMS_NAMED);
4074 $params = array_merge($params, $params2);
4076 if ($onlyenrolled) {
4077 $left = "";
4078 $having = "HAVING COUNT(u.id) > 0";
4079 } else {
4080 $left = "LEFT";
4081 $having = "";
4084 $sql = "SELECT c.id, c.name, c.contextid, c.idnumber, c.visible, COUNT(u.id) AS cnt
4085 FROM {cohort} c
4086 $left JOIN ({cohort_members} cm
4087 JOIN ($esql) u ON u.id = cm.userid) ON cm.cohortid = c.id
4088 WHERE c.contextid $parentsql
4089 GROUP BY c.id, c.name, c.contextid, c.idnumber, c.visible
4090 $having
4091 ORDER BY c.name, c.idnumber, c.visible";
4093 $cohorts = $DB->get_records_sql($sql, $params);
4095 foreach ($cohorts as $cid=>$cohort) {
4096 $cohorts[$cid] = format_string($cohort->name, true, array('context'=>$cohort->contextid));
4097 if ($cohort->cnt) {
4098 $cohorts[$cid] .= ' (' . $cohort->cnt . ')';
4102 return $cohorts;
4106 * Enrols all of the users in a cohort through a manual plugin instance.
4108 * In order for this to succeed the course must contain a valid manual
4109 * enrolment plugin instance that the user has permission to enrol users through.
4111 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
4113 * @global moodle_database $DB
4114 * @param course_enrolment_manager $manager
4115 * @param int $cohortid
4116 * @param int $roleid
4117 * @return int
4119 function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohortid, $roleid) {
4120 global $DB;
4121 debugging('enrol_cohort_enrol_all_users() is deprecated. This functionality is moved to enrol_manual.', DEBUG_DEVELOPER);
4123 $context = $manager->get_context();
4124 require_capability('moodle/course:enrolconfig', $context);
4126 $instance = false;
4127 $instances = $manager->get_enrolment_instances();
4128 foreach ($instances as $i) {
4129 if ($i->enrol == 'manual') {
4130 $instance = $i;
4131 break;
4134 $plugin = enrol_get_plugin('manual');
4135 if (!$instance || !$plugin || !$plugin->allow_enrol($instance) || !has_capability('enrol/'.$plugin->get_name().':enrol', $context)) {
4136 return false;
4138 $sql = "SELECT com.userid
4139 FROM {cohort_members} com
4140 LEFT JOIN (
4141 SELECT *
4142 FROM {user_enrolments} ue
4143 WHERE ue.enrolid = :enrolid
4144 ) ue ON ue.userid=com.userid
4145 WHERE com.cohortid = :cohortid AND ue.id IS NULL";
4146 $params = array('cohortid' => $cohortid, 'enrolid' => $instance->id);
4147 $rs = $DB->get_recordset_sql($sql, $params);
4148 $count = 0;
4149 foreach ($rs as $user) {
4150 $count++;
4151 $plugin->enrol_user($instance, $user->userid, $roleid);
4153 $rs->close();
4154 return $count;
4158 * Gets cohorts the user is able to view.
4160 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
4162 * @global moodle_database $DB
4163 * @param course_enrolment_manager $manager
4164 * @param int $offset limit output from
4165 * @param int $limit items to output per load
4166 * @param string $search search string
4167 * @return array Array(more => bool, offset => int, cohorts => array)
4169 function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '') {
4170 global $CFG;
4171 debugging('enrol_cohort_search_cohorts() is deprecated. This functionality is moved to enrol_manual.', DEBUG_DEVELOPER);
4172 require_once($CFG->dirroot . '/cohort/lib.php');
4174 $context = $manager->get_context();
4175 $cohorts = array();
4176 $instances = $manager->get_enrolment_instances();
4177 $enrolled = array();
4178 foreach ($instances as $instance) {
4179 if ($instance->enrol === 'cohort') {
4180 $enrolled[] = $instance->customint1;
4184 $rawcohorts = cohort_get_available_cohorts($context, COHORT_COUNT_MEMBERS, $offset, $limit, $search);
4186 // Produce the output respecting parameters.
4187 foreach ($rawcohorts as $c) {
4188 $cohorts[$c->id] = array(
4189 'cohortid' => $c->id,
4190 'name' => shorten_text(format_string($c->name, true, array('context'=>context::instance_by_id($c->contextid))), 35),
4191 'users' => $c->memberscnt,
4192 'enrolled' => in_array($c->id, $enrolled)
4195 return array('more' => !(bool)$limit, 'offset' => $offset, 'cohorts' => $cohorts);
4199 * Is $USER one of the supplied users?
4201 * $user2 will be null if viewing a user's recent conversations
4203 * @deprecated since Moodle 2.9 MDL-49371 - please do not use this function any more.
4204 * @todo MDL-49290 This will be deleted in Moodle 3.1.
4205 * @param stdClass the first user
4206 * @param stdClass the second user or null
4207 * @return bool True if the current user is one of either $user1 or $user2
4209 function message_current_user_is_involved($user1, $user2) {
4210 global $USER;
4212 debugging('message_current_user_is_involved() is deprecated, please do not use this function.', DEBUG_DEVELOPER);
4214 if (empty($user1->id) || (!empty($user2) && empty($user2->id))) {
4215 throw new coding_exception('Invalid user object detected. Missing id.');
4218 if ($user1->id != $USER->id && (empty($user2) || $user2->id != $USER->id)) {
4219 return false;
4221 return true;
4225 * Print badges on user profile page.
4227 * @deprecated since Moodle 2.9 MDL-45898 - please do not use this function any more.
4228 * @param int $userid User ID.
4229 * @param int $courseid Course if we need to filter badges (optional).
4231 function profile_display_badges($userid, $courseid = 0) {
4232 global $CFG, $PAGE, $USER, $SITE;
4233 require_once($CFG->dirroot . '/badges/renderer.php');
4235 debugging('profile_display_badges() is deprecated.', DEBUG_DEVELOPER);
4237 // Determine context.
4238 if (isloggedin()) {
4239 $context = context_user::instance($USER->id);
4240 } else {
4241 $context = context_system::instance();
4244 if ($USER->id == $userid || has_capability('moodle/badges:viewotherbadges', $context)) {
4245 $records = badges_get_user_badges($userid, $courseid, null, null, null, true);
4246 $renderer = new core_badges_renderer($PAGE, '');
4248 // Print local badges.
4249 if ($records) {
4250 $left = get_string('localbadgesp', 'badges', format_string($SITE->fullname));
4251 $right = $renderer->print_badges_list($records, $userid, true);
4252 echo html_writer::tag('dt', $left);
4253 echo html_writer::tag('dd', $right);
4256 // Print external badges.
4257 if ($courseid == 0 && !empty($CFG->badges_allowexternalbackpack)) {
4258 $backpack = get_backpack_settings($userid);
4259 if (isset($backpack->totalbadges) && $backpack->totalbadges !== 0) {
4260 $left = get_string('externalbadgesp', 'badges');
4261 $right = $renderer->print_badges_list($backpack->badges, $userid, true, true);
4262 echo html_writer::tag('dt', $left);
4263 echo html_writer::tag('dd', $right);
4270 * Adds user preferences elements to user edit form.
4272 * @deprecated since Moodle 2.9 MDL-45774 - Please do not use this function any more.
4273 * @todo MDL-49784 Remove this function in Moodle 3.1
4274 * @param stdClass $user
4275 * @param moodleform $mform
4276 * @param array|null $editoroptions
4277 * @param array|null $filemanageroptions
4279 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
4280 global $CFG;
4282 debugging('useredit_shared_definition_preferences() is deprecated.', DEBUG_DEVELOPER, backtrace);
4284 $choices = array();
4285 $choices['0'] = get_string('emaildisplayno');
4286 $choices['1'] = get_string('emaildisplayyes');
4287 $choices['2'] = get_string('emaildisplaycourse');
4288 $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
4289 $mform->setDefault('maildisplay', $CFG->defaultpreference_maildisplay);
4291 $choices = array();
4292 $choices['0'] = get_string('textformat');
4293 $choices['1'] = get_string('htmlformat');
4294 $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
4295 $mform->setDefault('mailformat', $CFG->defaultpreference_mailformat);
4297 if (!empty($CFG->allowusermailcharset)) {
4298 $choices = array();
4299 $charsets = get_list_of_charsets();
4300 if (!empty($CFG->sitemailcharset)) {
4301 $choices['0'] = get_string('site').' ('.$CFG->sitemailcharset.')';
4302 } else {
4303 $choices['0'] = get_string('site').' (UTF-8)';
4305 $choices = array_merge($choices, $charsets);
4306 $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
4309 $choices = array();
4310 $choices['0'] = get_string('emaildigestoff');
4311 $choices['1'] = get_string('emaildigestcomplete');
4312 $choices['2'] = get_string('emaildigestsubjects');
4313 $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
4314 $mform->setDefault('maildigest', $CFG->defaultpreference_maildigest);
4315 $mform->addHelpButton('maildigest', 'emaildigest');
4317 $choices = array();
4318 $choices['1'] = get_string('autosubscribeyes');
4319 $choices['0'] = get_string('autosubscribeno');
4320 $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
4321 $mform->setDefault('autosubscribe', $CFG->defaultpreference_autosubscribe);
4323 if (!empty($CFG->forum_trackreadposts)) {
4324 $choices = array();
4325 $choices['0'] = get_string('trackforumsno');
4326 $choices['1'] = get_string('trackforumsyes');
4327 $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
4328 $mform->setDefault('trackforums', $CFG->defaultpreference_trackforums);
4331 $editors = editors_get_enabled();
4332 if (count($editors) > 1) {
4333 $choices = array('' => get_string('defaulteditor'));
4334 $firsteditor = '';
4335 foreach (array_keys($editors) as $editor) {
4336 if (!$firsteditor) {
4337 $firsteditor = $editor;
4339 $choices[$editor] = get_string('pluginname', 'editor_' . $editor);
4341 $mform->addElement('select', 'preference_htmleditor', get_string('textediting'), $choices);
4342 $mform->setDefault('preference_htmleditor', '');
4343 } else {
4344 // Empty string means use the first chosen text editor.
4345 $mform->addElement('hidden', 'preference_htmleditor');
4346 $mform->setDefault('preference_htmleditor', '');
4347 $mform->setType('preference_htmleditor', PARAM_PLUGIN);
4350 $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
4351 $mform->setDefault('lang', $CFG->lang);