3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * 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.
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
31 defined('MOODLE_INTERNAL') || die();
34 * List all core subsystems and their location
36 * This is a whitelist of components that are part of the core and their
37 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
38 * plugin is not listed here and it does not have proper plugintype prefix,
39 * then it is considered as course activity module.
41 * The location is optionally dirroot relative path. NULL means there is no special
42 * directory for this subsystem. If the location is set, the subsystem's
43 * renderer.php is expected to be there.
45 * @deprecated since 2.6, use core_component::get_core_subsystems()
47 * @param bool $fullpaths false means relative paths from dirroot, use true for performance reasons
48 * @return array of (string)name => (string|null)location
50 function get_core_subsystems($fullpaths = false) {
53 // NOTE: do not add any other debugging here, keep forever.
55 $subsystems = core_component::get_core_subsystems();
61 debugging('Short paths are deprecated when using get_core_subsystems(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
63 $dlength = strlen($CFG->dirroot);
65 foreach ($subsystems as $k => $v) {
69 $subsystems[$k] = substr($v, $dlength+1);
76 * Lists all plugin types.
78 * @deprecated since 2.6, use core_component::get_plugin_types()
80 * @param bool $fullpaths false means relative paths from dirroot
81 * @return array Array of strings - name=>location
83 function get_plugin_types($fullpaths = true) {
86 // NOTE: do not add any other debugging here, keep forever.
88 $types = core_component::get_plugin_types();
94 debugging('Short paths are deprecated when using get_plugin_types(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
96 $dlength = strlen($CFG->dirroot);
98 foreach ($types as $k => $v) {
100 $types[$k] = 'theme';
103 $types[$k] = substr($v, $dlength+1);
110 * Use when listing real plugins of one type.
112 * @deprecated since 2.6, use core_component::get_plugin_list()
114 * @param string $plugintype type of plugin
115 * @return array name=>fulllocation pairs of plugins of given type
117 function get_plugin_list($plugintype) {
119 // NOTE: do not add any other debugging here, keep forever.
121 if ($plugintype === '') {
125 return core_component::get_plugin_list($plugintype);
129 * Get a list of all the plugins of a given type that define a certain class
130 * in a certain file. The plugin component names and class names are returned.
132 * @deprecated since 2.6, use core_component::get_plugin_list_with_class()
134 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
135 * @param string $class the part of the name of the class after the
136 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
137 * names like report_courselist_thing. If you are looking for classes with
138 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
139 * @param string $file the name of file within the plugin that defines the class.
140 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
141 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
143 function get_plugin_list_with_class($plugintype, $class, $file) {
145 // NOTE: do not add any other debugging here, keep forever.
147 return core_component::get_plugin_list_with_class($plugintype, $class, $file);
151 * Returns the exact absolute path to plugin directory.
153 * @deprecated since 2.6, use core_component::get_plugin_directory()
155 * @param string $plugintype type of plugin
156 * @param string $name name of the plugin
157 * @return string full path to plugin directory; NULL if not found
159 function get_plugin_directory($plugintype, $name) {
161 // NOTE: do not add any other debugging here, keep forever.
163 if ($plugintype === '') {
167 return core_component::get_plugin_directory($plugintype, $name);
171 * Normalize the component name using the "frankenstyle" names.
173 * @deprecated since 2.6, use core_component::normalize_component()
175 * @param string $component
176 * @return array as (string)$type => (string)$plugin
178 function normalize_component($component) {
180 // NOTE: do not add any other debugging here, keep forever.
182 return core_component::normalize_component($component);
186 * Return exact absolute path to a plugin directory.
188 * @deprecated since 2.6, use core_component::normalize_component()
190 * @param string $component name such as 'moodle', 'mod_forum'
191 * @return string full path to component directory; NULL if not found
193 function get_component_directory($component) {
195 // NOTE: do not add any other debugging here, keep forever.
197 return core_component::get_component_directory($component);
201 // === Deprecated before 2.6.0 ===
204 * Hack to find out the GD version by parsing phpinfo output
206 * @return int GD version (1, 2, or 0)
208 function check_gd_version() {
209 // TODO: delete function in Moodle 2.7
210 debugging('check_gd_version() is deprecated, GD extension is always available now');
214 if (function_exists('gd_info')){
215 $gd_info = gd_info();
216 if (substr_count($gd_info['GD Version'], '2.')) {
218 } else if (substr_count($gd_info['GD Version'], '1.')) {
224 phpinfo(INFO_MODULES);
225 $phpinfo = ob_get_contents();
228 $phpinfo = explode("\n", $phpinfo);
231 foreach ($phpinfo as $text) {
232 $parts = explode('</td>', $text);
233 foreach ($parts as $key => $val) {
234 $parts[$key] = trim(strip_tags($val));
236 if ($parts[0] == 'GD Version') {
237 if (substr_count($parts[1], '2.0')) {
240 $gdversion = intval($parts[1]);
245 return $gdversion; // 1, 2 or 0
249 * Not used any more, the account lockout handling is now
250 * part of authenticate_user_login().
253 function update_login_count() {
254 // TODO: delete function in Moodle 2.6
255 debugging('update_login_count() is deprecated, all calls need to be removed');
259 * Not used any more, replaced by proper account lockout.
262 function reset_login_count() {
263 // TODO: delete function in Moodle 2.6
264 debugging('reset_login_count() is deprecated, all calls need to be removed');
268 * Insert or update log display entry. Entry may already exist.
269 * $module, $action must be unique
272 * @param string $module
273 * @param string $action
274 * @param string $mtable
275 * @param string $field
279 function update_log_display_entry($module, $action, $mtable, $field) {
282 debugging('The update_log_display_entry() is deprecated, please use db/log.php description file instead.');
286 * Given some text in HTML format, this function will pass it
287 * through any filters that have been configured for this context.
289 * @deprecated use the text formatting in a standard way instead,
290 * this was abused mostly for embedding of attachments
292 * @param string $text The text to be passed through format filters
293 * @param int $courseid The current course.
294 * @return string the filtered string.
296 function filter_text($text, $courseid = NULL) {
297 global $CFG, $COURSE;
300 $courseid = $COURSE->id;
303 if (!$context = context_course::instance($courseid, IGNORE_MISSING)) {
307 return filter_manager::instance()->filter_text($text, $context);
311 * This function indicates that current page requires the https
312 * when $CFG->loginhttps enabled.
314 * By using this function properly, we can ensure 100% https-ized pages
315 * at our entire discretion (login, forgot_password, change_password)
316 * @deprecated use $PAGE->https_required() instead
318 function httpsrequired() {
320 $PAGE->https_required();
324 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
326 * @deprecated use moodle_url factory methods instead
328 * @param string $path Physical path to a file
329 * @param array $options associative array of GET variables to append to the URL
330 * @param string $type (questionfile|rssfile|httpscoursefile|coursefile)
331 * @return string URL to file
333 function get_file_url($path, $options=null, $type='coursefile') {
336 $path = str_replace('//', '/', $path);
337 $path = trim($path, '/'); // no leading and trailing slashes
342 $url = $CFG->wwwroot."/question/exportfile.php";
345 $url = $CFG->wwwroot."/rss/file.php";
347 case 'httpscoursefile':
348 $url = $CFG->httpswwwroot."/file.php";
352 $url = $CFG->wwwroot."/file.php";
355 if ($CFG->slasharguments) {
356 $parts = explode('/', $path);
357 foreach ($parts as $key => $part) {
358 /// anchor dash character should not be encoded
359 $subparts = explode('#', $part);
360 $subparts = array_map('rawurlencode', $subparts);
361 $parts[$key] = implode('#', $subparts);
363 $path = implode('/', $parts);
364 $ffurl = $url.'/'.$path;
367 $path = rawurlencode('/'.$path);
368 $ffurl = $url.'?file='.$path;
369 $separator = '&';
373 foreach ($options as $name=>$value) {
374 $ffurl = $ffurl.$separator.$name.'='.$value;
375 $separator = '&';
383 * Return the authentication plugin title
385 * @param string $authtype plugin type
388 function auth_get_plugin_title($authtype) {
389 debugging('Function auth_get_plugin_title() is deprecated, please use standard get_string("pluginname", "auth_'.$authtype.'")!');
390 return get_string('pluginname', "auth_{$authtype}");
394 * Returns a role object that is the default role for new enrolments in a given course
397 * @param object $course
398 * @return object returns a role or NULL if none set
400 function get_default_course_role($course) {
401 debugging('Function get_default_course_role() is deprecated, please use individual enrol plugin settings instead!');
403 $student = get_archetype_roles('student');
404 $student = reset($student);
410 * Was returning list of translations, use new string_manager instead
413 * @param bool $refreshcache force refreshing of lang cache
414 * @param bool $returnall ignore langlist, return all languages available
415 * @return array An associative array with contents in the form of LanguageCode => LanguageName
417 function get_list_of_languages($refreshcache=false, $returnall=false) {
418 debugging('get_list_of_languages() is deprecated, please use get_string_manager()->get_list_of_translations() instead.');
420 get_string_manager()->reset_caches();
422 return get_string_manager()->get_list_of_translations($returnall);
426 * Returns a list of currencies in the current language
430 function get_list_of_currencies() {
431 debugging('get_list_of_currencies() is deprecated, please use get_string_manager()->get_list_of_currencies() instead.');
432 return get_string_manager()->get_list_of_currencies();
436 * Returns a list of all enabled country names in the current translation
438 * @return array two-letter country code => translated name.
440 function get_list_of_countries() {
441 debugging('get_list_of_countries() is deprecated, please use get_string_manager()->get_list_of_countries() instead.');
442 return get_string_manager()->get_list_of_countries(false);
446 * Return all course participant for a given course
449 * @param integer $courseid
450 * @return array of user
452 function get_course_participants($courseid) {
453 return get_enrolled_users(context_course::instance($courseid));
457 * Return true if the user is a participant for a given course
460 * @param integer $userid
461 * @param integer $courseid
464 function is_course_participant($userid, $courseid) {
465 return is_enrolled(context_course::instance($courseid), $userid);
469 * Searches logs to find all enrolments since a certain date
471 * used to print recent activity
473 * @todo MDL-36993 this function is still used in block_recent_activity, deprecate properly
475 * @uses CONTEXT_COURSE
476 * @param int $courseid The course in question.
477 * @param int $timestart The date to check forward of
478 * @return object|false {@link $USER} records or false if error.
480 function get_recent_enrolments($courseid, $timestart) {
483 $context = context_course::instance($courseid);
485 $sql = "SELECT u.id, u.firstname, u.lastname, MAX(l.time)
486 FROM {user} u, {role_assignments} ra, {log} l
489 AND l.module = 'course'
490 AND l.action = 'enrol'
491 AND ".$DB->sql_cast_char2int('l.info')." = u.id
493 AND ra.contextid ".get_related_contexts_string($context)."
494 GROUP BY u.id, u.firstname, u.lastname
495 ORDER BY MAX(l.time) ASC";
496 $params = array($timestart, $courseid);
497 return $DB->get_records_sql($sql, $params);
500 ########### FROM weblib.php ##########################################################################
504 * Print a message in a standard themed box.
505 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
506 * parameters remain. If possible, $align, $width and $color should not be defined at all.
507 * Preferably just use print_box() in weblib.php
510 * @param string $message The message to display
511 * @param string $align alignment of the box, not the text (default center, left, right).
512 * @param string $width width of the box, including units %, for example '100%'.
513 * @param string $color background colour of the box, for example '#eee'.
514 * @param int $padding padding in pixels, specified without units.
515 * @param string $class space-separated class names.
516 * @param string $id space-separated id names.
517 * @param boolean $return return as string or just print it
518 * @return string|void Depending on $return
520 function print_simple_box($message, $align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
522 $output .= print_simple_box_start($align, $width, $color, $padding, $class, $id, true);
524 $output .= print_simple_box_end(true);
536 * This old function used to implement boxes using tables. Now it uses a DIV, but the old
537 * parameters remain. If possible, $align, $width and $color should not be defined at all.
538 * Even better, please use print_box_start() in weblib.php
540 * @param string $align alignment of the box, not the text (default center, left, right). DEPRECATED
541 * @param string $width width of the box, including % units, for example '100%'. DEPRECATED
542 * @param string $color background colour of the box, for example '#eee'. DEPRECATED
543 * @param int $padding padding in pixels, specified without units. OBSOLETE
544 * @param string $class space-separated class names.
545 * @param string $id space-separated id names.
546 * @param boolean $return return as string or just print it
547 * @return string|void Depending on $return
549 function print_simple_box_start($align='', $width='', $color='', $padding=5, $class='generalbox', $id='', $return=false) {
550 debugging('print_simple_box(_start/_end) is deprecated. Please use $OUTPUT->box(_start/_end) instead', DEBUG_DEVELOPER);
554 $divclasses = 'box '.$class.' '.$class.'content';
558 $divclasses .= ' boxalign'.$align; // Implement alignment using a class
560 if ($width) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
561 if (substr($width, -1, 1) == '%') { // Width is a % value
562 $width = (int) substr($width, 0, -1); // Extract just the number
564 $divclasses .= ' boxwidthnarrow'; // Approx 30% depending on theme
565 } else if ($width > 60) {
566 $divclasses .= ' boxwidthwide'; // Approx 80% depending on theme
568 $divclasses .= ' boxwidthnormal'; // Approx 50% depending on theme
571 $divstyles .= ' width:'.$width.';'; // Last resort
574 if ($color) { // Hopefully we can eliminate these in calls to this function (inline styles are bad)
575 $divstyles .= ' background:'.$color.';';
578 $divstyles = ' style="'.$divstyles.'"';
582 $id = ' id="'.$id.'"';
585 $output .= '<div'.$id.$divstyles.' class="'.$divclasses.'">';
596 * Print the end portion of a standard themed box.
597 * Preferably just use print_box_end() in weblib.php
599 * @param boolean $return return as string or just print it
600 * @return string|void Depending on $return
602 function print_simple_box_end($return=false) {
612 * Given some text this function converted any URLs it found into HTML links
614 * This core function has been replaced with filter_urltolink since Moodle 2.0
616 * @param string $text Passed in by reference. The string to be searched for urls.
618 function convert_urls_into_links($text) {
619 debugging('convert_urls_into_links() has been deprecated and replaced by a new filter');
623 * Used to be called from help.php to inject a list of smilies into the
624 * emoticons help file.
626 * @return string HTML
628 function get_emoticons_list_for_help_file() {
629 debugging('get_emoticons_list_for_help_file() has been deprecated, see the new emoticon_manager API');
634 * Was used to replace all known smileys in the text with image equivalents
636 * This core function has been replaced with filter_emoticon since Moodle 2.0
638 function replace_smilies(&$text) {
639 debugging('replace_smilies() has been deprecated and replaced with the new filter_emoticon');
643 * deprecated - use clean_param($string, PARAM_FILE); instead
644 * Check for bad characters ?
646 * @todo Finish documenting this function - more detail needed in description as well as details on arguments
648 * @param string $string ?
649 * @param int $allowdots ?
652 function detect_munged_arguments($string, $allowdots=1) {
653 if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references
656 if (preg_match('/[\|\`]/', $string)) { // check for other bad characters
659 if (empty($string) or $string == '/') {
668 * Unzip one zip file to a destination dir
669 * Both parameters must be FULL paths
670 * If destination isn't specified, it will be the
671 * SAME directory where the zip file resides.
674 * @param string $zipfile The zip file to unzip
675 * @param string $destination The location to unzip to
676 * @param bool $showstatus_ignored Unused
678 function unzip_file($zipfile, $destination = '', $showstatus_ignored = true) {
681 //Extract everything from zipfile
682 $path_parts = pathinfo(cleardoubleslashes($zipfile));
683 $zippath = $path_parts["dirname"]; //The path of the zip file
684 $zipfilename = $path_parts["basename"]; //The name of the zip file
685 $extension = $path_parts["extension"]; //The extension of the file
688 if (empty($zipfilename)) {
692 //If no extension, error
693 if (empty($extension)) {
698 $zipfile = cleardoubleslashes($zipfile);
700 //Check zipfile exists
701 if (!file_exists($zipfile)) {
705 //If no destination, passed let's go with the same directory
706 if (empty($destination)) {
707 $destination = $zippath;
711 $destpath = rtrim(cleardoubleslashes($destination), "/");
713 //Check destination path exists
714 if (!is_dir($destpath)) {
718 $packer = get_file_packer('application/zip');
720 $result = $packer->extract_to_pathname($zipfile, $destpath);
722 if ($result === false) {
726 foreach ($result as $status) {
727 if ($status !== true) {
736 * Zip an array of files/dirs to a destination zip file
737 * Both parameters must be FULL paths to the files/dirs
740 * @param array $originalfiles Files to zip
741 * @param string $destination The destination path
742 * @return bool Outcome
744 function zip_files ($originalfiles, $destination) {
747 //Extract everything from destination
748 $path_parts = pathinfo(cleardoubleslashes($destination));
749 $destpath = $path_parts["dirname"]; //The path of the zip file
750 $destfilename = $path_parts["basename"]; //The name of the zip file
751 $extension = $path_parts["extension"]; //The extension of the file
754 if (empty($destfilename)) {
758 //If no extension, add it
759 if (empty($extension)) {
761 $destfilename = $destfilename.'.'.$extension;
764 //Check destination path exists
765 if (!is_dir($destpath)) {
769 //Check destination path is writable. TODO!!
771 //Clean destination filename
772 $destfilename = clean_filename($destfilename);
774 //Now check and prepare every file
778 foreach ($originalfiles as $file) { //Iterate over each file
779 //Check for every file
780 $tempfile = cleardoubleslashes($file); // no doubleslashes!
781 //Calculate the base path for all files if it isn't set
782 if ($origpath === NULL) {
783 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
785 //See if the file is readable
786 if (!is_readable($tempfile)) { //Is readable
789 //See if the file/dir is in the same directory than the rest
790 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
793 //Add the file to the array
794 $files[] = $tempfile;
798 $start = strlen($origpath)+1;
799 foreach($files as $file) {
800 $zipfiles[substr($file, $start)] = $file;
803 $packer = get_file_packer('application/zip');
805 return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename);
808 /////////////////////////////////////////////////////////////
809 /// Old functions not used anymore - candidates for removal
810 /////////////////////////////////////////////////////////////
813 /** various deprecated groups function **/
817 * Get the IDs for the user's groups in the given course.
820 * @param int $courseid The course being examined - the 'course' table id field.
821 * @return array|bool An _array_ of groupids, or false
822 * (Was return $groupids[0] - consequences!)
824 function mygroupid($courseid) {
826 if ($groups = groups_get_all_groups($courseid, $USER->id)) {
827 return array_keys($groups);
835 * Returns the current group mode for a given course or activity module
837 * Could be false, SEPARATEGROUPS or VISIBLEGROUPS (<-- Martin)
839 * @param object $course Course Object
840 * @param object $cm Course Manager Object
841 * @return mixed $course->groupmode
843 function groupmode($course, $cm=null) {
845 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
846 return $cm->groupmode;
848 return $course->groupmode;
852 * Sets the current group in the session variable
853 * When $SESSION->currentgroup[$courseid] is set to 0 it means, show all groups.
854 * Sets currentgroup[$courseid] in the session variable appropriately.
855 * Does not do any permission checking.
858 * @param int $courseid The course being examined - relates to id field in
860 * @param int $groupid The group being examined.
861 * @return int Current group id which was set by this function
863 function set_current_group($courseid, $groupid) {
865 return $SESSION->currentgroup[$courseid] = $groupid;
870 * Gets the current group - either from the session variable or from the database.
873 * @param int $courseid The course being examined - relates to id field in
875 * @param bool $full If true, the return value is a full record object.
876 * If false, just the id of the record.
879 function get_current_group($courseid, $full = false) {
882 if (isset($SESSION->currentgroup[$courseid])) {
884 return groups_get_group($SESSION->currentgroup[$courseid]);
886 return $SESSION->currentgroup[$courseid];
890 $mygroupid = mygroupid($courseid);
891 if (is_array($mygroupid)) {
892 $mygroupid = array_shift($mygroupid);
893 set_current_group($courseid, $mygroupid);
895 return groups_get_group($mygroupid);
910 * Inndicates fatal error. This function was originally printing the
911 * error message directly, since 2.0 it is throwing exception instead.
912 * The error printing is handled in default exception handler.
914 * Old method, don't call directly in new code - use print_error instead.
916 * @param string $message The message to display to the user about the error.
917 * @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.
918 * @return void, always throws moodle_exception
920 function error($message, $link='') {
921 throw new moodle_exception('notlocalisederrormessage', 'error', $link, $message, 'error() is a deprecated function, please call print_error() instead of error()');
925 //////////////////////////
926 /// removed functions ////
927 //////////////////////////
930 * The old method that was used to include JavaScript libraries.
931 * Please use $PAGE->requires->js_module() instead.
933 * @param mixed $lib The library or libraries to load (a string or array of strings)
934 * There are three way to specify the library:
935 * 1. a shorname like 'yui_yahoo'. This translates into a call to $PAGE->requires->yui2_lib('yahoo');
936 * 2. the path to the library relative to wwwroot, for example 'lib/javascript-static.js'
937 * 3. (legacy) a full URL like $CFG->wwwroot . '/lib/javascript-static.js'.
938 * 2. and 3. lead to a call $PAGE->requires->js('/lib/javascript-static.js').
940 function require_js($lib) {
941 throw new coding_exception('require_js() was removed, use new JS api');
945 * @deprecated use $PAGE->theme->name instead.
946 * @return string the name of the current theme.
948 function current_theme() {
950 // TODO, uncomment this once we have eliminated all references to current_theme in core code.
951 // debugging('current_theme is deprecated, use $PAGE->theme->name instead', DEBUG_DEVELOPER);
952 return $PAGE->theme->name;
956 * Prints some red text using echo
959 * @param string $error The text to be displayed in red
961 function formerr($error) {
962 debugging('formerr() has been deprecated. Please change your code to use $OUTPUT->error_text($string).');
964 echo $OUTPUT->error_text($error);
968 * Return the markup for the destination of the 'Skip to main content' links.
969 * Accessibility improvement for keyboard-only users.
971 * Used in course formats, /index.php and /course/index.php
973 * @deprecated use $OUTPUT->skip_link_target() in instead.
974 * @return string HTML element.
976 function skip_main_destination() {
978 return $OUTPUT->skip_link_target();
982 * Prints a string in a specified size (retained for backward compatibility)
985 * @param string $text The text to be displayed
986 * @param int $size The size to set the font for text display.
987 * @param bool $return If set to true output is returned rather than echoed Default false
988 * @return string|void String if return is true
990 function print_headline($text, $size=2, $return=false) {
992 debugging('print_headline() has been deprecated. Please change your code to use $OUTPUT->heading().');
993 $output = $OUTPUT->heading($text, $size);
1002 * Prints text in a format for use in headings.
1005 * @param string $text The text to be displayed
1006 * @param string $deprecated No longer used. (Use to do alignment.)
1007 * @param int $size The size to set the font for text display.
1008 * @param string $class
1009 * @param bool $return If set to true output is returned rather than echoed, default false
1010 * @param string $id The id to use in the element
1011 * @return string|void String if return=true nothing otherwise
1013 function print_heading($text, $deprecated = '', $size = 2, $class = 'main', $return = false, $id = '') {
1015 debugging('print_heading() has been deprecated. Please change your code to use $OUTPUT->heading().');
1016 if (!empty($deprecated)) {
1017 debugging('Use of deprecated align attribute of print_heading. ' .
1018 'Please do not specify styling in PHP code like that.', DEBUG_DEVELOPER);
1020 $output = $OUTPUT->heading($text, $size, $class, $id);
1029 * Output a standard heading block
1032 * @param string $heading The text to write into the heading
1033 * @param string $class An additional Class Attr to use for the heading
1034 * @param bool $return If set to true output is returned rather than echoed, default false
1035 * @return string|void HTML String if return=true nothing otherwise
1037 function print_heading_block($heading, $class='', $return=false) {
1039 debugging('print_heading_with_block() has been deprecated. Please change your code to use $OUTPUT->heading().');
1040 $output = $OUTPUT->heading($heading, 2, 'headingblock header ' . renderer_base::prepare_classes($class));
1049 * Print a message in a standard themed box.
1050 * Replaces print_simple_box (see deprecatedlib.php)
1053 * @param string $message, the content of the box
1054 * @param string $classes, space-separated class names.
1055 * @param string $ids
1056 * @param boolean $return, return as string or just print it
1057 * @return string|void mixed string or void
1059 function print_box($message, $classes='generalbox', $ids='', $return=false) {
1061 debugging('print_box() has been deprecated. Please change your code to use $OUTPUT->box().');
1062 $output = $OUTPUT->box($message, $classes, $ids);
1071 * Starts a box using divs
1072 * Replaces print_simple_box_start (see deprecatedlib.php)
1075 * @param string $classes, space-separated class names.
1076 * @param string $ids
1077 * @param boolean $return, return as string or just print it
1078 * @return string|void string or void
1080 function print_box_start($classes='generalbox', $ids='', $return=false) {
1082 debugging('print_box_start() has been deprecated. Please change your code to use $OUTPUT->box_start().');
1083 $output = $OUTPUT->box_start($classes, $ids);
1092 * Simple function to end a box (see above)
1093 * Replaces print_simple_box_end (see deprecatedlib.php)
1096 * @param boolean $return, return as string or just print it
1097 * @return string|void Depending on value of return
1099 function print_box_end($return=false) {
1101 debugging('print_box_end() has been deprecated. Please change your code to use $OUTPUT->box_end().');
1102 $output = $OUTPUT->box_end();
1111 * Print a message in a standard themed container.
1114 * @param string $message, the content of the container
1115 * @param boolean $clearfix clear both sides
1116 * @param string $classes, space-separated class names.
1117 * @param string $idbase
1118 * @param boolean $return, return as string or just print it
1119 * @return string|void Depending on value of $return
1121 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
1124 $classes .= ' clearfix';
1126 $output = $OUTPUT->container($message, $classes, $idbase);
1135 * Starts a container using divs
1138 * @param boolean $clearfix clear both sides
1139 * @param string $classes, space-separated class names.
1140 * @param string $idbase
1141 * @param boolean $return, return as string or just print it
1142 * @return string|void Based on value of $return
1144 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
1147 $classes .= ' clearfix';
1149 $output = $OUTPUT->container_start($classes, $idbase);
1158 * Deprecated, now handled automatically in themes
1160 function check_theme_arrows() {
1161 debugging('check_theme_arrows() has been deprecated, do not use it anymore, it is now automatic.');
1165 * Simple function to end a container (see above)
1168 * @param boolean $return, return as string or just print it
1169 * @return string|void Based on $return
1171 function print_container_end($return=false) {
1173 $output = $OUTPUT->container_end();
1182 * Print a bold message in an optional color.
1184 * @deprecated use $OUTPUT->notification instead.
1185 * @param string $message The message to print out
1186 * @param string $style Optional style to display message text in
1187 * @param string $align Alignment option
1188 * @param bool $return whether to return an output string or echo now
1189 * @return string|bool Depending on $result
1191 function notify($message, $classes = 'notifyproblem', $align = 'center', $return = false) {
1194 if ($classes == 'green') {
1195 debugging('Use of deprecated class name "green" in notify. Please change to "notifysuccess".', DEBUG_DEVELOPER);
1196 $classes = 'notifysuccess'; // Backward compatible with old color system
1199 $output = $OUTPUT->notification($message, $classes);
1208 * Print a continue button that goes to a particular URL.
1210 * @deprecated since Moodle 2.0
1212 * @param string $link The url to create a link to.
1213 * @param bool $return If set to true output is returned rather than echoed, default false
1214 * @return string|void HTML String if return=true nothing otherwise
1216 function print_continue($link, $return = false) {
1217 global $CFG, $OUTPUT;
1220 if (!empty($_SERVER['HTTP_REFERER'])) {
1221 $link = $_SERVER['HTTP_REFERER'];
1222 $link = str_replace('&', '&', $link); // make it valid XHTML
1224 $link = $CFG->wwwroot .'/';
1228 $output = $OUTPUT->continue_button($link);
1237 * Print a standard header
1239 * @param string $title Appears at the top of the window
1240 * @param string $heading Appears at the top of the page
1241 * @param string $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
1242 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
1243 * @param string $meta Meta tags to be added to the header
1244 * @param boolean $cache Should this page be cacheable?
1245 * @param string $button HTML code for a button (usually for module editing)
1246 * @param string $menu HTML code for a popup menu
1247 * @param boolean $usexml use XML for this page
1248 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
1249 * @param bool $return If true, return the visible elements of the header instead of echoing them.
1250 * @return string|void If return=true then string else void
1252 function print_header($title='', $heading='', $navigation='', $focus='',
1253 $meta='', $cache=true, $button=' ', $menu=null,
1254 $usexml=false, $bodytags='', $return=false) {
1255 global $PAGE, $OUTPUT;
1257 $PAGE->set_title($title);
1258 $PAGE->set_heading($heading);
1259 $PAGE->set_cacheable($cache);
1260 if ($button == '') {
1263 $PAGE->set_button($button);
1264 $PAGE->set_headingmenu($menu);
1269 throw new coding_exception('The $meta parameter to print_header is no longer supported. '.
1270 'You should be able to do everything you want with $PAGE->requires and other such mechanisms.');
1273 throw new coding_exception('The $usexml parameter to print_header is no longer supported.');
1276 throw new coding_exception('The $bodytags parameter to print_header is no longer supported.');
1279 $output = $OUTPUT->header();
1289 * This version of print_header is simpler because the course name does not have to be
1290 * provided explicitly in the strings. It can be used on the site page as in courses
1291 * Eventually all print_header could be replaced by print_header_simple
1293 * @deprecated since Moodle 2.0
1294 * @param string $title Appears at the top of the window
1295 * @param string $heading Appears at the top of the page
1296 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
1297 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
1298 * @param string $meta Meta tags to be added to the header
1299 * @param boolean $cache Should this page be cacheable?
1300 * @param string $button HTML code for a button (usually for module editing)
1301 * @param string $menu HTML code for a popup menu
1302 * @param boolean $usexml use XML for this page
1303 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
1304 * @param bool $return If true, return the visible elements of the header instead of echoing them.
1305 * @return string|void If $return=true the return string else nothing
1307 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
1308 $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
1310 global $COURSE, $CFG, $PAGE, $OUTPUT;
1313 throw new coding_exception('The $meta parameter to print_header is no longer supported. '.
1314 'You should be able to do everything you want with $PAGE->requires and other such mechanisms.');
1317 throw new coding_exception('The $usexml parameter to print_header is no longer supported.');
1320 throw new coding_exception('The $bodytags parameter to print_header is no longer supported.');
1323 $PAGE->set_title($title);
1324 $PAGE->set_heading($heading);
1325 $PAGE->set_cacheable(true);
1326 $PAGE->set_button($button);
1328 $output = $OUTPUT->header();
1337 function print_footer($course = NULL, $usercourse = NULL, $return = false) {
1338 global $PAGE, $OUTPUT;
1339 debugging('print_footer() has been deprecated. Please change your code to use $OUTPUT->footer().');
1340 // TODO check arguments.
1341 if (is_string($course)) {
1342 debugging("Magic values like 'home', 'empty' passed to print_footer no longer have any effect. " .
1343 'To achieve a similar effect, call $PAGE->set_pagelayout before you call print_header.', DEBUG_DEVELOPER);
1344 } else if (!empty($course->id) && $course->id != $PAGE->course->id) {
1345 throw new coding_exception('The $course object you passed to print_footer does not match $PAGE->course.');
1347 if (!is_null($usercourse)) {
1348 debugging('The second parameter ($usercourse) to print_footer is no longer supported. ' .
1349 '(I did not think it was being used anywhere.)', DEBUG_DEVELOPER);
1351 $output = $OUTPUT->footer();
1360 * Returns text to be displayed to the user which reflects their login status
1366 * @uses CONTEXT_COURSE
1367 * @param course $course {@link $COURSE} object containing course information
1368 * @param user $user {@link $USER} object containing user information
1369 * @return string HTML
1371 function user_login_string($course='ignored', $user='ignored') {
1372 debugging('user_login_info() has been deprecated. User login info is now handled via themes layouts.');
1377 * Prints a nice side block with an optional header. The content can either
1378 * be a block of HTML or a list of text with optional icons.
1380 * @todo Finish documenting this function. Show example of various attributes, etc.
1382 * @static int $block_id Increments for each call to the function
1383 * @param string $heading HTML for the heading. Can include full HTML or just
1384 * plain text - plain text will automatically be enclosed in the appropriate
1386 * @param string $content HTML for the content
1387 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1388 * @param array $icons optional icons for the things in $list.
1389 * @param string $footer Extra HTML content that gets output at the end, inside a <div class="footer">
1390 * @param array $attributes an array of attribute => value pairs that are put on the
1391 * outer div of this block. If there is a class attribute ' block' gets appended to it. If there isn't
1392 * already a class, class='block' is used.
1393 * @param string $title Plain text title, as embedded in the $heading.
1396 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
1399 // We don't use $heading, becuse it often contains HTML that we don't want.
1400 // However, sometimes $title is not set, but $heading is.
1401 if (empty($title)) {
1402 $title = strip_tags($heading);
1405 // Render list contents to HTML if required.
1406 if (empty($content) && $list) {
1407 $content = $OUTPUT->list_block_contents($icons, $list);
1410 $bc = new block_contents();
1411 $bc->content = $content;
1412 $bc->footer = $footer;
1413 $bc->title = $title;
1415 if (isset($attributes['id'])) {
1416 $bc->id = $attributes['id'];
1417 unset($attributes['id']);
1419 $bc->attributes = $attributes;
1421 echo $OUTPUT->block($bc, BLOCK_POS_LEFT); // POS LEFT may be wrong, but no way to get a better guess here.
1425 * This was used by old code to see whether a block region had anything in it,
1426 * and hence wether that region should be printed.
1428 * We don't ever want old code to print blocks, so we now always return false.
1429 * The function only exists to avoid fatal errors in old code.
1431 * @deprecated since Moodle 2.0. always returns false.
1433 * @param object $blockmanager
1434 * @param string $region
1437 function blocks_have_content(&$blockmanager, $region) {
1438 debugging('The function blocks_have_content should no longer be used. Blocks are now printed by the theme.');
1443 * This was used by old code to print the blocks in a region.
1445 * We don't ever want old code to print blocks, so this is now a no-op.
1446 * The function only exists to avoid fatal errors in old code.
1448 * @deprecated since Moodle 2.0. does nothing.
1450 * @param object $page
1451 * @param object $blockmanager
1452 * @param string $region
1454 function blocks_print_group($page, $blockmanager, $region) {
1455 debugging('The function blocks_print_group should no longer be used. Blocks are now printed by the theme.');
1459 * This used to be the old entry point for anyone that wants to use blocks.
1460 * Since we don't want people people dealing with blocks this way any more,
1461 * just return a suitable empty array.
1463 * @deprecated since Moodle 2.0.
1465 * @param object $page
1468 function blocks_setup(&$page, $pinned = BLOCKS_PINNED_FALSE) {
1469 debugging('The function blocks_print_group should no longer be used. Blocks are now printed by the theme.');
1470 return array(BLOCK_POS_LEFT => array(), BLOCK_POS_RIGHT => array());
1474 * This iterates over an array of blocks and calculates the preferred width
1475 * Parameter passed by reference for speed; it's not modified.
1477 * @deprecated since Moodle 2.0. Layout is now controlled by the theme.
1479 * @param mixed $instances
1481 function blocks_preferred_width($instances) {
1482 debugging('The function blocks_print_group should no longer be used. Blocks are now printed by the theme.');
1487 * Print a nicely formatted table.
1489 * @deprecated since Moodle 2.0
1491 * @param array $table is an object with several properties.
1493 function print_table($table, $return=false) {
1495 // TODO MDL-19755 turn debugging on once we migrate the current core code to use the new API
1496 debugging('print_table() has been deprecated. Please change your code to use html_writer::table().');
1497 $newtable = new html_table();
1498 foreach ($table as $property => $value) {
1499 if (property_exists($newtable, $property)) {
1500 $newtable->{$property} = $value;
1503 if (isset($table->class)) {
1504 $newtable->attributes['class'] = $table->class;
1506 if (isset($table->rowclass) && is_array($table->rowclass)) {
1507 debugging('rowclass[] has been deprecated for html_table and should be replaced by rowclasses[]. please fix the code.');
1508 $newtable->rowclasses = $table->rowclass;
1510 $output = html_writer::table($newtable);
1520 * Creates and displays (or returns) a link to a popup window
1522 * @deprecated since Moodle 2.0
1524 * @param string $url Web link. Either relative to $CFG->wwwroot, or a full URL.
1525 * @param string $name Name to be assigned to the popup window (this is used by
1526 * client-side scripts to "talk" to the popup window)
1527 * @param string $linkname Text to be displayed as web link
1528 * @param int $height Height to assign to popup window
1529 * @param int $width Height to assign to popup window
1530 * @param string $title Text to be displayed as popup page title
1531 * @param string $options List of additional options for popup window
1532 * @param bool $return If true, return as a string, otherwise print
1533 * @param string $id id added to the element
1534 * @param string $class class added to the element
1535 * @return string html code to display a link to a popup window.
1537 function link_to_popup_window ($url, $name=null, $linkname=null, $height=400, $width=500, $title=null, $options=null, $return=false) {
1538 debugging('link_to_popup_window() has been removed. Please change your code to use $OUTPUT->action_link(). Please note popups are discouraged for accessibility reasons');
1540 return html_writer::link($url, $name);
1544 * Creates and displays (or returns) a buttons to a popup window.
1546 * @deprecated since Moodle 2.0
1548 * @param string $url Web link. Either relative to $CFG->wwwroot, or a full URL.
1549 * @param string $name Name to be assigned to the popup window (this is used by
1550 * client-side scripts to "talk" to the popup window)
1551 * @param string $linkname Text to be displayed as web link
1552 * @param int $height Height to assign to popup window
1553 * @param int $width Height to assign to popup window
1554 * @param string $title Text to be displayed as popup page title
1555 * @param string $options List of additional options for popup window
1556 * @param bool $return If true, return as a string, otherwise print
1557 * @param string $id id added to the element
1558 * @param string $class class added to the element
1559 * @return string html code to display a link to a popup window.
1561 function button_to_popup_window ($url, $name=null, $linkname=null,
1562 $height=400, $width=500, $title=null, $options=null, $return=false,
1563 $id=null, $class=null) {
1566 debugging('button_to_popup_window() has been deprecated. Please change your code to use $OUTPUT->single_button().');
1568 if ($options == 'none') {
1572 if (empty($linkname)) {
1573 throw new coding_exception('A link must have a descriptive text value! See $OUTPUT->action_link() for usage.');
1576 // Create a single_button object
1577 $form = new single_button($url, $linkname, 'post');
1578 $form->button->title = $title;
1579 $form->button->id = $id;
1581 // Parse the $options string
1582 $popupparams = array();
1583 if (!empty($options)) {
1584 $optionsarray = explode(',', $options);
1585 foreach ($optionsarray as $option) {
1586 if (strstr($option, '=')) {
1587 $parts = explode('=', $option);
1588 if ($parts[1] == '0') {
1589 $popupparams[$parts[0]] = false;
1591 $popupparams[$parts[0]] = $parts[1];
1594 $popupparams[$option] = true;
1599 if (!empty($height)) {
1600 $popupparams['height'] = $height;
1602 if (!empty($width)) {
1603 $popupparams['width'] = $width;
1606 $form->button->add_action(new popup_action('click', $url, $name, $popupparams));
1607 $output = $OUTPUT->render($form);
1617 * Print a self contained form with a single submit button.
1619 * @deprecated since Moodle 2.0
1621 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
1622 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
1623 * @param string $label the caption that appears on the button.
1624 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
1625 * @param string $notusedanymore no longer used.
1626 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
1627 * @param string $tooltip a tooltip to add to the button as a title attribute.
1628 * @param boolean $disabled if true, the button will be disabled.
1629 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
1630 * @param string $formid The id attribute to use for the form
1631 * @return string|void Depending on the $return paramter.
1633 function print_single_button($link, $options, $label='OK', $method='get', $notusedanymore='',
1634 $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='', $formid = '') {
1637 debugging('print_single_button() has been deprecated. Please change your code to use $OUTPUT->single_button().');
1639 // Cast $options to array
1640 $options = (array) $options;
1642 $button = new single_button(new moodle_url($link, $options), $label, $method, array('disabled'=>$disabled, 'title'=>$tooltip, 'id'=>$formid));
1644 if ($jsconfirmmessage) {
1645 $button->button->add_confirm_action($jsconfirmmessage);
1648 $output = $OUTPUT->render($button);
1658 * Print a spacer image with the option of including a line break.
1660 * @deprecated since Moodle 2.0
1663 * @param int $height The height in pixels to make the spacer
1664 * @param int $width The width in pixels to make the spacer
1665 * @param boolean $br If set to true a BR is written after the spacer
1667 function print_spacer($height=1, $width=1, $br=true, $return=false) {
1668 global $CFG, $OUTPUT;
1670 debugging('print_spacer() has been deprecated. Please change your code to use $OUTPUT->spacer().');
1672 $output = $OUTPUT->spacer(array('height'=>$height, 'width'=>$width, 'br'=>$br));
1682 * Print the specified user's avatar.
1684 * @deprecated since Moodle 2.0
1688 * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname, email
1689 * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
1690 * if at all possible, particularly for reports. It is very bad for performance.
1691 * @param int $courseid The course id. Used when constructing the link to the user's profile.
1692 * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
1693 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
1694 * @param boolean $return If false print picture to current page, otherwise return the output as string
1695 * @param boolean $link enclose printed image in a link the user's profile (default true).
1696 * @param string $target link target attribute. Makes the profile open in a popup window.
1697 * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
1698 * decorative images, or where the username will be printed anyway.)
1699 * @return string|void String or nothing, depending on $return.
1701 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
1704 debugging('print_user_picture() has been deprecated. Please change your code to use $OUTPUT->user_picture($user, array(\'courseid\'=>$courseid).');
1706 if (!is_object($user)) {
1708 $user = new stdClass();
1709 $user->id = $userid;
1712 if (empty($user->picture) and $picture) {
1713 $user->picture = $picture;
1716 $options = array('size'=>$size, 'link'=>$link, 'alttext'=>$alttext, 'courseid'=>$courseid, 'popup'=>!empty($target));
1718 $output = $OUTPUT->user_picture($user, $options);
1728 * Prints a basic textarea field.
1730 * @deprecated since Moodle 2.0
1732 * When using this function, you should
1735 * @param bool $usehtmleditor Enables the use of the htmleditor for this field.
1736 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
1737 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
1738 * @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.
1739 * @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.
1740 * @param string $name Name to use for the textarea element.
1741 * @param string $value Initial content to display in the textarea.
1742 * @param int $obsolete deprecated
1743 * @param bool $return If false, will output string. If true, will return string value.
1744 * @param string $id CSS ID to add to the textarea element.
1745 * @return string|void depending on the value of $return
1747 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
1748 /// $width and height are legacy fields and no longer used as pixels like they used to be.
1749 /// However, you can set them to zero to override the mincols and minrows values below.
1751 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
1752 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
1761 $id = 'edit-'.$name;
1764 if ($usehtmleditor) {
1765 if ($height && ($rows < $minrows)) {
1768 if ($width && ($cols < $mincols)) {
1773 if ($usehtmleditor) {
1774 editors_head_setup();
1775 $editor = editors_get_preferred_editor(FORMAT_HTML);
1776 $editor->use_editor($id, array('legacy'=>true));
1781 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
1782 if ($usehtmleditor) {
1783 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
1787 $str .= '</textarea>'."\n";
1797 * Print a help button.
1799 * @deprecated since Moodle 2.0
1801 function helpbutton($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false, $imagetext='') {
1802 throw new coding_exception('helpbutton() can not be used any more, please see $OUTPUT->help_icon().');
1806 * Print a help button.
1808 * Prints a special help button that is a link to the "live" emoticon popup
1810 * @todo Finish documenting this function
1814 * @param string $form ?
1815 * @param string $field ?
1816 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
1817 * @return string|void Depending on value of $return
1819 function emoticonhelpbutton($form, $field, $return = false) {
1822 debugging('emoticonhelpbutton() was removed, new text editors will implement this feature');
1826 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
1827 * Should be used only with htmleditor or textarea.
1831 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
1833 * @return string Link to help button
1835 function editorhelpbutton(){
1842 * Print a help button.
1844 * Prints a special help button for html editors (htmlarea in this case)
1846 * @todo Write code into this function! detect current editor and print correct info
1848 * @return string Only returns an empty string at the moment
1850 function editorshortcutshelpbutton() {
1854 //TODO: detect current editor and print correct info
1860 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
1861 * provide this function with the language strings for sortasc and sortdesc.
1863 * @deprecated since Moodle 2.0
1865 * TODO migrate to outputlib
1866 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
1869 * @param string $direction 'up' or 'down'
1870 * @param string $strsort The language string used for the alt attribute of this image
1871 * @param bool $return Whether to print directly or return the html string
1872 * @return string|void depending on $return
1875 function print_arrow($direction='up', $strsort=null, $return=false) {
1876 // debugging('print_arrow() has been deprecated. Please change your code to use $OUTPUT->arrow().');
1880 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
1886 switch ($direction) {
1901 // Prepare language string
1903 if (empty($strsort) && !empty($sortdir)) {
1904 $strsort = get_string('sort' . $sortdir, 'grades');
1907 $return = ' <img src="'.$OUTPUT->pix_url('t/' . $direction) . '" alt="'.$strsort.'" /> ';
1917 * Returns a string containing a link to the user documentation.
1918 * Also contains an icon by default. Shown to teachers and admin only.
1920 * @deprecated since Moodle 2.0
1922 function doc_link($path='', $text='', $iconpath='ignored') {
1923 throw new coding_exception('doc_link() can not be used any more, please see $OUTPUT->doc_link().');
1927 * Prints a single paging bar to provide access to other pages (usually in a search)
1929 * @deprecated since Moodle 2.0
1931 * @param int $totalcount Thetotal number of entries available to be paged through
1932 * @param int $page The page you are currently viewing
1933 * @param int $perpage The number of entries that should be shown per page
1934 * @param mixed $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
1935 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1936 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1937 * @param bool $nocurr do not display the current page as a link (dropped, link is never displayed for the current page)
1938 * @param bool $return whether to return an output string or echo now
1939 * @return bool|string depending on $result
1941 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
1944 debugging('print_paging_bar() has been deprecated. Please change your code to use $OUTPUT->render($pagingbar).');
1946 if (empty($nocurr)) {
1947 debugging('the feature of parameter $nocurr has been removed from the paging_bar');
1950 $pagingbar = new paging_bar($totalcount, $page, $perpage, $baseurl);
1951 $pagingbar->pagevar = $pagevar;
1952 $output = $OUTPUT->render($pagingbar);
1963 * Print a message along with "Yes" and "No" links for the user to continue.
1965 * @deprecated since Moodle 2.0
1968 * @param string $message The text to display
1969 * @param string $linkyes The link to take the user to if they choose "Yes"
1970 * @param string $linkno The link to take the user to if they choose "No"
1971 * @param string $optionyes The yes option to show on the notice
1972 * @param string $optionsno The no option to show
1973 * @param string $methodyes Form action method to use if yes [post, get]
1974 * @param string $methodno Form action method to use if no [post, get]
1975 * @return void Output is echo'd
1977 function notice_yesno($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
1979 debugging('notice_yesno() has been deprecated. Please change your code to use $OUTPUT->confirm($message, $buttoncontinue, $buttoncancel).');
1983 $buttoncontinue = new single_button(new moodle_url($linkyes, $optionsyes), get_string('yes'), $methodyes);
1984 $buttoncancel = new single_button(new moodle_url($linkno, $optionsno), get_string('no'), $methodno);
1986 echo $OUTPUT->confirm($message, $buttoncontinue, $buttoncancel);
1990 * Given an array of values, output the HTML for a select element with those options.
1992 * @deprecated since Moodle 2.0
1994 * Normally, you only need to use the first few parameters.
1996 * @param array $options The options to offer. An array of the form
1997 * $options[{value}] = {text displayed for that option};
1998 * @param string $name the name of this form control, as in <select name="..." ...
1999 * @param string $selected the option to select initially, default none.
2000 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
2001 * Set this to '' if you don't want a 'nothing is selected' option.
2002 * @param string $script if not '', then this is added to the <select> element as an onchange handler.
2003 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
2004 * @param boolean $return if false (the default) the the output is printed directly, If true, the
2005 * generated HTML is returned as a string.
2006 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
2007 * @param int $tabindex if give, sets the tabindex attribute on the <select> element. Default none.
2008 * @param string $id value to use for the id attribute of the <select> element. If none is given,
2009 * then a suitable one is constructed.
2010 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
2011 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
2012 * $listbox is an integer, that number is used for size instead.
2013 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
2014 * when $listbox display is enabled
2015 * @param string $class value to use for the class attribute of the <select> element. If none is given,
2016 * then a suitable one is constructed.
2017 * @return string|void If $return=true returns string, else echo's and returns void
2019 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
2020 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
2021 $id='', $listbox=false, $multiple=false, $class='') {
2024 debugging('choose_from_menu() has been deprecated. Please change your code to use html_writer::select().');
2027 debugging('The $script parameter has been deprecated. You must use component_actions instead', DEBUG_DEVELOPER);
2029 $attributes = array();
2030 $attributes['disabled'] = $disabled ? 'disabled' : null;
2031 $attributes['tabindex'] = $tabindex ? $tabindex : null;
2032 $attributes['multiple'] = $multiple ? $multiple : null;
2033 $attributes['class'] = $class ? $class : null;
2034 $attributes['id'] = $id ? $id : null;
2036 $output = html_writer::select($options, $name, $selected, array($nothingvalue=>$nothing), $attributes);
2046 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
2047 * Other options like choose_from_menu.
2049 * @deprecated since Moodle 2.0
2051 * Calls {@link choose_from_menu()} with preset arguments
2052 * @see choose_from_menu()
2054 * @param string $name the name of this form control, as in <select name="..." ...
2055 * @param string $selected the option to select initially, default none.
2056 * @param string $script if not '', then this is added to the <select> element as an onchange handler.
2057 * @param boolean $return Whether this function should return a string or output it (defaults to false)
2058 * @param boolean $disabled (defaults to false)
2059 * @param int $tabindex
2060 * @return string|void If $return=true returns string, else echo's and returns void
2062 function choose_from_menu_yesno($name, $selected, $script = '', $return = false, $disabled = false, $tabindex = 0) {
2063 debugging('choose_from_menu_yesno() has been deprecated. Please change your code to use html_writer.');
2067 debugging('The $script parameter has been deprecated. You must use component_actions instead', DEBUG_DEVELOPER);
2070 $output = html_writer::select_yes_no($name, $selected, array('disabled'=>($disabled ? 'disabled' : null), 'tabindex'=>$tabindex));
2080 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
2081 * including option headings with the first level.
2083 * @deprecated since Moodle 2.0
2085 * This function is very similar to {@link choose_from_menu_yesno()}
2086 * and {@link choose_from_menu()}
2088 * @todo Add datatype handling to make sure $options is an array
2090 * @param array $options An array of objects to choose from
2091 * @param string $name The XHTML field name
2092 * @param string $selected The value to select by default
2093 * @param string $nothing The label for the 'nothing is selected' option.
2094 * Defaults to get_string('choose').
2095 * @param string $script If not '', then this is added to the <select> element
2096 * as an onchange handler.
2097 * @param string $nothingvalue The value for the first `nothing` option if $nothing is set
2098 * @param bool $return Whether this function should return a string or output
2099 * it (defaults to false)
2100 * @param bool $disabled Is the field disabled by default
2101 * @param int|string $tabindex Override the tabindex attribute [numeric]
2102 * @return string|void If $return=true returns string, else echo's and returns void
2104 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
2105 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
2107 debugging('choose_from_menu_nested() has been removed. Please change your code to use html_writer::select().');
2112 * Prints a help button about a scale
2114 * @deprecated since Moodle 2.0
2117 * @param id $courseid
2118 * @param object $scale
2119 * @param boolean $return If set to true returns rather than echo's
2120 * @return string|bool Depending on value of $return
2122 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
2123 // debugging('print_scale_menu_helpbutton() has been deprecated. Please change your code to use $OUTPUT->help_scale($courseid, $scale).');
2126 $output = $OUTPUT->help_icon_scale($courseid, $scale);
2136 * Prints form items with the names $hour and $minute
2138 * @deprecated since Moodle 2.0
2140 * @param string $hour fieldname
2141 * @param string $minute fieldname
2142 * @param int $currenttime A default timestamp in GMT
2143 * @param int $step minute spacing
2144 * @param boolean $return If set to true returns rather than echo's
2145 * @return string|bool Depending on value of $return
2147 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
2148 debugging('print_time_selector() has been deprecated. Please change your code to use html_writer.');
2150 $hourselector = html_writer::select_time('hours', $hour, $currenttime);
2151 $minuteselector = html_writer::select_time('minutes', $minute, $currenttime, $step);
2153 $output = $hourselector . $$minuteselector;
2163 * Prints form items with the names $day, $month and $year
2165 * @deprecated since Moodle 2.0
2167 * @param string $day fieldname
2168 * @param string $month fieldname
2169 * @param string $year fieldname
2170 * @param int $currenttime A default timestamp in GMT
2171 * @param boolean $return If set to true returns rather than echo's
2172 * @return string|bool Depending on value of $return
2174 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
2175 debugging('print_date_selector() has been deprecated. Please change your code to use html_writer.');
2177 $dayselector = html_writer::select_time('days', $day, $currenttime);
2178 $monthselector = html_writer::select_time('months', $month, $currenttime);
2179 $yearselector = html_writer::select_time('years', $year, $currenttime);
2181 $output = $dayselector . $monthselector . $yearselector;
2191 * Implements a complete little form with a dropdown menu.
2193 * @deprecated since Moodle 2.0
2195 function popup_form($baseurl, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
2196 $targetwindow='self', $selectlabel='', $optionsextra=NULL, $submitvalue='', $disabled=false, $showbutton=false) {
2197 throw new coding_exception('popup_form() can not be used any more, please see $OUTPUT->single_select or $OUTPUT->url_select().');
2201 * Prints a simple button to close a window
2203 * @deprecated since Moodle 2.0
2206 * @param string $name Name of the window to close
2207 * @param boolean $return whether this function should return a string or output it.
2208 * @param boolean $reloadopener if true, clicking the button will also reload
2209 * the page that opend this popup window.
2210 * @return string|void if $return is true, void otherwise
2212 function close_window_button($name='closewindow', $return=false, $reloadopener = false) {
2215 debugging('close_window_button() has been deprecated. Please change your code to use $OUTPUT->close_window_button().');
2216 $output = $OUTPUT->close_window_button(get_string($name));
2226 * Given an array of values, creates a group of radio buttons to be part of a form
2228 * @deprecated since Moodle 2.0
2230 * @staticvar int $idcounter
2231 * @param array $options An array of value-label pairs for the radio group (values as keys)
2232 * @param string $name Name of the radiogroup (unique in the form)
2233 * @param string $checked The value that is already checked
2234 * @param bool $return Whether this function should return a string or output
2235 * it (defaults to false)
2236 * @return string|void If $return=true returns string, else echo's and returns void
2238 function choose_from_radio ($options, $name, $checked='', $return=false) {
2239 debugging('choose_from_radio() has been removed. Please change your code to use html_writer.');
2243 * Display an standard html checkbox with an optional label
2245 * @deprecated since Moodle 2.0
2247 * @staticvar int $idcounter
2248 * @param string $name The name of the checkbox
2249 * @param string $value The valus that the checkbox will pass when checked
2250 * @param bool $checked The flag to tell the checkbox initial state
2251 * @param string $label The label to be showed near the checkbox
2252 * @param string $alt The info to be inserted in the alt tag
2253 * @param string $script If not '', then this is added to the checkbox element
2254 * as an onchange handler.
2255 * @param bool $return Whether this function should return a string or output
2256 * it (defaults to false)
2257 * @return string|void If $return=true returns string, else echo's and returns void
2259 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
2261 // debugging('print_checkbox() has been deprecated. Please change your code to use html_writer::checkbox().');
2264 if (!empty($script)) {
2265 debugging('The use of the $script param in print_checkbox has not been migrated into html_writer::checkbox().', DEBUG_DEVELOPER);
2268 $output = html_writer::checkbox($name, $value, $checked, $label);
2270 if (empty($return)) {
2280 * Display an standard html text field with an optional label
2282 * @deprecated since Moodle 2.0
2284 * @param string $name The name of the text field
2285 * @param string $value The value of the text field
2286 * @param string $alt The info to be inserted in the alt tag
2287 * @param int $size Sets the size attribute of the field. Defaults to 50
2288 * @param int $maxlength Sets the maxlength attribute of the field. Not set by default
2289 * @param bool $return Whether this function should return a string or output
2290 * it (defaults to false)
2291 * @return string|void If $return=true returns string, else echo's and returns void
2293 function print_textfield($name, $value, $alt = '', $size=50, $maxlength=0, $return=false) {
2294 debugging('print_textfield() has been deprecated. Please use mforms or html_writer.');
2300 $style = "width: {$size}px;";
2301 $attributes = array('type'=>'text', 'name'=>$name, 'alt'=>$alt, 'style'=>$style, 'value'=>$value);
2303 $attributes['maxlength'] = $maxlength;
2306 $output = html_writer::empty_tag('input', $attributes);
2308 if (empty($return)) {
2317 * Centered heading with attached help button (same title text)
2318 * and optional icon attached
2320 * @deprecated since Moodle 2.0
2322 * @param string $text The text to be displayed
2323 * @param string $helppage The help page to link to
2324 * @param string $module The module whose help should be linked to
2325 * @param string $icon Image to display if needed
2326 * @param bool $return If set to true output is returned rather than echoed, default false
2327 * @return string|void String if return=true nothing otherwise
2329 function print_heading_with_help($text, $helppage, $module='moodle', $icon=false, $return=false) {
2331 debugging('print_heading_with_help() has been deprecated. Please change your code to use $OUTPUT->heading().');
2335 // Extract the src from $icon if it exists
2336 if (preg_match('/src="([^"]*)"/', $icon, $matches)) {
2337 $icon = $matches[1];
2338 $icon = new moodle_url($icon);
2343 $output = $OUTPUT->heading_with_help($text, $helppage, $module, $icon);
2353 * Returns a turn edit on/off button for tag in a self contained form.
2354 * @deprecated since Moodle 2.0
2355 * @param string $tagid The ID attribute
2358 function update_tag_button($tagid) {
2360 debugging('update_tag_button() has been deprecated. Please change your code to use $OUTPUT->edit_button(moodle_url).');
2361 return $OUTPUT->edit_button(new moodle_url('/tag/index.php', array('id' => $tagid)));
2366 * Prints the 'update this xxx' button that appears on module pages.
2368 * @deprecated since Moodle 2.0
2370 * @param string $cmid the course_module id.
2371 * @param string $ignored not used any more. (Used to be courseid.)
2372 * @param string $string the module name - get_string('modulename', 'xxx')
2373 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
2375 function update_module_button($cmid, $ignored, $string) {
2376 global $CFG, $OUTPUT;
2378 // debugging('update_module_button() has been deprecated. Please change your code to use $OUTPUT->update_module_button().');
2380 //NOTE: DO NOT call new output method because it needs the module name we do not have here!
2382 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
2383 $string = get_string('updatethis', '', $string);
2385 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
2386 return $OUTPUT->single_button($url, $string);
2393 * Returns a turn edit on/off button for course in a self contained form.
2394 * Used to be an icon, but it's now a simple form button
2396 * Note that the caller is responsible for capchecks.
2400 * @param int $courseid The course to update by id as found in 'course' table
2403 function update_course_icon($courseid) {
2404 global $CFG, $OUTPUT;
2406 debugging('update_course_button() has been deprecated. Please change your code to use $OUTPUT->edit_button(moodle_url).');
2408 return $OUTPUT->edit_button(new moodle_url('/course/view.php', array('id' => $courseid)));
2412 * Prints breadcrumb trail of links, called in theme/-/header.html
2414 * This function has now been deprecated please use output's navbar method instead
2418 * echo $OUTPUT->navbar();
2421 * @deprecated since 2.0
2422 * @param mixed $navigation deprecated
2423 * @param string $separator OBSOLETE, and now deprecated
2424 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
2425 * @return string|void String or null, depending on $return.
2427 function print_navigation ($navigation, $separator=0, $return=false) {
2428 global $OUTPUT,$PAGE;
2430 # debugging('print_navigation has been deprecated please update your theme to use $OUTPUT->navbar() instead', DEBUG_DEVELOPER);
2432 $output = $OUTPUT->navbar();
2442 * This function will build the navigation string to be used by print_header
2445 * It automatically generates the site and course level (if appropriate) links.
2447 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
2448 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
2450 * If you want to add any further navigation links after the ones this function generates,
2451 * the pass an array of extra link arrays like this:
2453 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
2454 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
2456 * The normal case is to just add one further link, for example 'Editing forum' after
2457 * 'General Developer Forum', with no link.
2458 * To do that, you need to pass
2459 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
2460 * However, becuase this is a very common case, you can use a shortcut syntax, and just
2461 * pass the string 'Editing forum', instead of an array as $extranavlinks.
2463 * At the moment, the link types only have limited significance. Type 'activity' is
2464 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
2465 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
2466 * This really needs to be documented better. In the mean time, try to be consistent, it will
2467 * enable people to customise the navigation more in future.
2469 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
2470 * If you get the $cm object using the function get_coursemodule_from_instance or
2471 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
2472 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
2473 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
2474 * warning is printed in developer debug mode.
2476 * @deprecated since 2.0
2477 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
2478 * only want one extra item with no link, you can pass a string instead. If you don't want
2479 * any extra links, pass an empty string.
2480 * @param mixed $cm deprecated
2481 * @return array Navigation array
2483 function build_navigation($extranavlinks, $cm = null) {
2484 global $CFG, $COURSE, $DB, $SITE, $PAGE;
2486 if (is_array($extranavlinks) && count($extranavlinks)>0) {
2487 # debugging('build_navigation() has been deprecated, please replace with $PAGE->navbar methods', DEBUG_DEVELOPER);
2488 foreach ($extranavlinks as $nav) {
2489 if (array_key_exists('name', $nav)) {
2490 if (array_key_exists('link', $nav) && !empty($nav['link'])) {
2491 $link = $nav['link'];
2495 $PAGE->navbar->add($nav['name'],$link);
2500 return(array('newnav' => true, 'navlinks' => array()));
2504 * Returns a small popup menu of course activity modules
2506 * Given a course and a (current) coursemodule
2507 * his function returns a small popup menu with all the
2508 * course activity modules in it, as a navigation menu
2509 * The data is taken from the serialised array stored in
2516 * @uses CONTEXT_COURSE
2517 * @param object $course A {@link $COURSE} object.
2518 * @param object $cm A {@link $COURSE} object.
2519 * @param string $targetwindow The target window attribute to us
2522 function navmenu($course, $cm=NULL, $targetwindow='self') {
2523 // This function has been deprecated with the creation of the global nav in
2530 * Returns a little popup menu for switching roles
2532 * @deprecated in Moodle 2.0
2533 * @param int $courseid The course to update by id as found in 'course' table
2536 function switchroles_form($courseid) {
2537 debugging('switchroles_form() has been deprecated and replaced by an item in the global settings block');
2542 * Print header for admin page
2543 * @deprecated since Moodle 20. Please use normal $OUTPUT->header() instead
2544 * @param string $focus focus element
2546 function admin_externalpage_print_header($focus='') {
2549 debugging('admin_externalpage_print_header is deprecated. Please $OUTPUT->header() instead.', DEBUG_DEVELOPER);
2551 echo $OUTPUT->header();
2555 * @deprecated since Moodle 1.9. Please use normal $OUTPUT->footer() instead
2557 function admin_externalpage_print_footer() {
2558 // TODO Still 103 referernces in core code. Don't do debugging output yet.
2559 debugging('admin_externalpage_print_footer is deprecated. Please $OUTPUT->footer() instead.', DEBUG_DEVELOPER);
2561 echo $OUTPUT->footer();
2564 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
2568 * Call this function to add an event to the calendar table and to call any calendar plugins
2570 * @param object $event An object representing an event from the calendar table.
2571 * The event will be identified by the id field. The object event should include the following:
2573 * <li><b>$event->name</b> - Name for the event
2574 * <li><b>$event->description</b> - Description of the event (defaults to '')
2575 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
2576 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
2577 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
2578 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
2579 * <li><b>$event->modulename</b> - Name of the module that creates this event
2580 * <li><b>$event->instance</b> - Instance of the module that owns this event
2581 * <li><b>$event->eventtype</b> - The type info together with the module info could
2582 * be used by calendar plugins to decide how to display event
2583 * <li><b>$event->timestart</b>- Timestamp for start of event
2584 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
2585 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
2587 * @return int|false The id number of the resulting record or false if failed
2589 function add_event($event) {
2591 require_once($CFG->dirroot.'/calendar/lib.php');
2592 $event = calendar_event::create($event);
2593 if ($event !== false) {
2600 * Call this function to update an event in the calendar table
2601 * the event will be identified by the id field of the $event object.
2603 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
2604 * @return bool Success
2606 function update_event($event) {
2608 require_once($CFG->dirroot.'/calendar/lib.php');
2609 $event = (object)$event;
2610 $calendarevent = calendar_event::load($event->id);
2611 return $calendarevent->update($event);
2615 * Call this function to delete the event with id $id from calendar table.
2617 * @param int $id The id of an event from the 'event' table.
2620 function delete_event($id) {
2622 require_once($CFG->dirroot.'/calendar/lib.php');
2623 $event = calendar_event::load($id);
2624 return $event->delete();
2628 * Call this function to hide an event in the calendar table
2629 * the event will be identified by the id field of the $event object.
2631 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
2634 function hide_event($event) {
2636 require_once($CFG->dirroot.'/calendar/lib.php');
2637 $event = new calendar_event($event);
2638 return $event->toggle_visibility(false);
2642 * Call this function to unhide an event in the calendar table
2643 * the event will be identified by the id field of the $event object.
2645 * @param object $event An object representing an event from the calendar table. The event will be identified by the id field.
2648 function show_event($event) {
2650 require_once($CFG->dirroot.'/calendar/lib.php');
2651 $event = new calendar_event($event);
2652 return $event->toggle_visibility(true);
2656 * @deprecated Use textlib::strtolower($text) instead.
2658 function moodle_strtolower($string, $encoding='') {
2659 throw new coding_exception('moodle_strtolower() cannot be used any more. Please use textlib::strtolower() instead.');
2663 * Original singleton helper function, please use static methods instead,
2664 * ex: textlib::convert()
2666 * @deprecated since Moodle 2.2 use textlib::xxxx() instead
2668 * @return textlib instance
2670 function textlib_get_instance() {
2672 debugging('textlib_get_instance() is deprecated. Please use static calling textlib::functioname() instead.', DEBUG_DEVELOPER);
2674 return new textlib();
2678 * Gets the generic section name for a courses section
2680 * The global function is deprecated. Each course format can define their own generic section name
2682 * @deprecated since 2.4
2683 * @see get_section_name()
2684 * @see format_base::get_section_name()
2686 * @param string $format Course format ID e.g. 'weeks' $course->format
2687 * @param stdClass $section Section object from database
2688 * @return Display name that the course format prefers, e.g. "Week 2"
2690 function get_generic_section_name($format, stdClass $section) {
2691 debugging('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base', DEBUG_DEVELOPER);
2692 return get_string('sectionname', "format_$format") . ' ' . $section->section;
2696 * Returns an array of sections for the requested course id
2698 * It is usually not recommended to display the list of sections used
2699 * in course because the course format may have it's own way to do it.
2701 * If you need to just display the name of the section please call:
2702 * get_section_name($course, $section)
2703 * {@link get_section_name()}
2704 * from 2.4 $section may also be just the field course_sections.section
2706 * If you need the list of all sections it is more efficient to get this data by calling
2707 * $modinfo = get_fast_modinfo($courseorid);
2708 * $sections = $modinfo->get_section_info_all()
2709 * {@link get_fast_modinfo()}
2710 * {@link course_modinfo::get_section_info_all()}
2712 * Information about one section (instance of section_info):
2713 * get_fast_modinfo($courseorid)->get_sections_info($section)
2714 * {@link course_modinfo::get_section_info()}
2716 * @deprecated since 2.4
2718 * @param int $courseid
2719 * @return array Array of section_info objects
2721 function get_all_sections($courseid) {
2723 debugging('get_all_sections() is deprecated. See phpdocs for this function', DEBUG_DEVELOPER);
2724 return get_fast_modinfo($courseid)->get_section_info_all();
2728 * Given a full mod object with section and course already defined, adds this module to that section.
2730 * This function is deprecated, please use {@link course_add_cm_to_section()}
2731 * Note that course_add_cm_to_section() also updates field course_modules.section and
2732 * calls rebuild_course_cache()
2734 * @deprecated since 2.4
2736 * @param object $mod
2737 * @param int $beforemod An existing ID which we will insert the new module before
2738 * @return int The course_sections ID where the mod is inserted
2740 function add_mod_to_section($mod, $beforemod = null) {
2741 debugging('Function add_mod_to_section() is deprecated, please use course_add_cm_to_section()', DEBUG_DEVELOPER);
2743 return course_add_cm_to_section($mod->course, $mod->coursemodule, $mod->section, $beforemod);
2747 * Returns a number of useful structures for course displays
2749 * Function get_all_mods() is deprecated in 2.4
2752 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
2756 * $mods = get_fast_modinfo($courseorid)->get_cms();
2757 * $modnames = get_module_types_names();
2758 * $modnamesplural = get_module_types_names(true);
2759 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
2762 * @deprecated since 2.4
2764 * @param int $courseid id of the course to get info about
2765 * @param array $mods (return) list of course modules
2766 * @param array $modnames (return) list of names of all module types installed and available
2767 * @param array $modnamesplural (return) list of names of all module types installed and available in the plural form
2768 * @param array $modnamesused (return) list of names of all module types used in the course
2770 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
2771 debugging('Function get_all_mods() is deprecated. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details', DEBUG_DEVELOPER);
2774 $modnames = get_module_types_names();
2775 $modnamesplural= get_module_types_names(true);
2776 $modinfo = get_fast_modinfo($courseid);
2777 $mods = $modinfo->get_cms();
2778 $modnamesused = $modinfo->get_used_module_names();
2782 * Returns course section - creates new if does not exist yet
2784 * This function is deprecated. To create a course section call:
2785 * course_create_sections_if_missing($courseorid, $sections);
2786 * to get the section call:
2787 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
2789 * @see course_create_sections_if_missing()
2790 * @see get_fast_modinfo()
2791 * @deprecated since 2.4
2793 * @param int $section relative section number (field course_sections.section)
2794 * @param int $courseid
2795 * @return stdClass record from table {course_sections}
2797 function get_course_section($section, $courseid) {
2799 debugging('Function get_course_section() is deprecated. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.', DEBUG_DEVELOPER);
2801 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2804 $cw = new stdClass();
2805 $cw->course = $courseid;
2806 $cw->section = $section;
2808 $cw->summaryformat = FORMAT_HTML;
2810 $id = $DB->insert_record("course_sections", $cw);
2811 rebuild_course_cache($courseid, true);
2812 return $DB->get_record("course_sections", array("id"=>$id));
2816 * Return the start and end date of the week in Weekly course format
2818 * It is not recommended to use this function outside of format_weeks plugin
2820 * @deprecated since 2.4
2821 * @see format_weeks::get_section_dates()
2823 * @param stdClass $section The course_section entry from the DB
2824 * @param stdClass $course The course entry from DB
2825 * @return stdClass property start for startdate, property end for enddate
2827 function format_weeks_get_section_dates($section, $course) {
2828 debugging('Function format_weeks_get_section_dates() is deprecated. It is not recommended to'.
2829 ' use it outside of format_weeks plugin', DEBUG_DEVELOPER);
2830 if (isset($course->format) && $course->format === 'weeks') {
2831 return course_get_format($course)->get_section_dates($section);
2837 * Obtains shared data that is used in print_section when displaying a
2838 * course-module entry.
2840 * Deprecated. Instead of:
2841 * list($content, $name) = get_print_section_cm_text($cm, $course);
2843 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
2844 * $name = $cm->get_formatted_name();
2846 * @deprecated since 2.5
2847 * @see cm_info::get_formatted_content()
2848 * @see cm_info::get_formatted_name()
2850 * This data is also used in other areas of the code.
2851 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
2852 * @param object $course (argument not used)
2853 * @return array An array with the following values in this order:
2854 * $content (optional extra content for after link),
2855 * $instancename (text of link)
2857 function get_print_section_cm_text(cm_info $cm, $course) {
2858 debugging('Function get_print_section_cm_text() is deprecated. Please use '.
2859 'cm_info::get_formatted_content() and cm_info::get_formatted_name()',
2861 return array($cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true)),
2862 $cm->get_formatted_name());
2866 * Prints the menus to add activities and resources.
2868 * Deprecated. Please use:
2869 * $courserenderer = $PAGE->get_renderer('core', 'course');
2870 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
2871 * array('inblock' => $vertical));
2872 * echo $output; // if $return argument in print_section_add_menus() set to false
2874 * @deprecated since 2.5
2875 * @see core_course_renderer::course_section_add_cm_control()
2877 * @param stdClass $course course object, must be the same as set on the page
2878 * @param int $section relative section number (field course_sections.section)
2879 * @param null|array $modnames (argument ignored) get_module_types_names() is used instead of argument
2880 * @param bool $vertical Vertical orientation
2881 * @param bool $return Return the menus or send them to output
2882 * @param int $sectionreturn The section to link back to
2883 * @return void|string depending on $return
2885 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
2887 debugging('Function print_section_add_menus() is deprecated. Please use course renderer '.
2888 'function course_section_add_cm_control()', DEBUG_DEVELOPER);
2890 $courserenderer = $PAGE->get_renderer('core', 'course');
2891 $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
2892 array('inblock' => $vertical));
2897 return !empty($output);
2902 * Produces the editing buttons for a module
2904 * Deprecated. Please use:
2905 * $courserenderer = $PAGE->get_renderer('core', 'course');
2906 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
2907 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
2909 * @deprecated since 2.5
2910 * @see course_get_cm_edit_actions()
2911 * @see core_course_renderer->course_section_cm_edit_actions()
2913 * @param stdClass $mod The module to produce editing buttons for
2914 * @param bool $absolute_ignored (argument ignored) - all links are absolute
2915 * @param bool $moveselect (argument ignored)
2916 * @param int $indent The current indenting
2917 * @param int $section The section to link back to
2918 * @return string XHTML for the editing buttons
2920 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
2922 debugging('Function make_editing_buttons() is deprecated, please see PHPdocs in '.
2923 'lib/deprecatedlib.php on how to replace it', DEBUG_DEVELOPER);
2924 if (!($mod instanceof cm_info)) {
2925 $modinfo = get_fast_modinfo($mod->course);
2926 $mod = $modinfo->get_cm($mod->id);
2928 $actions = course_get_cm_edit_actions($mod, $indent, $section);
2930 $courserenderer = $PAGE->get_renderer('core', 'course');
2931 // The space added before the <span> is a ugly hack but required to set the CSS property white-space: nowrap
2932 // and having it to work without attaching the preceding text along with it. Hopefully the refactoring of
2933 // the course page HTML will allow this to be removed.
2934 return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
2938 * Prints a section full of activity modules
2940 * Deprecated. Please use:
2941 * $courserenderer = $PAGE->get_renderer('core', 'course');
2942 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
2943 * array('hidecompletion' => $hidecompletion));
2945 * @deprecated since 2.5
2946 * @see core_course_renderer::course_section_cm_list()
2948 * @param stdClass $course The course
2949 * @param stdClass|section_info $section The section object containing properties id and section
2950 * @param array $mods (argument not used)
2951 * @param array $modnamesused (argument not used)
2952 * @param bool $absolute (argument not used)
2953 * @param string $width (argument not used)
2954 * @param bool $hidecompletion Hide completion status
2955 * @param int $sectionreturn The section to return to
2958 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
2960 debugging('Function print_section() is deprecated. Please use course renderer function '.
2961 'course_section_cm_list() instead.', DEBUG_DEVELOPER);
2962 $displayoptions = array('hidecompletion' => $hidecompletion);
2963 $courserenderer = $PAGE->get_renderer('core', 'course');
2964 echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn, $displayoptions);
2968 * Displays the list of courses with user notes
2970 * This function is not used in core. It was replaced by block course_overview
2972 * @deprecated since 2.5
2974 * @param array $courses
2975 * @param array $remote_courses
2977 function print_overview($courses, array $remote_courses=array()) {
2978 global $CFG, $USER, $DB, $OUTPUT;
2979 debugging('Function print_overview() is deprecated. Use block course_overview to display this information', DEBUG_DEVELOPER);
2981 $htmlarray = array();
2982 if ($modules = $DB->get_records('modules')) {
2983 foreach ($modules as $mod) {
2984 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
2985 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
2986 $fname = $mod->name.'_print_overview';
2987 if (function_exists($fname)) {
2988 $fname($courses,$htmlarray);
2993 foreach ($courses as $course) {
2994 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2995 echo $OUTPUT->box_start('coursebox');
2996 $attributes = array('title' => s($fullname));
2997 if (empty($course->visible)) {
2998 $attributes['class'] = 'dimmed';
3000 echo $OUTPUT->heading(html_writer::link(
3001 new moodle_url('/course/view.php', array('id' => $course->id)), $fullname, $attributes), 3);
3002 if (array_key_exists($course->id,$htmlarray)) {
3003 foreach ($htmlarray[$course->id] as $modname => $html) {
3007 echo $OUTPUT->box_end();
3010 if (!empty($remote_courses)) {
3011 echo $OUTPUT->heading(get_string('remotecourses', 'mnet'));
3013 foreach ($remote_courses as $course) {
3014 echo $OUTPUT->box_start('coursebox');
3015 $attributes = array('title' => s($course->fullname));
3016 echo $OUTPUT->heading(html_writer::link(
3017 new moodle_url('/auth/mnet/jump.php', array('hostid' => $course->hostid, 'wantsurl' => '/course/view.php?id='.$course->remoteid)),
3018 format_string($course->shortname),
3019 $attributes) . ' (' . format_string($course->hostname) . ')', 3);
3020 echo $OUTPUT->box_end();
3025 * This function trawls through the logs looking for
3026 * anything new since the user's last login
3028 * This function was only used to print the content of block recent_activity
3029 * All functionality is moved into class {@link block_recent_activity}
3030 * and renderer {@link block_recent_activity_renderer}
3032 * @deprecated since 2.5
3033 * @param stdClass $course
3035 function print_recent_activity($course) {
3036 // $course is an object
3037 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
3038 debugging('Function print_recent_activity() is deprecated. It is not recommended to'.
3039 ' use it outside of block_recent_activity', DEBUG_DEVELOPER);
3041 $context = context_course::instance($course->id);
3043 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
3045 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
3047 if (!isguestuser()) {
3048 if (!empty($USER->lastcourseaccess[$course->id])) {
3049 if ($USER->lastcourseaccess[$course->id] > $timestart) {
3050 $timestart = $USER->lastcourseaccess[$course->id];
3055 echo '<div class="activitydate">';
3056 echo get_string('activitysince', '', userdate($timestart));
3058 echo '<div class="activityhead">';
3060 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
3066 /// Firstly, have there been any new enrolments?
3068 $users = get_recent_enrolments($course->id, $timestart);
3070 //Accessibility: new users now appear in an <OL> list.
3072 echo '<div class="newusers">';
3073 echo $OUTPUT->heading(get_string("newusers").':', 3);
3075 echo "<ol class=\"list\">\n";
3076 foreach ($users as $user) {
3077 $fullname = fullname($user, $viewfullnames);
3078 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
3080 echo "</ol>\n</div>\n";
3083 /// Next, have there been any modifications to the course structure?
3085 $modinfo = get_fast_modinfo($course);
3087 $changelist = array();
3089 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
3090 module = 'course' AND
3091 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
3092 array($timestart, $course->id), "id ASC");
3095 $actions = array('add mod', 'update mod', 'delete mod');
3096 $newgones = array(); // added and later deleted items
3097 foreach ($logs as $key => $log) {
3098 if (!in_array($log->action, $actions)) {
3101 $info = explode(' ', $log->info);
3103 // note: in most cases I replaced hardcoding of label with use of
3104 // $cm->has_view() but it was not possible to do this here because
3105 // we don't necessarily have the $cm for it
3106 if ($info[0] == 'label') { // Labels are ignored in recent activity
3110 if (count($info) != 2) {
3111 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
3115 $modname = $info[0];
3116 $instanceid = $info[1];
3118 if ($log->action == 'delete mod') {
3119 // unfortunately we do not know if the mod was visible
3120 if (!array_key_exists($log->info, $newgones)) {
3121 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
3122 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
3125 if (!isset($modinfo->instances[$modname][$instanceid])) {
3126 if ($log->action == 'add mod') {
3127 // do not display added and later deleted activities
3128 $newgones[$log->info] = true;
3132 $cm = $modinfo->instances[$modname][$instanceid];
3133 if (!$cm->uservisible) {
3137 if ($log->action == 'add mod') {
3138 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
3139 $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>");
3141 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
3142 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
3143 $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>");
3149 if (!empty($changelist)) {
3150 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
3152 foreach ($changelist as $changeinfo => $change) {
3153 echo '<p class="activity">'.$change['text'].'</p>';
3157 /// Now display new things from each module
3159 $usedmodules = array();
3160 foreach($modinfo->cms as $cm) {
3161 if (isset($usedmodules[$cm->modname])) {
3164 if (!$cm->uservisible) {
3167 $usedmodules[$cm->modname] = $cm->modname;
3170 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
3171 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
3172 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
3173 $print_recent_activity = $modname.'_print_recent_activity';
3174 if (function_exists($print_recent_activity)) {
3175 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
3176 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
3179 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
3184 echo '<p class="message">'.get_string('nothingnew').'</p>';
3189 * Delete a course module and any associated data at the course level (events)
3190 * Until 1.5 this function simply marked a deleted flag ... now it
3191 * deletes it completely.
3193 * @deprecated since 2.5
3195 * @param int $id the course module id
3196 * @return boolean true on success, false on failure
3198 function delete_course_module($id) {
3199 debugging('Function delete_course_module() is deprecated. Please use course_delete_module() instead.', DEBUG_DEVELOPER);
3203 require_once($CFG->libdir.'/gradelib.php');
3204 require_once($CFG->dirroot.'/blog/lib.php');
3206 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
3209 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
3210 //delete events from calendar
3211 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
3212 foreach($events as $event) {
3213 delete_event($event->id);
3216 //delete grade items, outcome items and grades attached to modules
3217 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
3218 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
3219 foreach ($grade_items as $grade_item) {
3220 $grade_item->delete('moddelete');
3223 // Delete completion and availability data; it is better to do this even if the
3224 // features are not turned on, in case they were turned on previously (these will be
3225 // very quick on an empty table)
3226 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
3227 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
3228 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
3229 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
3231 delete_context(CONTEXT_MODULE, $cm->id);
3232 return $DB->delete_records('course_modules', array('id'=>$cm->id));
3236 * Prints the turn editing on/off button on course/index.php or course/category.php.
3238 * @deprecated since 2.5
3240 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
3241 * @return string HTML of the editing button, or empty string, if this user is not allowed
3244 function update_category_button($categoryid = 0) {
3245 global $CFG, $PAGE, $OUTPUT;
3246 debugging('Function update_category_button() is deprecated. Pages to view '.
3247 'and edit courses are now separate and no longer depend on editing mode.',
3250 // Check permissions.
3251 if (!can_edit_in_category($categoryid)) {
3255 // Work out the appropriate action.
3256 if ($PAGE->user_is_editing()) {
3257 $label = get_string('turneditingoff');
3260 $label = get_string('turneditingon');
3264 // Generate the button HTML.
3265 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
3267 $options['id'] = $categoryid;
3268 $page = 'category.php';
3270 $page = 'index.php';
3272 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
3276 * This function recursively travels the categories, building up a nice list
3277 * for display. It also makes an array that list all the parents for each
3280 * For example, if you have a tree of categories like:
3281 * Miscellaneous (id = 1)
3282 * Subcategory (id = 2)
3283 * Sub-subcategory (id = 4)
3284 * Other category (id = 3)
3285 * Then after calling this function you will have
3286 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
3287 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
3288 * 3 => 'Other category');
3289 * $parents = array(2 => array(1), 4 => array(1, 2));
3291 * If you specify $requiredcapability, then only categories where the current
3292 * user has that capability will be added to $list, although all categories
3293 * will still be added to $parents, and if you only have $requiredcapability
3294 * in a child category, not the parent, then the child catgegory will still be
3297 * If you specify the option $excluded, then that category, and all its children,
3298 * are omitted from the tree. This is useful when you are doing something like
3299 * moving categories, where you do not want to allow people to move a category
3300 * to be the child of itself.
3302 * This function is deprecated! For list of categories use
3303 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
3304 * For parents of one particular category use
3305 * coursecat::get($id)->get_parents()
3307 * @deprecated since 2.5
3309 * @param array $list For output, accumulates an array categoryid => full category path name
3310 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
3311 * @param string/array $requiredcapability if given, only categories where the current
3312 * user has this capability will be added to $list. Can also be an array of capabilities,
3313 * in which case they are all required.
3314 * @param integer $excludeid Omit this category and its children from the lists built.
3315 * @param object $category Not used
3316 * @param string $path Not used
3318 function make_categories_list(&$list, &$parents, $requiredcapability = '',
3319 $excludeid = 0, $category = NULL, $path = "") {
3321 require_once($CFG->libdir.'/coursecatlib.php');
3323 debugging('Global function make_categories_list() is deprecated. Please use '.
3324 'coursecat::make_categories_list() and coursecat::get_parents()',
3327 // For categories list use just this one function:
3331 $list += coursecat::make_categories_list($requiredcapability, $excludeid);
3333 // Building the list of all parents of all categories in the system is highly undesirable and hardly ever needed.
3334 // Usually user needs only parents for one particular category, in which case should be used:
3335 // coursecat::get($categoryid)->get_parents()
3336 if (empty($parents)) {
3339 $all = $DB->get_records_sql('SELECT id, parent FROM {course_categories} ORDER BY sortorder');
3340 foreach ($all as $record) {
3341 if ($record->parent) {
3342 $parents[$record->id] = array_merge($parents[$record->parent], array($record->parent));
3344 $parents[$record->id] = array();
3350 * Delete category, but move contents to another category.
3352 * This function is deprecated. Please use
3353 * coursecat::get($category->id)->delete_move($newparentid, $showfeedback);
3355 * @see coursecat::delete_move()
3356 * @deprecated since 2.5
3358 * @param object $category
3359 * @param int $newparentid category id
3360 * @return bool status
3362 function category_delete_move($category, $newparentid, $showfeedback=true) {
3364 require_once($CFG->libdir.'/coursecatlib.php');
3366 debugging('Function category_delete_move() is deprecated. Please use coursecat::delete_move() instead.');
3368 return coursecat::get($category->id)->delete_move($newparentid, $showfeedback);
3372 * Recursively delete category including all subcategories and courses.
3374 * This function is deprecated. Please use
3375 * coursecat::get($category->id)->delete_full($showfeedback);
3377 * @see coursecat::delete_full()
3378 * @deprecated since 2.5
3380 * @param stdClass $category
3381 * @param boolean $showfeedback display some notices
3382 * @return array return deleted courses
3384 function category_delete_full($category, $showfeedback=true) {
3386 require_once($CFG->libdir.'/coursecatlib.php');
3388 debugging('Function category_delete_full() is deprecated. Please use coursecat::delete_full() instead.');
3390 return coursecat::get($category->id)->delete_full($showfeedback);
3394 * Efficiently moves a category - NOTE that this can have
3395 * a huge impact access-control-wise...
3397 * This function is deprecated. Please use
3398 * $coursecat = coursecat::get($category->id);
3399 * if ($coursecat->can_change_parent($newparentcat->id)) {
3400 * $coursecat->change_parent($newparentcat->id);
3403 * Alternatively you can use
3404 * $coursecat->update(array('parent' => $newparentcat->id));
3406 * Function update() also updates field course_categories.timemodified
3408 * @see coursecat::change_parent()
3409 * @see coursecat::update()
3410 * @deprecated since 2.5
3412 * @param stdClass|coursecat $category
3413 * @param stdClass|coursecat $newparentcat
3415 function move_category($category, $newparentcat) {
3417 require_once($CFG->libdir.'/coursecatlib.php');
3419 debugging('Function move_category() is deprecated. Please use coursecat::change_parent() instead.');
3421 return coursecat::get($category->id)->change_parent($newparentcat->id);
3425 * Hide course category and child course and subcategories
3427 * This function is deprecated. Please use
3428 * coursecat::get($category->id)->hide();
3430 * @see coursecat::hide()
3431 * @deprecated since 2.5
3433 * @param stdClass $category
3436 function course_category_hide($category) {
3438 require_once($CFG->libdir.'/coursecatlib.php');
3440 debugging('Function course_category_hide() is deprecated. Please use coursecat::hide() instead.');
3442 coursecat::get($category->id)->hide();
3446 * Show course category and child course and subcategories
3448 * This function is deprecated. Please use
3449 * coursecat::get($category->id)->show();
3451 * @see coursecat::show()
3452 * @deprecated since 2.5
3454 * @param stdClass $category
3457 function course_category_show($category) {
3459 require_once($CFG->libdir.'/coursecatlib.php');
3461 debugging('Function course_category_show() is deprecated. Please use coursecat::show() instead.');
3463 coursecat::get($category->id)->show();
3467 * Return specified category, default if given does not exist
3469 * This function is deprecated.
3470 * To get the category with the specified it please use:
3471 * coursecat::get($catid, IGNORE_MISSING);
3473 * coursecat::get($catid, MUST_EXIST);
3475 * To get the first available category please use
3476 * coursecat::get_default();
3478 * class coursecat will also make sure that at least one category exists in DB
3480 * @deprecated since 2.5
3481 * @see coursecat::get()
3482 * @see coursecat::get_default()
3484 * @param int $catid course category id
3485 * @return object caregory
3487 function get_course_category($catid=0) {
3490 debugging('Function get_course_category() is deprecated. Please use coursecat::get(), see phpdocs for more details');
3494 if (!empty($catid)) {
3495 $category = $DB->get_record('course_categories', array('id'=>$catid));
3499 // the first category is considered default for now
3500 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
3501 $category = reset($category);
3504 $cat = new stdClass();
3505 $cat->name = get_string('miscellaneous');
3507 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
3508 $cat->timemodified = time();
3509 $catid = $DB->insert_record('course_categories', $cat);
3510 // make sure category context exists
3511 context_coursecat::instance($catid);
3512 mark_context_dirty('/'.SYSCONTEXTID);
3513 fix_course_sortorder(); // Required to build course_categories.depth and .path.
3514 $category = $DB->get_record('course_categories', array('id'=>$catid));
3522 * Create a new course category and marks the context as dirty
3524 * This function does not set the sortorder for the new category and
3525 * {@link fix_course_sortorder()} should be called after creating a new course
3528 * Please note that this function does not verify access control.
3530 * This function is deprecated. It is replaced with the method create() in class coursecat.
3531 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
3533 * @deprecated since 2.5
3535 * @param object $category All of the data required for an entry in the course_categories table
3536 * @return object new course category
3538 function create_course_category($category) {
3541 debugging('Function create_course_category() is deprecated. Please use coursecat::create(), see phpdocs for more details', DEBUG_DEVELOPER);
3543 $category->timemodified = time();
3544 $category->id = $DB->insert_record('course_categories', $category);
3545 $category = $DB->get_record('course_categories', array('id' => $category->id));
3547 // We should mark the context as dirty
3548 $category->context = context_coursecat::instance($category->id);
3549 $category->context->mark_dirty();
3555 * Returns an array of category ids of all the subcategories for a given
3558 * This function is deprecated.
3560 * To get visible children categories of the given category use:
3561 * coursecat::get($categoryid)->get_children();
3562 * This function will return the array or coursecat objects, on each of them
3563 * you can call get_children() again
3565 * @see coursecat::get()
3566 * @see coursecat::get_children()
3568 * @deprecated since 2.5
3571 * @param int $catid - The id of the category whose subcategories we want to find.
3572 * @return array of category ids.
3574 function get_all_subcategories($catid) {
3577 debugging('Function get_all_subcategories() is deprecated. Please use appropriate methods() of coursecat class. See phpdocs for more details',
3582 if ($categories = $DB->get_records('course_categories', array('parent' => $catid))) {
3583 foreach ($categories as $cat) {
3584 array_push($subcats, $cat->id);
3585 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
3592 * Gets the child categories of a given courses category
3594 * This function is deprecated. Please use functions in class coursecat:
3595 * - coursecat::get($parentid)->has_children()
3596 * tells if the category has children (visible or not to the current user)
3598 * - coursecat::get($parentid)->get_children()
3599 * returns an array of coursecat objects, each of them represents a children category visible
3600 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
3602 * - coursecat::get($parentid)->get_children_count()
3603 * returns number of children categories visible to the current user
3605 * - coursecat::count_all()
3606 * returns total count of all categories in the system (both visible and not)
3608 * - coursecat::get_default()
3609 * returns the first category (usually to be used if count_all() == 1)
3611 * @deprecated since 2.5
3613 * @param int $parentid the id of a course category.
3614 * @return array all the child course categories.
3616 function get_child_categories($parentid) {
3618 debugging('Function get_child_categories() is deprecated. Use coursecat::get_children() or see phpdocs for more details.',
3622 $sql = context_helper::get_preload_record_columns_sql('ctx');
3623 $records = $DB->get_records_sql("SELECT c.*, $sql FROM {course_categories} c ".
3624 "JOIN {context} ctx on ctx.instanceid = c.id AND ctx.contextlevel = ? WHERE c.parent = ? ORDER BY c.sortorder",
3625 array(CONTEXT_COURSECAT, $parentid));
3626 foreach ($records as $category) {
3627 context_helper::preload_from_record($category);
3628 if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($category->id))) {
3637 * Returns a sorted list of categories.
3639 * When asking for $parent='none' it will return all the categories, regardless
3640 * of depth. Wheen asking for a specific parent, the default is to return
3641 * a "shallow" resultset. Pass false to $shallow and it will return all
3642 * the child categories as well.
3644 * @deprecated since 2.5
3646 * This function is deprecated. Use appropriate functions from class coursecat.
3649 * coursecat::get($categoryid)->get_children()
3650 * - returns all children of the specified category as instances of class
3651 * coursecat, which means on each of them method get_children() can be called again
3653 * coursecat::get($categoryid)->get_children(array('recursive' => true))
3654 * - returns all children of the specified category and all subcategories
3656 * coursecat::get(0)->get_children(array('recursive' => true))
3657 * - returns all categories defined in the system
3659 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
3661 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
3662 * {@link coursecat::get_default()}
3664 * The code of this deprecated function is left as it is because coursecat::get_children()
3665 * returns categories as instances of coursecat and not stdClass
3667 * @param string $parent The parent category if any
3668 * @param string $sort the sortorder
3669 * @param bool $shallow - set to false to get the children too
3670 * @return array of categories
3672 function get_categories($parent='none', $sort=NULL, $shallow=true) {
3675 debugging('Function get_categories() is deprecated. Please use coursecat::get_children(). See phpdocs for more details',
3678 if ($sort === NULL) {
3679 $sort = 'ORDER BY cc.sortorder ASC';
3680 } elseif ($sort ==='') {
3681 // leave it as empty
3683 $sort = "ORDER BY $sort";
3686 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
3688 if ($parent === 'none') {
3689 $sql = "SELECT cc.* $ccselect
3690 FROM {course_categories} cc
3695 } elseif ($shallow) {
3696 $sql = "SELECT cc.* $ccselect
3697 FROM {course_categories} cc
3701 $params = array($parent);
3704 $sql = "SELECT cc.* $ccselect
3705 FROM {course_categories} cc
3707 JOIN {course_categories} ccp
3708 ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
3711 $params = array($parent);
3713 $categories = array();