Merge branch 'MDL-61960-master' of git://github.com/farhan6318/moodle
[moodle.git] / lib / deprecatedlib.php
blob1c3c922b8ebd8cccc36eddfa7b0a470717186a56
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * deprecatedlib.php - Old functions retained only for backward compatibility
21 * Old functions retained only for backward compatibility. New code should not
22 * use any of these functions.
24 * @package core
25 * @subpackage deprecated
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 * @deprecated
31 defined('MOODLE_INTERNAL') || die();
33 /* === Functions that needs to be kept longer in deprecated lib than normal time period === */
35 /**
36 * Add an entry to the legacy log table.
38 * @deprecated since 2.7 use new events instead
40 * @param int $courseid The course id
41 * @param string $module The module name e.g. forum, journal, resource, course, user etc
42 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
43 * @param string $url The file and parameters used to see the results of the action
44 * @param string $info Additional description information
45 * @param int $cm The course_module->id if there is one
46 * @param int|stdClass $user If log regards $user other than $USER
47 * @return void
49 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
50 debugging('add_to_log() has been deprecated, please rewrite your code to the new events API', DEBUG_DEVELOPER);
52 // This is a nasty hack that allows us to put all the legacy stuff into legacy storage,
53 // this way we may move all the legacy settings there too.
54 $manager = get_log_manager();
55 if (method_exists($manager, 'legacy_add_to_log')) {
56 $manager->legacy_add_to_log($courseid, $module, $action, $url, $info, $cm, $user);
60 /**
61 * @deprecated since 2.6
63 function events_trigger() {
64 throw new coding_exception('events_trigger() has been deprecated along with all Events 1 API in favour of Events 2 API.');
67 /**
68 * List all core subsystems and their location
70 * This is a whitelist of components that are part of the core and their
71 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
72 * plugin is not listed here and it does not have proper plugintype prefix,
73 * then it is considered as course activity module.
75 * The location is optionally dirroot relative path. NULL means there is no special
76 * directory for this subsystem. If the location is set, the subsystem's
77 * renderer.php is expected to be there.
79 * @deprecated since 2.6, use core_component::get_core_subsystems()
81 * @param bool $fullpaths false means relative paths from dirroot, use true for performance reasons
82 * @return array of (string)name => (string|null)location
84 function get_core_subsystems($fullpaths = false) {
85 global $CFG;
87 // NOTE: do not add any other debugging here, keep forever.
89 $subsystems = core_component::get_core_subsystems();
91 if ($fullpaths) {
92 return $subsystems;
95 debugging('Short paths are deprecated when using get_core_subsystems(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
97 $dlength = strlen($CFG->dirroot);
99 foreach ($subsystems as $k => $v) {
100 if ($v === null) {
101 continue;
103 $subsystems[$k] = substr($v, $dlength+1);
106 return $subsystems;
110 * Lists all plugin types.
112 * @deprecated since 2.6, use core_component::get_plugin_types()
114 * @param bool $fullpaths false means relative paths from dirroot
115 * @return array Array of strings - name=>location
117 function get_plugin_types($fullpaths = true) {
118 global $CFG;
120 // NOTE: do not add any other debugging here, keep forever.
122 $types = core_component::get_plugin_types();
124 if ($fullpaths) {
125 return $types;
128 debugging('Short paths are deprecated when using get_plugin_types(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
130 $dlength = strlen($CFG->dirroot);
132 foreach ($types as $k => $v) {
133 if ($k === 'theme') {
134 $types[$k] = 'theme';
135 continue;
137 $types[$k] = substr($v, $dlength+1);
140 return $types;
144 * Use when listing real plugins of one type.
146 * @deprecated since 2.6, use core_component::get_plugin_list()
148 * @param string $plugintype type of plugin
149 * @return array name=>fulllocation pairs of plugins of given type
151 function get_plugin_list($plugintype) {
153 // NOTE: do not add any other debugging here, keep forever.
155 if ($plugintype === '') {
156 $plugintype = 'mod';
159 return core_component::get_plugin_list($plugintype);
163 * Get a list of all the plugins of a given type that define a certain class
164 * in a certain file. The plugin component names and class names are returned.
166 * @deprecated since 2.6, use core_component::get_plugin_list_with_class()
168 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
169 * @param string $class the part of the name of the class after the
170 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
171 * names like report_courselist_thing. If you are looking for classes with
172 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
173 * @param string $file the name of file within the plugin that defines the class.
174 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
175 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
177 function get_plugin_list_with_class($plugintype, $class, $file) {
179 // NOTE: do not add any other debugging here, keep forever.
181 return core_component::get_plugin_list_with_class($plugintype, $class, $file);
185 * Returns the exact absolute path to plugin directory.
187 * @deprecated since 2.6, use core_component::get_plugin_directory()
189 * @param string $plugintype type of plugin
190 * @param string $name name of the plugin
191 * @return string full path to plugin directory; NULL if not found
193 function get_plugin_directory($plugintype, $name) {
195 // NOTE: do not add any other debugging here, keep forever.
197 if ($plugintype === '') {
198 $plugintype = 'mod';
201 return core_component::get_plugin_directory($plugintype, $name);
205 * Normalize the component name using the "frankenstyle" names.
207 * @deprecated since 2.6, use core_component::normalize_component()
209 * @param string $component
210 * @return array two-items list of [(string)type, (string|null)name]
212 function normalize_component($component) {
214 // NOTE: do not add any other debugging here, keep forever.
216 return core_component::normalize_component($component);
220 * Return exact absolute path to a plugin directory.
222 * @deprecated since 2.6, use core_component::normalize_component()
224 * @param string $component name such as 'moodle', 'mod_forum'
225 * @return string full path to component directory; NULL if not found
227 function get_component_directory($component) {
229 // NOTE: do not add any other debugging here, keep forever.
231 return core_component::get_component_directory($component);
235 * Get the context instance as an object. This function will create the
236 * context instance if it does not exist yet.
238 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
239 * @todo This will be deleted in Moodle 2.8, refer MDL-34472
240 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
241 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
242 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
243 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
244 * MUST_EXIST means throw exception if no record or multiple records found
245 * @return context The context object.
247 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
249 debugging('get_context_instance() is deprecated, please use context_xxxx::instance() instead.', DEBUG_DEVELOPER);
251 $instances = (array)$instance;
252 $contexts = array();
254 $classname = context_helper::get_class_for_level($contextlevel);
256 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
257 foreach ($instances as $inst) {
258 $contexts[$inst] = $classname::instance($inst, $strictness);
261 if (is_array($instance)) {
262 return $contexts;
263 } else {
264 return $contexts[$instance];
267 /* === End of long term deprecated api list === */
270 * Adds a file upload to the log table so that clam can resolve the filename to the user later if necessary
272 * @deprecated since 2.7 - use new file picker instead
275 function clam_log_upload($newfilepath, $course=null, $nourl=false) {
276 throw new coding_exception('clam_log_upload() can not be used any more, please use file picker instead');
280 * This function logs to error_log and to the log table that an infected file has been found and what's happened to it.
282 * @deprecated since 2.7 - use new file picker instead
285 function clam_log_infected($oldfilepath='', $newfilepath='', $userid=0) {
286 throw new coding_exception('clam_log_infected() can not be used any more, please use file picker instead');
290 * Some of the modules allow moving attachments (glossary), in which case we need to hunt down an original log and change the path.
292 * @deprecated since 2.7 - use new file picker instead
295 function clam_change_log($oldpath, $newpath, $update=true) {
296 throw new coding_exception('clam_change_log() can not be used any more, please use file picker instead');
300 * Replaces the given file with a string.
302 * @deprecated since 2.7 - infected files are now deleted in file picker
305 function clam_replace_infected_file($file) {
306 throw new coding_exception('clam_replace_infected_file() can not be used any more, please use file picker instead');
310 * Deals with an infected file - either moves it to a quarantinedir
311 * (specified in CFG->quarantinedir) or deletes it.
313 * If moving it fails, it deletes it.
315 * @deprecated since 2.7
317 function clam_handle_infected_file($file, $userid=0, $basiconly=false) {
318 throw new coding_exception('clam_handle_infected_file() can not be used any more, please use file picker instead');
322 * If $CFG->runclamonupload is set, we scan a given file. (called from {@link preprocess_files()})
324 * @deprecated since 2.7
326 function clam_scan_moodle_file(&$file, $course) {
327 throw new coding_exception('clam_scan_moodle_file() can not be used any more, please use file picker instead');
332 * Checks whether the password compatibility library will work with the current
333 * version of PHP. This cannot be done using PHP version numbers since the fix
334 * has been backported to earlier versions in some distributions.
336 * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
338 * @deprecated since 2.7 PHP 5.4.x should be always compatible.
341 function password_compat_not_supported() {
342 throw new coding_exception('Do not use password_compat_not_supported() - bcrypt is now always available');
346 * Factory method that was returning moodle_session object.
348 * @deprecated since 2.6
350 function session_get_instance() {
351 throw new coding_exception('session_get_instance() is removed, use \core\session\manager instead');
355 * Returns true if legacy session used.
357 * @deprecated since 2.6
359 function session_is_legacy() {
360 throw new coding_exception('session_is_legacy() is removed, do not use any more');
364 * Terminates all sessions, auth hooks are not executed.
366 * @deprecated since 2.6
368 function session_kill_all() {
369 throw new coding_exception('session_kill_all() is removed, use \core\session\manager::kill_all_sessions() instead');
373 * Mark session as accessed, prevents timeouts.
375 * @deprecated since 2.6
377 function session_touch($sid) {
378 throw new coding_exception('session_touch() is removed, use \core\session\manager::touch_session() instead');
382 * Terminates one sessions, auth hooks are not executed.
384 * @deprecated since 2.6
386 function session_kill($sid) {
387 throw new coding_exception('session_kill() is removed, use \core\session\manager::kill_session() instead');
391 * Terminates all sessions of one user, auth hooks are not executed.
393 * @deprecated since 2.6
395 function session_kill_user($userid) {
396 throw new coding_exception('session_kill_user() is removed, use \core\session\manager::kill_user_sessions() instead');
400 * Setup $USER object - called during login, loginas, etc.
402 * Call sync_user_enrolments() manually after log-in, or log-in-as.
404 * @deprecated since 2.6
406 function session_set_user($user) {
407 throw new coding_exception('session_set_user() is removed, use \core\session\manager::set_user() instead');
411 * Is current $USER logged-in-as somebody else?
412 * @deprecated since 2.6
414 function session_is_loggedinas() {
415 throw new coding_exception('session_is_loggedinas() is removed, use \core\session\manager::is_loggedinas() instead');
419 * Returns the $USER object ignoring current login-as session
420 * @deprecated since 2.6
422 function session_get_realuser() {
423 throw new coding_exception('session_get_realuser() is removed, use \core\session\manager::get_realuser() instead');
427 * Login as another user - no security checks here.
428 * @deprecated since 2.6
430 function session_loginas($userid, $context) {
431 throw new coding_exception('session_loginas() is removed, use \core\session\manager::loginas() instead');
435 * Minify JavaScript files.
437 * @deprecated since 2.6
439 function js_minify($files) {
440 throw new coding_exception('js_minify() is removed, use core_minify::js_files() or core_minify::js() instead.');
444 * Minify CSS files.
446 * @deprecated since 2.6
448 function css_minify_css($files) {
449 throw new coding_exception('css_minify_css() is removed, use core_minify::css_files() or core_minify::css() instead.');
452 // === Deprecated before 2.6.0 ===
455 * Hack to find out the GD version by parsing phpinfo output
457 * @deprecated
459 function check_gd_version() {
460 throw new coding_exception('check_gd_version() is removed, GD extension is always available now');
464 * Not used any more, the account lockout handling is now
465 * part of authenticate_user_login().
466 * @deprecated
468 function update_login_count() {
469 throw new coding_exception('update_login_count() is removed, all calls need to be removed');
473 * Not used any more, replaced by proper account lockout.
474 * @deprecated
476 function reset_login_count() {
477 throw new coding_exception('reset_login_count() is removed, all calls need to be removed');
481 * @deprecated
483 function update_log_display_entry($module, $action, $mtable, $field) {
485 throw new coding_exception('The update_log_display_entry() is removed, please use db/log.php description file instead.');
489 * @deprecated use the text formatting in a standard way instead (http://docs.moodle.org/dev/Output_functions)
490 * this was abused mostly for embedding of attachments
492 function filter_text($text, $courseid = NULL) {
493 throw new coding_exception('filter_text() can not be used anymore, use format_text(), format_string() etc instead.');
497 * @deprecated Loginhttps is no longer supported
499 function httpsrequired() {
500 throw new coding_exception('httpsrequired() can not be used any more. Loginhttps is no longer supported.');
504 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
506 * @deprecated since 3.1 - replacement legacy file API methods can be found on the moodle_url class, for example:
507 * The moodle_url::make_legacyfile_url() method can be used to generate a legacy course file url. To generate
508 * course module file.php url the moodle_url::make_file_url() should be used.
510 * @param string $path Physical path to a file
511 * @param array $options associative array of GET variables to append to the URL
512 * @param string $type (questionfile|rssfile|httpscoursefile|coursefile)
513 * @return string URL to file
515 function get_file_url($path, $options=null, $type='coursefile') {
516 debugging('Function get_file_url() is deprecated, please use moodle_url factory methods instead.', DEBUG_DEVELOPER);
517 global $CFG;
519 $path = str_replace('//', '/', $path);
520 $path = trim($path, '/'); // no leading and trailing slashes
522 // type of file
523 switch ($type) {
524 case 'questionfile':
525 $url = $CFG->wwwroot."/question/exportfile.php";
526 break;
527 case 'rssfile':
528 $url = $CFG->wwwroot."/rss/file.php";
529 break;
530 case 'coursefile':
531 default:
532 $url = $CFG->wwwroot."/file.php";
535 if ($CFG->slasharguments) {
536 $parts = explode('/', $path);
537 foreach ($parts as $key => $part) {
538 /// anchor dash character should not be encoded
539 $subparts = explode('#', $part);
540 $subparts = array_map('rawurlencode', $subparts);
541 $parts[$key] = implode('#', $subparts);
543 $path = implode('/', $parts);
544 $ffurl = $url.'/'.$path;
545 $separator = '?';
546 } else {
547 $path = rawurlencode('/'.$path);
548 $ffurl = $url.'?file='.$path;
549 $separator = '&amp;';
552 if ($options) {
553 foreach ($options as $name=>$value) {
554 $ffurl = $ffurl.$separator.$name.'='.$value;
555 $separator = '&amp;';
559 return $ffurl;
563 * @deprecated use get_enrolled_users($context) instead.
565 function get_course_participants($courseid) {
566 throw new coding_exception('get_course_participants() can not be used any more, use get_enrolled_users() instead.');
570 * @deprecated use is_enrolled($context, $userid) instead.
572 function is_course_participant($userid, $courseid) {
573 throw new coding_exception('is_course_participant() can not be used any more, use is_enrolled() instead.');
577 * @deprecated
579 function get_recent_enrolments($courseid, $timestart) {
580 throw new coding_exception('get_recent_enrolments() is removed as it returned inaccurate results.');
584 * @deprecated use clean_param($string, PARAM_FILE) instead.
586 function detect_munged_arguments($string, $allowdots=1) {
587 throw new coding_exception('detect_munged_arguments() can not be used any more, please use clean_param(,PARAM_FILE) instead.');
592 * Unzip one zip file to a destination dir
593 * Both parameters must be FULL paths
594 * If destination isn't specified, it will be the
595 * SAME directory where the zip file resides.
597 * @global object
598 * @param string $zipfile The zip file to unzip
599 * @param string $destination The location to unzip to
600 * @param bool $showstatus_ignored Unused
601 * @deprecated since 2.0 MDL-15919
603 function unzip_file($zipfile, $destination = '', $showstatus_ignored = true) {
604 debugging(__FUNCTION__ . '() is deprecated. '
605 . 'Please use the application/zip file_packer implementation instead.', DEBUG_DEVELOPER);
607 // Extract everything from zipfile.
608 $path_parts = pathinfo(cleardoubleslashes($zipfile));
609 $zippath = $path_parts["dirname"]; //The path of the zip file
610 $zipfilename = $path_parts["basename"]; //The name of the zip file
611 $extension = $path_parts["extension"]; //The extension of the file
613 //If no file, error
614 if (empty($zipfilename)) {
615 return false;
618 //If no extension, error
619 if (empty($extension)) {
620 return false;
623 //Clear $zipfile
624 $zipfile = cleardoubleslashes($zipfile);
626 //Check zipfile exists
627 if (!file_exists($zipfile)) {
628 return false;
631 //If no destination, passed let's go with the same directory
632 if (empty($destination)) {
633 $destination = $zippath;
636 //Clear $destination
637 $destpath = rtrim(cleardoubleslashes($destination), "/");
639 //Check destination path exists
640 if (!is_dir($destpath)) {
641 return false;
644 $packer = get_file_packer('application/zip');
646 $result = $packer->extract_to_pathname($zipfile, $destpath);
648 if ($result === false) {
649 return false;
652 foreach ($result as $status) {
653 if ($status !== true) {
654 return false;
658 return true;
662 * Zip an array of files/dirs to a destination zip file
663 * Both parameters must be FULL paths to the files/dirs
665 * @global object
666 * @param array $originalfiles Files to zip
667 * @param string $destination The destination path
668 * @return bool Outcome
670 * @deprecated since 2.0 MDL-15919
672 function zip_files($originalfiles, $destination) {
673 debugging(__FUNCTION__ . '() is deprecated. '
674 . 'Please use the application/zip file_packer implementation instead.', DEBUG_DEVELOPER);
676 // Extract everything from destination.
677 $path_parts = pathinfo(cleardoubleslashes($destination));
678 $destpath = $path_parts["dirname"]; //The path of the zip file
679 $destfilename = $path_parts["basename"]; //The name of the zip file
680 $extension = $path_parts["extension"]; //The extension of the file
682 //If no file, error
683 if (empty($destfilename)) {
684 return false;
687 //If no extension, add it
688 if (empty($extension)) {
689 $extension = 'zip';
690 $destfilename = $destfilename.'.'.$extension;
693 //Check destination path exists
694 if (!is_dir($destpath)) {
695 return false;
698 //Check destination path is writable. TODO!!
700 //Clean destination filename
701 $destfilename = clean_filename($destfilename);
703 //Now check and prepare every file
704 $files = array();
705 $origpath = NULL;
707 foreach ($originalfiles as $file) { //Iterate over each file
708 //Check for every file
709 $tempfile = cleardoubleslashes($file); // no doubleslashes!
710 //Calculate the base path for all files if it isn't set
711 if ($origpath === NULL) {
712 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
714 //See if the file is readable
715 if (!is_readable($tempfile)) { //Is readable
716 continue;
718 //See if the file/dir is in the same directory than the rest
719 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
720 continue;
722 //Add the file to the array
723 $files[] = $tempfile;
726 $zipfiles = array();
727 $start = strlen($origpath)+1;
728 foreach($files as $file) {
729 $zipfiles[substr($file, $start)] = $file;
732 $packer = get_file_packer('application/zip');
734 return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename);
738 * @deprecated use groups_get_all_groups() instead.
740 function mygroupid($courseid) {
741 throw new coding_exception('mygroupid() can not be used any more, please use groups_get_all_groups() instead.');
745 * @deprecated since Moodle 2.0 MDL-14617 - please do not use this function any more.
747 function groupmode($course, $cm=null) {
748 throw new coding_exception('groupmode() can not be used any more, please use groups_get_* instead.');
752 * @deprecated Since year 2006 - please do not use this function any more.
754 function set_current_group($courseid, $groupid) {
755 throw new coding_exception('set_current_group() can not be used anymore, please use $SESSION->currentgroup[$courseid] instead');
759 * @deprecated Since year 2006 - please do not use this function any more.
761 function get_current_group($courseid, $full = false) {
762 throw new coding_exception('get_current_group() can not be used any more, please use groups_get_* instead');
766 * @deprecated Since Moodle 2.8
768 function groups_filter_users_by_course_module_visible($cm, $users) {
769 throw new coding_exception('groups_filter_users_by_course_module_visible() is removed. ' .
770 'Replace with a call to \core_availability\info_module::filter_user_list(), ' .
771 'which does basically the same thing but includes other restrictions such ' .
772 'as profile restrictions.');
776 * @deprecated Since Moodle 2.8
778 function groups_course_module_visible($cm, $userid=null) {
779 throw new coding_exception('groups_course_module_visible() is removed, use $cm->uservisible to decide whether the current
780 user can ' . 'access an activity.', DEBUG_DEVELOPER);
784 * @deprecated since 2.0
786 function error($message, $link='') {
787 throw new coding_exception('notlocalisederrormessage', 'error', $link, $message, 'error() is a removed, please call
788 print_error() instead of error()');
793 * @deprecated use $PAGE->theme->name instead.
795 function current_theme() {
796 throw new coding_exception('current_theme() can not be used any more, please use $PAGE->theme->name instead');
800 * @deprecated
802 function formerr($error) {
803 throw new coding_exception('formerr() is removed. Please change your code to use $OUTPUT->error_text($string).');
807 * @deprecated use $OUTPUT->skip_link_target() in instead.
809 function skip_main_destination() {
810 throw new coding_exception('skip_main_destination() can not be used any more, please use $OUTPUT->skip_link_target() instead.');
814 * @deprecated use $OUTPUT->container() instead.
816 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
817 throw new coding_exception('print_container() can not be used any more. Please use $OUTPUT->container() instead.');
821 * @deprecated use $OUTPUT->container_start() instead.
823 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
824 throw new coding_exception('print_container_start() can not be used any more. Please use $OUTPUT->container_start() instead.');
828 * @deprecated use $OUTPUT->container_end() instead.
830 function print_container_end($return=false) {
831 throw new coding_exception('print_container_end() can not be used any more. Please use $OUTPUT->container_end() instead.');
835 * @deprecated since Moodle 2.0 MDL-19077 - use $OUTPUT->notification instead.
837 function notify() {
838 throw new coding_exception('notify() is removed, please use $OUTPUT->notification() instead');
842 * @deprecated use $OUTPUT->continue_button() instead.
844 function print_continue($link, $return = false) {
845 throw new coding_exception('print_continue() can not be used any more. Please use $OUTPUT->continue_button() instead.');
849 * @deprecated use $PAGE methods instead.
851 function print_header($title='', $heading='', $navigation='', $focus='',
852 $meta='', $cache=true, $button='&nbsp;', $menu=null,
853 $usexml=false, $bodytags='', $return=false) {
855 throw new coding_exception('print_header() can not be used any more. Please use $PAGE methods instead.');
859 * @deprecated use $PAGE methods instead.
861 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
862 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
864 throw new coding_exception('print_header_simple() can not be used any more. Please use $PAGE methods instead.');
868 * @deprecated use $OUTPUT->block() instead.
870 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
871 throw new coding_exception('print_side_block() can not be used any more, please use $OUTPUT->block() instead.');
875 * Prints a basic textarea field.
877 * @deprecated since Moodle 2.0
879 * When using this function, you should
881 * @global object
882 * @param bool $unused No longer used.
883 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
884 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
885 * @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.
886 * @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.
887 * @param string $name Name to use for the textarea element.
888 * @param string $value Initial content to display in the textarea.
889 * @param int $obsolete deprecated
890 * @param bool $return If false, will output string. If true, will return string value.
891 * @param string $id CSS ID to add to the textarea element.
892 * @return string|void depending on the value of $return
894 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
895 /// $width and height are legacy fields and no longer used as pixels like they used to be.
896 /// However, you can set them to zero to override the mincols and minrows values below.
898 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
899 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
901 global $CFG;
903 $mincols = 65;
904 $minrows = 10;
905 $str = '';
907 if ($id === '') {
908 $id = 'edit-'.$name;
911 if ($height && ($rows < $minrows)) {
912 $rows = $minrows;
914 if ($width && ($cols < $mincols)) {
915 $cols = $mincols;
918 editors_head_setup();
919 $editor = editors_get_preferred_editor(FORMAT_HTML);
920 $editor->set_text($value);
921 $editor->use_editor($id, array('legacy'=>true));
923 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
924 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
925 $str .= '</textarea>'."\n";
927 if ($return) {
928 return $str;
930 echo $str;
934 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
935 * provide this function with the language strings for sortasc and sortdesc.
937 * @deprecated use $OUTPUT->arrow() instead.
938 * @todo final deprecation of this function once MDL-45448 is resolved
940 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
942 * @global object
943 * @param string $direction 'up' or 'down'
944 * @param string $strsort The language string used for the alt attribute of this image
945 * @param bool $return Whether to print directly or return the html string
946 * @return string|void depending on $return
949 function print_arrow($direction='up', $strsort=null, $return=false) {
950 global $OUTPUT;
952 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER);
954 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
955 return null;
958 $return = null;
960 switch ($direction) {
961 case 'up':
962 $sortdir = 'asc';
963 break;
964 case 'down':
965 $sortdir = 'desc';
966 break;
967 case 'move':
968 $sortdir = 'asc';
969 break;
970 default:
971 $sortdir = null;
972 break;
975 // Prepare language string
976 $strsort = '';
977 if (empty($strsort) && !empty($sortdir)) {
978 $strsort = get_string('sort' . $sortdir, 'grades');
981 $return = ' ' . $OUTPUT->pix_icon('t/' . $direction, $strsort) . ' ';
983 if ($return) {
984 return $return;
985 } else {
986 echo $return;
991 * @deprecated since Moodle 2.0
993 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
994 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
995 $id='', $listbox=false, $multiple=false, $class='') {
996 throw new coding_exception('choose_from_menu() is removed. Please change your code to use html_writer::select().');
1001 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1003 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1004 throw new coding_exception('print_scale_menu_helpbutton() can not be used any more. '.
1005 'Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.');
1009 * @deprecated use html_writer::checkbox() instead.
1011 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1012 throw new coding_exception('print_checkbox() can not be used any more. Please use html_writer::checkbox() instead.');
1016 * Prints the 'update this xxx' button that appears on module pages.
1018 * @deprecated since Moodle 3.2
1020 * @param string $cmid the course_module id.
1021 * @param string $ignored not used any more. (Used to be courseid.)
1022 * @param string $string the module name - get_string('modulename', 'xxx')
1023 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1025 function update_module_button($cmid, $ignored, $string) {
1026 global $CFG, $OUTPUT;
1028 debugging('update_module_button() has been deprecated and should not be used anymore. Activity modules should not add the ' .
1029 'edit module button, the link is already available in the Administration block. Themes can choose to display the link ' .
1030 'in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
1032 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1033 $string = get_string('updatethis', '', $string);
1035 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1036 return $OUTPUT->single_button($url, $string);
1037 } else {
1038 return '';
1043 * @deprecated use $OUTPUT->navbar() instead
1045 function print_navigation ($navigation, $separator=0, $return=false) {
1046 throw new coding_exception('print_navigation() can not be used any more, please update use $OUTPUT->navbar() instead.');
1050 * @deprecated Please use $PAGE->navabar methods instead.
1052 function build_navigation($extranavlinks, $cm = null) {
1053 throw new coding_exception('build_navigation() can not be used any more, please use $PAGE->navbar methods instead.');
1057 * @deprecated not relevant with global navigation in Moodle 2.x+
1059 function navmenu($course, $cm=NULL, $targetwindow='self') {
1060 throw new coding_exception('navmenu() can not be used any more, it is no longer relevant with global navigation.');
1063 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1067 * @deprecated please use calendar_event::create() instead.
1069 function add_event($event) {
1070 throw new coding_exception('add_event() can not be used any more, please use calendar_event::create() instead.');
1074 * @deprecated please calendar_event->update() instead.
1076 function update_event($event) {
1077 throw new coding_exception('update_event() is removed, please use calendar_event->update() instead.');
1081 * @deprecated please use calendar_event->delete() instead.
1083 function delete_event($id) {
1084 throw new coding_exception('delete_event() can not be used any more, please use '.
1085 'calendar_event->delete() instead.');
1089 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1091 function hide_event($event) {
1092 throw new coding_exception('hide_event() can not be used any more, please use '.
1093 'calendar_event->toggle_visibility(false) instead.');
1097 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1099 function show_event($event) {
1100 throw new coding_exception('show_event() can not be used any more, please use '.
1101 'calendar_event->toggle_visibility(true) instead.');
1105 * @deprecated since Moodle 2.2 use core_text::xxxx() instead.
1106 * @see core_text
1108 function textlib_get_instance() {
1109 throw new coding_exception('textlib_get_instance() can not be used any more, please use '.
1110 'core_text::functioname() instead.');
1114 * @deprecated since 2.4
1115 * @see get_section_name()
1116 * @see format_base::get_section_name()
1119 function get_generic_section_name($format, stdClass $section) {
1120 throw new coding_exception('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base');
1124 * Returns an array of sections for the requested course id
1126 * It is usually not recommended to display the list of sections used
1127 * in course because the course format may have it's own way to do it.
1129 * If you need to just display the name of the section please call:
1130 * get_section_name($course, $section)
1131 * {@link get_section_name()}
1132 * from 2.4 $section may also be just the field course_sections.section
1134 * If you need the list of all sections it is more efficient to get this data by calling
1135 * $modinfo = get_fast_modinfo($courseorid);
1136 * $sections = $modinfo->get_section_info_all()
1137 * {@link get_fast_modinfo()}
1138 * {@link course_modinfo::get_section_info_all()}
1140 * Information about one section (instance of section_info):
1141 * get_fast_modinfo($courseorid)->get_sections_info($section)
1142 * {@link course_modinfo::get_section_info()}
1144 * @deprecated since 2.4
1146 function get_all_sections($courseid) {
1148 throw new coding_exception('get_all_sections() is removed. See phpdocs for this function');
1152 * This function is deprecated, please use {@link course_add_cm_to_section()}
1153 * Note that course_add_cm_to_section() also updates field course_modules.section and
1154 * calls rebuild_course_cache()
1156 * @deprecated since 2.4
1158 function add_mod_to_section($mod, $beforemod = null) {
1159 throw new coding_exception('Function add_mod_to_section() is removed, please use course_add_cm_to_section()');
1163 * Returns a number of useful structures for course displays
1165 * Function get_all_mods() is deprecated in 2.4
1166 * Instead of:
1167 * <code>
1168 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1169 * </code>
1170 * please use:
1171 * <code>
1172 * $mods = get_fast_modinfo($courseorid)->get_cms();
1173 * $modnames = get_module_types_names();
1174 * $modnamesplural = get_module_types_names(true);
1175 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1176 * </code>
1178 * @deprecated since 2.4
1180 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1181 throw new coding_exception('Function get_all_mods() is removed. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details');
1185 * Returns course section - creates new if does not exist yet
1187 * This function is deprecated. To create a course section call:
1188 * course_create_sections_if_missing($courseorid, $sections);
1189 * to get the section call:
1190 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1192 * @see course_create_sections_if_missing()
1193 * @see get_fast_modinfo()
1194 * @deprecated since 2.4
1196 function get_course_section($section, $courseid) {
1197 throw new coding_exception('Function get_course_section() is removed. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.');
1201 * @deprecated since 2.4
1202 * @see format_weeks::get_section_dates()
1204 function format_weeks_get_section_dates($section, $course) {
1205 throw new coding_exception('Function format_weeks_get_section_dates() is removed. It is not recommended to'.
1206 ' use it outside of format_weeks plugin');
1210 * Deprecated. Instead of:
1211 * list($content, $name) = get_print_section_cm_text($cm, $course);
1212 * use:
1213 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1214 * $name = $cm->get_formatted_name();
1216 * @deprecated since 2.5
1217 * @see cm_info::get_formatted_content()
1218 * @see cm_info::get_formatted_name()
1220 function get_print_section_cm_text(cm_info $cm, $course) {
1221 throw new coding_exception('Function get_print_section_cm_text() is removed. Please use '.
1222 'cm_info::get_formatted_content() and cm_info::get_formatted_name()');
1226 * Deprecated. Please use:
1227 * $courserenderer = $PAGE->get_renderer('core', 'course');
1228 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1229 * array('inblock' => $vertical));
1230 * echo $output;
1232 * @deprecated since 2.5
1233 * @see core_course_renderer::course_section_add_cm_control()
1235 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1236 throw new coding_exception('Function print_section_add_menus() is removed. Please use course renderer '.
1237 'function course_section_add_cm_control()');
1241 * Deprecated. Please use:
1242 * $courserenderer = $PAGE->get_renderer('core', 'course');
1243 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
1244 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1246 * @deprecated since 2.5
1247 * @see course_get_cm_edit_actions()
1248 * @see core_course_renderer->course_section_cm_edit_actions()
1250 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
1251 throw new coding_exception('Function make_editing_buttons() is removed, please see PHPdocs in '.
1252 'lib/deprecatedlib.php on how to replace it');
1256 * Deprecated. Please use:
1257 * $courserenderer = $PAGE->get_renderer('core', 'course');
1258 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
1259 * array('hidecompletion' => $hidecompletion));
1261 * @deprecated since 2.5
1262 * @see core_course_renderer::course_section_cm_list()
1264 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1265 throw new coding_exception('Function print_section() is removed. Please use course renderer function '.
1266 'course_section_cm_list() instead.');
1270 * @deprecated since 2.5
1272 function print_overview($courses, array $remote_courses=array()) {
1273 throw new coding_exception('Function print_overview() is removed. Use block course_overview to display this information');
1277 * @deprecated since 2.5
1279 function print_recent_activity($course) {
1280 throw new coding_exception('Function print_recent_activity() is removed. It is not recommended to'.
1281 ' use it outside of block_recent_activity');
1285 * @deprecated since 2.5
1287 function delete_course_module($id) {
1288 throw new coding_exception('Function delete_course_module() is removed. Please use course_delete_module() instead.');
1292 * @deprecated since 2.5
1294 function update_category_button($categoryid = 0) {
1295 throw new coding_exception('Function update_category_button() is removed. Pages to view '.
1296 'and edit courses are now separate and no longer depend on editing mode.');
1300 * This function is deprecated! For list of categories use
1301 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
1302 * For parents of one particular category use
1303 * coursecat::get($id)->get_parents()
1305 * @deprecated since 2.5
1307 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1308 $excludeid = 0, $category = NULL, $path = "") {
1309 throw new coding_exception('Global function make_categories_list() is removed. Please use '.
1310 'coursecat::make_categories_list() and coursecat::get_parents()');
1314 * @deprecated since 2.5
1316 function category_delete_move($category, $newparentid, $showfeedback=true) {
1317 throw new coding_exception('Function category_delete_move() is removed. Please use coursecat::delete_move() instead.');
1321 * @deprecated since 2.5
1323 function category_delete_full($category, $showfeedback=true) {
1324 throw new coding_exception('Function category_delete_full() is removed. Please use coursecat::delete_full() instead.');
1328 * This function is deprecated. Please use
1329 * $coursecat = coursecat::get($category->id);
1330 * if ($coursecat->can_change_parent($newparentcat->id)) {
1331 * $coursecat->change_parent($newparentcat->id);
1334 * Alternatively you can use
1335 * $coursecat->update(array('parent' => $newparentcat->id));
1337 * @see coursecat::change_parent()
1338 * @see coursecat::update()
1339 * @deprecated since 2.5
1341 function move_category($category, $newparentcat) {
1342 throw new coding_exception('Function move_category() is removed. Please use coursecat::change_parent() instead.');
1346 * This function is deprecated. Please use
1347 * coursecat::get($category->id)->hide();
1349 * @see coursecat::hide()
1350 * @deprecated since 2.5
1352 function course_category_hide($category) {
1353 throw new coding_exception('Function course_category_hide() is removed. Please use coursecat::hide() instead.');
1357 * This function is deprecated. Please use
1358 * coursecat::get($category->id)->show();
1360 * @see coursecat::show()
1361 * @deprecated since 2.5
1363 function course_category_show($category) {
1364 throw new coding_exception('Function course_category_show() is removed. Please use coursecat::show() instead.');
1368 * This function is deprecated.
1369 * To get the category with the specified it please use:
1370 * coursecat::get($catid, IGNORE_MISSING);
1371 * or
1372 * coursecat::get($catid, MUST_EXIST);
1374 * To get the first available category please use
1375 * coursecat::get_default();
1377 * @deprecated since 2.5
1379 function get_course_category($catid=0) {
1380 throw new coding_exception('Function get_course_category() is removed. Please use coursecat::get(), see phpdocs for more details');
1384 * This function is deprecated. It is replaced with the method create() in class coursecat.
1385 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
1387 * @deprecated since 2.5
1389 function create_course_category($category) {
1390 throw new coding_exception('Function create_course_category() is removed. Please use coursecat::create(), see phpdocs for more details');
1394 * This function is deprecated.
1396 * To get visible children categories of the given category use:
1397 * coursecat::get($categoryid)->get_children();
1398 * This function will return the array or coursecat objects, on each of them
1399 * you can call get_children() again
1401 * @see coursecat::get()
1402 * @see coursecat::get_children()
1404 * @deprecated since 2.5
1406 function get_all_subcategories($catid) {
1407 throw new coding_exception('Function get_all_subcategories() is removed. Please use appropriate methods() of coursecat
1408 class. See phpdocs for more details');
1412 * This function is deprecated. Please use functions in class coursecat:
1413 * - coursecat::get($parentid)->has_children()
1414 * tells if the category has children (visible or not to the current user)
1416 * - coursecat::get($parentid)->get_children()
1417 * returns an array of coursecat objects, each of them represents a children category visible
1418 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
1420 * - coursecat::get($parentid)->get_children_count()
1421 * returns number of children categories visible to the current user
1423 * - coursecat::count_all()
1424 * returns total count of all categories in the system (both visible and not)
1426 * - coursecat::get_default()
1427 * returns the first category (usually to be used if count_all() == 1)
1429 * @deprecated since 2.5
1431 function get_child_categories($parentid) {
1432 throw new coding_exception('Function get_child_categories() is removed. Use coursecat::get_children() or see phpdocs for
1433 more details.');
1438 * @deprecated since 2.5
1440 * This function is deprecated. Use appropriate functions from class coursecat.
1441 * Examples:
1443 * coursecat::get($categoryid)->get_children()
1444 * - returns all children of the specified category as instances of class
1445 * coursecat, which means on each of them method get_children() can be called again.
1446 * Only categories visible to the current user are returned.
1448 * coursecat::get(0)->get_children()
1449 * - returns all top-level categories visible to the current user.
1451 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
1453 * coursecat::make_categories_list()
1454 * - returns an array of all categories id/names in the system.
1455 * Also only returns categories visible to current user and can additionally be
1456 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
1458 * make_categories_options()
1459 * - Returns full course categories tree to be used in html_writer::select()
1461 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
1462 * {@link coursecat::get_default()}
1464 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1465 throw new coding_exception('Function get_categories() is removed. Please use coursecat::get_children() or see phpdocs for other alternatives');
1469 * This function is deprecated, please use course renderer:
1470 * $renderer = $PAGE->get_renderer('core', 'course');
1471 * echo $renderer->course_search_form($value, $format);
1473 * @deprecated since 2.5
1475 function print_course_search($value="", $return=false, $format="plain") {
1476 throw new coding_exception('Function print_course_search() is removed, please use course renderer');
1480 * This function is deprecated, please use:
1481 * $renderer = $PAGE->get_renderer('core', 'course');
1482 * echo $renderer->frontpage_my_courses()
1484 * @deprecated since 2.5
1486 function print_my_moodle() {
1487 throw new coding_exception('Function print_my_moodle() is removed, please use course renderer function frontpage_my_courses()');
1491 * This function is deprecated, it is replaced with protected function
1492 * {@link core_course_renderer::frontpage_remote_course()}
1493 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1495 * @deprecated since 2.5
1497 function print_remote_course($course, $width="100%") {
1498 throw new coding_exception('Function print_remote_course() is removed, please use course renderer');
1502 * This function is deprecated, it is replaced with protected function
1503 * {@link core_course_renderer::frontpage_remote_host()}
1504 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1506 * @deprecated since 2.5
1508 function print_remote_host($host, $width="100%") {
1509 throw new coding_exception('Function print_remote_host() is removed, please use course renderer');
1513 * @deprecated since 2.5
1515 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1517 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1518 throw new coding_exception('Function print_whole_category_list() is removed, please use course renderer');
1522 * @deprecated since 2.5
1524 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1525 throw new coding_exception('Function print_category_info() is removed, please use course renderer');
1529 * @deprecated since 2.5
1531 * This function is not used any more in moodle core and course renderer does not have render function for it.
1532 * Combo list on the front page is displayed as:
1533 * $renderer = $PAGE->get_renderer('core', 'course');
1534 * echo $renderer->frontpage_combo_list()
1536 * The new class {@link coursecat} stores the information about course category tree
1537 * To get children categories use:
1538 * coursecat::get($id)->get_children()
1539 * To get list of courses use:
1540 * coursecat::get($id)->get_courses()
1542 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1544 function get_course_category_tree($id = 0, $depth = 0) {
1545 throw new coding_exception('Function get_course_category_tree() is removed, please use course renderer or coursecat class,
1546 see function phpdocs for more info');
1550 * @deprecated since 2.5
1552 * To print a generic list of courses use:
1553 * $renderer = $PAGE->get_renderer('core', 'course');
1554 * echo $renderer->courses_list($courses);
1556 * To print list of all courses:
1557 * $renderer = $PAGE->get_renderer('core', 'course');
1558 * echo $renderer->frontpage_available_courses();
1560 * To print list of courses inside category:
1561 * $renderer = $PAGE->get_renderer('core', 'course');
1562 * echo $renderer->course_category($category); // this will also print subcategories
1564 function print_courses($category) {
1565 throw new coding_exception('Function print_courses() is removed, please use course renderer');
1569 * @deprecated since 2.5
1571 * Please use course renderer to display a course information box.
1572 * $renderer = $PAGE->get_renderer('core', 'course');
1573 * echo $renderer->courses_list($courses); // will print list of courses
1574 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
1576 function print_course($course, $highlightterms = '') {
1577 throw new coding_exception('Function print_course() is removed, please use course renderer');
1581 * @deprecated since 2.5
1583 * This function is not used any more in moodle core and course renderer does not have render function for it.
1584 * Combo list on the front page is displayed as:
1585 * $renderer = $PAGE->get_renderer('core', 'course');
1586 * echo $renderer->frontpage_combo_list()
1588 * The new class {@link coursecat} stores the information about course category tree
1589 * To get children categories use:
1590 * coursecat::get($id)->get_children()
1591 * To get list of courses use:
1592 * coursecat::get($id)->get_courses()
1594 function get_category_courses_array($categoryid = 0) {
1595 throw new coding_exception('Function get_category_courses_array() is removed, please use methods of coursecat class');
1599 * @deprecated since 2.5
1601 function get_category_courses_array_recursively(array &$flattened, $category) {
1602 throw new coding_exception('Function get_category_courses_array_recursively() is removed, please use methods of coursecat class', DEBUG_DEVELOPER);
1606 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
1608 function blog_get_context_url($context=null) {
1609 throw new coding_exception('Function blog_get_context_url() is removed, getting params from context is not reliable for blogs.');
1613 * @deprecated since 2.5
1615 * To get list of all courses with course contacts ('managers') use
1616 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
1618 * To get list of courses inside particular category use
1619 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
1621 * Additionally you can specify sort order, offset and maximum number of courses,
1622 * see {@link coursecat::get_courses()}
1624 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
1625 throw new coding_exception('Function get_courses_wmanagers() is removed, please use coursecat::get_courses()');
1629 * @deprecated since 2.5
1631 function convert_tree_to_html($tree, $row=0) {
1632 throw new coding_exception('Function convert_tree_to_html() is removed. Consider using class tabtree and core_renderer::render_tabtree()');
1636 * @deprecated since 2.5
1638 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
1639 throw new coding_exception('Function convert_tabrows_to_tree() is removed. Consider using class tabtree');
1643 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
1645 function can_use_rotated_text() {
1646 debugging('can_use_rotated_text() is removed. JS feature detection is used automatically.');
1650 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
1651 * @see context::instance_by_id($id)
1653 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
1654 throw new coding_exception('get_context_instance_by_id() is now removed, please use context::instance_by_id($id) instead.');
1658 * Returns system context or null if can not be created yet.
1660 * @see context_system::instance()
1661 * @deprecated since 2.2
1662 * @param bool $cache use caching
1663 * @return context system context (null if context table not created yet)
1665 function get_system_context($cache = true) {
1666 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
1667 return context_system::instance(0, IGNORE_MISSING, $cache);
1671 * @see context::get_parent_context_ids()
1672 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
1674 function get_parent_contexts(context $context, $includeself = false) {
1675 throw new coding_exception('get_parent_contexts() is removed, please use $context->get_parent_context_ids() instead.');
1679 * @deprecated since Moodle 2.2
1680 * @see context::get_parent_context()
1682 function get_parent_contextid(context $context) {
1683 throw new coding_exception('get_parent_contextid() is removed, please use $context->get_parent_context() instead.');
1687 * @see context::get_child_contexts()
1688 * @deprecated since 2.2
1690 function get_child_contexts(context $context) {
1691 throw new coding_exception('get_child_contexts() is removed, please use $context->get_child_contexts() instead.');
1695 * @see context_helper::create_instances()
1696 * @deprecated since 2.2
1698 function create_contexts($contextlevel = null, $buildpaths = true) {
1699 throw new coding_exception('create_contexts() is removed, please use context_helper::create_instances() instead.');
1703 * @see context_helper::cleanup_instances()
1704 * @deprecated since 2.2
1706 function cleanup_contexts() {
1707 throw new coding_exception('cleanup_contexts() is removed, please use context_helper::cleanup_instances() instead.');
1711 * Populate context.path and context.depth where missing.
1713 * @deprecated since 2.2
1715 function build_context_path($force = false) {
1716 throw new coding_exception('build_context_path() is removed, please use context_helper::build_all_paths() instead.');
1720 * @deprecated since 2.2
1722 function rebuild_contexts(array $fixcontexts) {
1723 throw new coding_exception('rebuild_contexts() is removed, please use $context->reset_paths(true) instead.');
1727 * @deprecated since Moodle 2.2
1728 * @see context_helper::preload_course()
1730 function preload_course_contexts($courseid) {
1731 throw new coding_exception('preload_course_contexts() is removed, please use context_helper::preload_course() instead.');
1735 * @deprecated since Moodle 2.2
1736 * @see context::update_moved()
1738 function context_moved(context $context, context $newparent) {
1739 throw new coding_exception('context_moved() is removed, please use context::update_moved() instead.');
1743 * @see context::get_capabilities()
1744 * @deprecated since 2.2
1746 function fetch_context_capabilities(context $context) {
1747 throw new coding_exception('fetch_context_capabilities() is removed, please use $context->get_capabilities() instead.');
1751 * @deprecated since 2.2
1752 * @see context_helper::preload_from_record()
1754 function context_instance_preload(stdClass $rec) {
1755 throw new coding_exception('context_instance_preload() is removed, please use context_helper::preload_from_record() instead.');
1759 * Returns context level name
1761 * @deprecated since 2.2
1762 * @see context_helper::get_level_name()
1764 function get_contextlevel_name($contextlevel) {
1765 throw new coding_exception('get_contextlevel_name() is removed, please use context_helper::get_level_name() instead.');
1769 * @deprecated since 2.2
1770 * @see context::get_context_name()
1772 function print_context_name(context $context, $withprefix = true, $short = false) {
1773 throw new coding_exception('print_context_name() is removed, please use $context->get_context_name() instead.');
1777 * @deprecated since 2.2, use $context->mark_dirty() instead
1778 * @see context::mark_dirty()
1780 function mark_context_dirty($path) {
1781 throw new coding_exception('mark_context_dirty() is removed, please use $context->mark_dirty() instead.');
1785 * @deprecated since Moodle 2.2
1786 * @see context_helper::delete_instance() or context::delete_content()
1788 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1789 if ($deleterecord) {
1790 throw new coding_exception('delete_context() is removed, please use context_helper::delete_instance() instead.');
1791 } else {
1792 throw new coding_exception('delete_context() is removed, please use $context->delete_content() instead.');
1797 * @deprecated since 2.2
1798 * @see context::get_url()
1800 function get_context_url(context $context) {
1801 throw new coding_exception('get_context_url() is removed, please use $context->get_url() instead.');
1805 * @deprecated since 2.2
1806 * @see context::get_course_context()
1808 function get_course_context(context $context) {
1809 throw new coding_exception('get_course_context() is removed, please use $context->get_course_context(true) instead.');
1813 * @deprecated since 2.2
1814 * @see enrol_get_users_courses()
1816 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1818 throw new coding_exception('get_user_courses_bycap() is removed, please use enrol_get_users_courses() instead.');
1822 * @deprecated since Moodle 2.2
1824 function get_role_context_caps($roleid, context $context) {
1825 throw new coding_exception('get_role_context_caps() is removed, it is really slow. Don\'t use it.');
1829 * @see context::get_course_context()
1830 * @deprecated since 2.2
1832 function get_courseid_from_context(context $context) {
1833 throw new coding_exception('get_courseid_from_context() is removed, please use $context->get_course_context(false) instead.');
1837 * If you are using this methid, you should have something like this:
1839 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1841 * To prevent the use of this deprecated function, replace the line above with something similar to this:
1843 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1845 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1846 * ^ ^ ^ ^
1847 * $params = array('contextlevel' => CONTEXT_COURSE);
1849 * @see context_helper:;get_preload_record_columns_sql()
1850 * @deprecated since 2.2
1852 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
1853 throw new coding_exception('context_instance_preload_sql() is removed, please use context_helper::get_preload_record_columns_sql() instead.');
1857 * @deprecated since 2.2
1858 * @see context::get_parent_context_ids()
1860 function get_related_contexts_string(context $context) {
1861 throw new coding_exception('get_related_contexts_string() is removed, please use $context->get_parent_context_ids(true) instead.');
1865 * @deprecated since 2.6
1866 * @see core_component::get_plugin_list_with_file()
1868 function get_plugin_list_with_file($plugintype, $file, $include = false) {
1869 throw new coding_exception('get_plugin_list_with_file() is removed, please use core_component::get_plugin_list_with_file() instead.');
1873 * @deprecated since 2.6
1875 function check_browser_operating_system($brand) {
1876 throw new coding_exception('check_browser_operating_system is removed, please update your code to use core_useragent instead.');
1880 * @deprecated since 2.6
1882 function check_browser_version($brand, $version = null) {
1883 throw new coding_exception('check_browser_version is removed, please update your code to use core_useragent instead.');
1887 * @deprecated since 2.6
1889 function get_device_type() {
1890 throw new coding_exception('get_device_type is removed, please update your code to use core_useragent instead.');
1894 * @deprecated since 2.6
1896 function get_device_type_list($incusertypes = true) {
1897 throw new coding_exception('get_device_type_list is removed, please update your code to use core_useragent instead.');
1901 * @deprecated since 2.6
1903 function get_selected_theme_for_device_type($devicetype = null) {
1904 throw new coding_exception('get_selected_theme_for_device_type is removed, please update your code to use core_useragent instead.');
1908 * @deprecated since 2.6
1910 function get_device_cfg_var_name($devicetype = null) {
1911 throw new coding_exception('get_device_cfg_var_name is removed, please update your code to use core_useragent instead.');
1915 * @deprecated since 2.6
1917 function set_user_device_type($newdevice) {
1918 throw new coding_exception('set_user_device_type is removed, please update your code to use core_useragent instead.');
1922 * @deprecated since 2.6
1924 function get_user_device_type() {
1925 throw new coding_exception('get_user_device_type is removed, please update your code to use core_useragent instead.');
1929 * @deprecated since 2.6
1931 function get_browser_version_classes() {
1932 throw new coding_exception('get_browser_version_classes is removed, please update your code to use core_useragent instead.');
1936 * @deprecated since Moodle 2.6
1937 * @see core_user::get_support_user()
1939 function generate_email_supportuser() {
1940 throw new coding_exception('generate_email_supportuser is removed, please use core_user::get_support_user');
1944 * @deprecated since Moodle 2.6
1946 function badges_get_issued_badge_info($hash) {
1947 throw new coding_exception('Function badges_get_issued_badge_info() is removed. Please use core_badges_assertion class and methods to generate badge assertion.');
1951 * @deprecated since 2.6
1953 function can_use_html_editor() {
1954 throw new coding_exception('can_use_html_editor is removed, please update your code to assume it returns true.');
1959 * @deprecated since Moodle 2.7, use {@link user_count_login_failures()} instead.
1961 function count_login_failures($mode, $username, $lastlogin) {
1962 throw new coding_exception('count_login_failures() can not be used any more, please use user_count_login_failures().');
1966 * @deprecated since 2.7 MDL-33099/MDL-44088 - please do not use this function any more.
1968 function ajaxenabled(array $browsers = null) {
1969 throw new coding_exception('ajaxenabled() can not be used anymore. Update your code to work with JS at all times.');
1973 * @deprecated Since Moodle 2.7 MDL-44070
1975 function coursemodule_visible_for_user($cm, $userid=0) {
1976 throw new coding_exception('coursemodule_visible_for_user() can not be used any more,
1977 please use \core_availability\info_module::is_user_visible()');
1981 * @deprecated since Moodle 2.8 MDL-36014, MDL-35618 this functionality is removed
1983 function enrol_cohort_get_cohorts(course_enrolment_manager $manager) {
1984 throw new coding_exception('Function enrol_cohort_get_cohorts() is removed, use enrol_cohort_search_cohorts() or '.
1985 'cohort_get_available_cohorts() instead');
1989 * This function is deprecated, use {@link cohort_can_view_cohort()} instead since it also
1990 * takes into account current context
1992 * @deprecated since Moodle 2.8 MDL-36014 please use cohort_can_view_cohort()
1994 function enrol_cohort_can_view_cohort($cohortid) {
1995 throw new coding_exception('Function enrol_cohort_can_view_cohort() is removed, use cohort_can_view_cohort() instead');
1999 * It is advisable to use {@link cohort_get_available_cohorts()} instead.
2001 * @deprecated since Moodle 2.8 MDL-36014 use cohort_get_available_cohorts() instead
2003 function cohort_get_visible_list($course, $onlyenrolled=true) {
2004 throw new coding_exception('Function cohort_get_visible_list() is removed. Please use function cohort_get_available_cohorts() ".
2005 "that correctly checks capabilities.');
2009 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2011 function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohortid, $roleid) {
2012 throw new coding_exception('enrol_cohort_enrol_all_users() is removed. This functionality is moved to enrol_manual.');
2016 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2018 function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '') {
2019 throw new coding_exception('enrol_cohort_search_cohorts() is removed. This functionality is moved to enrol_manual.');
2022 /* === Apis deprecated in since Moodle 2.9 === */
2025 * Is $USER one of the supplied users?
2027 * $user2 will be null if viewing a user's recent conversations
2029 * @deprecated since Moodle 2.9 MDL-49371 - please do not use this function any more.
2031 function message_current_user_is_involved($user1, $user2) {
2032 throw new coding_exception('message_current_user_is_involved() can not be used any more.');
2036 * Print badges on user profile page.
2038 * @deprecated since Moodle 2.9 MDL-45898 - please do not use this function any more.
2040 function profile_display_badges($userid, $courseid = 0) {
2041 throw new coding_exception('profile_display_badges() can not be used any more.');
2045 * Adds user preferences elements to user edit form.
2047 * @deprecated since Moodle 2.9 MDL-45774 - Please do not use this function any more.
2049 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
2050 throw new coding_exception('useredit_shared_definition_preferences() can not be used any more.');
2055 * Convert region timezone to php supported timezone
2057 * @deprecated since Moodle 2.9
2059 function calendar_normalize_tz($tz) {
2060 throw new coding_exception('calendar_normalize_tz() can not be used any more, please use core_date::normalise_timezone() instead.');
2064 * Returns a float which represents the user's timezone difference from GMT in hours
2065 * Checks various settings and picks the most dominant of those which have a value
2066 * @deprecated since Moodle 2.9
2068 function get_user_timezone_offset($tz = 99) {
2069 throw new coding_exception('get_user_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2074 * Returns an int which represents the systems's timezone difference from GMT in seconds
2075 * @deprecated since Moodle 2.9
2077 function get_timezone_offset($tz) {
2078 throw new coding_exception('get_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2082 * Returns a list of timezones in the current language.
2083 * @deprecated since Moodle 2.9
2085 function get_list_of_timezones() {
2086 throw new coding_exception('get_list_of_timezones() can not be used any more, please use core_date::get_list_of_timezones() instead');
2090 * Previous internal API, it was not supposed to be used anywhere.
2091 * @deprecated since Moodle 2.9
2093 function update_timezone_records($timezones) {
2094 throw new coding_exception('update_timezone_records() can not be used any more, please use standard PHP DateTime class instead');
2098 * Previous internal API, it was not supposed to be used anywhere.
2099 * @deprecated since Moodle 2.9
2101 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2102 throw new coding_exception('calculate_user_dst_table() can not be used any more, please use standard PHP DateTime class instead');
2106 * Previous internal API, it was not supposed to be used anywhere.
2107 * @deprecated since Moodle 2.9
2109 function dst_changes_for_year($year, $timezone) {
2110 throw new coding_exception('dst_changes_for_year() can not be used any more, please use standard DateTime class instead');
2114 * Previous internal API, it was not supposed to be used anywhere.
2115 * @deprecated since Moodle 2.9
2117 function get_timezone_record($timezonename) {
2118 throw new coding_exception('get_timezone_record() can not be used any more, please use standard PHP DateTime class instead');
2121 /* === Apis deprecated since Moodle 3.0 === */
2123 * @deprecated since Moodle 3.0 MDL-49360 - please do not use this function any more.
2125 function get_referer($stripquery = true) {
2126 throw new coding_exception('get_referer() can not be used any more. Please use get_local_referer() instead.');
2130 * @deprecated since Moodle 3.0 use \core_useragent::is_web_crawler instead.
2132 function is_web_crawler() {
2133 throw new coding_exception('is_web_crawler() can not be used any more. Please use core_useragent::is_web_crawler() instead.');
2137 * @deprecated since Moodle 3.0 MDL-50287 - please do not use this function any more.
2139 function completion_cron() {
2140 throw new coding_exception('completion_cron() can not be used any more. Functionality has been moved to scheduled tasks.');
2144 * @deprecated since 3.0
2146 function coursetag_get_tags($courseid, $userid=0, $tagtype='', $numtags=0, $unused = '') {
2147 throw new coding_exception('Function coursetag_get_tags() can not be used any more. Userid is no longer used for tagging courses.');
2151 * @deprecated since 3.0
2153 function coursetag_get_all_tags($unused='', $numtags=0) {
2154 throw new coding_exception('Function coursetag_get_all_tag() can not be used any more. Userid is no longer used for tagging courses.');
2158 * @deprecated since 3.0
2160 function coursetag_get_jscript() {
2161 throw new coding_exception('Function coursetag_get_jscript() can not be used any more and is obsolete.');
2165 * @deprecated since 3.0
2167 function coursetag_get_jscript_links($elementid, $coursetagslinks) {
2168 throw new coding_exception('Function coursetag_get_jscript_links() can not be used any more and is obsolete.');
2172 * @deprecated since 3.0
2174 function coursetag_get_records($courseid, $userid) {
2175 throw new coding_exception('Function coursetag_get_records() can not be used any more. Userid is no longer used for tagging courses.');
2179 * @deprecated since 3.0
2181 function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {
2182 throw new coding_exception('Function coursetag_store_keywords() can not be used any more. Userid is no longer used for tagging courses.');
2186 * @deprecated since 3.0
2188 function coursetag_delete_keyword($tagid, $userid, $courseid) {
2189 throw new coding_exception('Function coursetag_delete_keyword() can not be used any more. Userid is no longer used for tagging courses.');
2193 * @deprecated since 3.0
2195 function coursetag_get_tagged_courses($tagid) {
2196 throw new coding_exception('Function coursetag_get_tagged_courses() can not be used any more. Userid is no longer used for tagging courses.');
2200 * @deprecated since 3.0
2202 function coursetag_delete_course_tags($courseid, $showfeedback=false) {
2203 throw new coding_exception('Function coursetag_delete_course_tags() is deprecated. Use core_tag_tag::remove_all_item_tags().');
2207 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
2208 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
2210 * @package core_tag
2211 * @deprecated since 3.1
2212 * @param string $tagid tagid to modify
2213 * @param string $type either 'default' or 'official'
2214 * @return bool true on success, false otherwise
2216 function tag_type_set($tagid, $type) {
2217 debugging('Function tag_type_set() is deprecated and can be replaced with use core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2218 if ($tag = core_tag_tag::get($tagid, '*')) {
2219 return $tag->update(array('isstandard' => ($type === 'official') ? 1 : 0));
2221 return false;
2225 * Set the description of a tag
2227 * @package core_tag
2228 * @deprecated since 3.1
2229 * @param int $tagid the id of the tag
2230 * @param string $description the tag's description string to be set
2231 * @param int $descriptionformat the moodle text format of the description
2232 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
2233 * @return bool true on success, false otherwise
2235 function tag_description_set($tagid, $description, $descriptionformat) {
2236 debugging('Function tag_type_set() is deprecated and can be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2237 if ($tag = core_tag_tag::get($tagid, '*')) {
2238 return $tag->update(array('description' => $description, 'descriptionformat' => $descriptionformat));
2240 return false;
2244 * Get the array of db record of tags associated to a record (instances).
2246 * @package core_tag
2247 * @deprecated since 3.1
2248 * @param string $record_type the record type for which we want to get the tags
2249 * @param int $record_id the record id for which we want to get the tags
2250 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2251 * @param int $userid (optional) only required for course tagging
2252 * @return array the array of tags
2254 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
2255 debugging('Method tag_get_tags() is deprecated and replaced with core_tag_tag::get_item_tags(). ' .
2256 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2257 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2258 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2259 $tags = core_tag_tag::get_item_tags(null, $record_type, $record_id, $standardonly, $userid);
2260 $rv = array();
2261 foreach ($tags as $id => $t) {
2262 $rv[$id] = $t->to_object();
2264 return $rv;
2268 * Get the array of tags display names, indexed by id.
2270 * @package core_tag
2271 * @deprecated since 3.1
2272 * @param string $record_type the record type for which we want to get the tags
2273 * @param int $record_id the record id for which we want to get the tags
2274 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2275 * @return array the array of tags (with the value returned by core_tag_tag::make_display_name), indexed by id
2277 function tag_get_tags_array($record_type, $record_id, $type=null) {
2278 debugging('Method tag_get_tags_array() is deprecated and replaced with core_tag_tag::get_item_tags_array(). ' .
2279 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2280 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2281 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2282 return core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly);
2286 * Get a comma-separated string of tags associated to a record.
2288 * Use {@link tag_get_tags()} to get the same information in an array.
2290 * @package core_tag
2291 * @deprecated since 3.1
2292 * @param string $record_type the record type for which we want to get the tags
2293 * @param int $record_id the record id for which we want to get the tags
2294 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
2295 * @param string $type either 'official' or 'default', if null, all tags are returned
2296 * @return string the comma-separated list of tags.
2298 function tag_get_tags_csv($record_type, $record_id, $html=null, $type=null) {
2299 global $CFG, $OUTPUT;
2300 debugging('Method tag_get_tags_csv() is deprecated. Instead you should use either ' .
2301 'core_tag_tag::get_item_tags_array() or $OUTPUT->tag_list(core_tag_tag::get_item_tags()). ' .
2302 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2303 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2304 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2305 if ($html != TAG_RETURN_TEXT) {
2306 return $OUTPUT->tag_list(core_tag_tag::get_item_tags('', $record_type, $record_id, $standardonly), '');
2307 } else {
2308 return join(', ', core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly, 0, false));
2313 * Get an array of tag ids associated to a record.
2315 * @package core_tag
2316 * @deprecated since 3.1
2317 * @param string $record_type the record type for which we want to get the tags
2318 * @param int $record_id the record id for which we want to get the tags
2319 * @return array tag ids, indexed and sorted by 'ordering'
2321 function tag_get_tags_ids($record_type, $record_id) {
2322 debugging('Method tag_get_tags_ids() is deprecated. Please consider using core_tag_tag::get_item_tags() or similar methods.', DEBUG_DEVELOPER);
2323 $tag_ids = array();
2324 $tagobjects = core_tag_tag::get_item_tags(null, $record_type, $record_id);
2325 foreach ($tagobjects as $tagobject) {
2326 $tag = $tagobject->to_object();
2327 if ( array_key_exists($tag->ordering, $tag_ids) ) {
2328 $tag->ordering++;
2330 $tag_ids[$tag->ordering] = $tag->id;
2332 ksort($tag_ids);
2333 return $tag_ids;
2337 * Returns the database ID of a set of tags.
2339 * @deprecated since 3.1
2340 * @param mixed $tags one tag, or array of tags, to look for.
2341 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
2342 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
2343 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
2344 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
2346 function tag_get_id($tags, $return_value = null) {
2347 global $CFG, $DB;
2348 debugging('Method tag_get_id() is deprecated and can be replaced with core_tag_tag::get_by_name() or core_tag_tag::get_by_name_bulk(). ' .
2349 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2351 if (!is_array($tags)) {
2352 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
2353 if ($tagobject = core_tag_tag::get_by_name(core_tag_collection::get_default(), $tags)) {
2354 return $tagobject->id;
2355 } else {
2356 return 0;
2359 $tags = array($tags);
2362 $records = core_tag_tag::get_by_name_bulk(core_tag_collection::get_default(), $tags,
2363 $return_value == TAG_RETURN_OBJECT ? '*' : 'id, name');
2364 foreach ($records as $name => $record) {
2365 if ($return_value != TAG_RETURN_OBJECT) {
2366 $records[$name] = $record->id ? $record->id : null;
2367 } else {
2368 $records[$name] = $record->to_object();
2371 return $records;
2375 * Change the "value" of a tag, and update the associated 'name'.
2377 * @package core_tag
2378 * @deprecated since 3.1
2379 * @param int $tagid the id of the tag to modify
2380 * @param string $newrawname the new rawname
2381 * @return bool true on success, false otherwise
2383 function tag_rename($tagid, $newrawname) {
2384 debugging('Function tag_rename() is deprecated and may be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2385 if ($tag = core_tag_tag::get($tagid, '*')) {
2386 return $tag->update(array('rawname' => $newrawname));
2388 return false;
2392 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
2394 * @package core_tag
2395 * @deprecated since 3.1
2396 * @param string $record_type the type of the record for which to remove the instance
2397 * @param int $record_id the id of the record for which to remove the instance
2398 * @param int $tagid the tagid that needs to be removed
2399 * @param int $userid (optional) the userid
2400 * @return bool true on success, false otherwise
2402 function tag_delete_instance($record_type, $record_id, $tagid, $userid = null) {
2403 debugging('Function tag_delete_instance() is deprecated and replaced with core_tag_tag::remove_item_tag() instead. ' .
2404 'Component is required for retrieving instances', DEBUG_DEVELOPER);
2405 $tag = core_tag_tag::get($tagid);
2406 core_tag_tag::remove_item_tag('', $record_type, $record_id, $tag->rawname, $userid);
2410 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
2412 * @package core_tag
2413 * @deprecated since 3.1
2414 * @category tag
2415 * @param string $tag tag to look for
2416 * @param string $type type to restrict search to. If null, every matching record will be returned
2417 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
2418 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
2419 * @return array of matching objects, indexed by record id, from the table containing the type requested
2421 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
2422 debugging('Function tag_find_records() is deprecated and replaced with core_tag_tag::get_by_name()->get_tagged_items(). '.
2423 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2425 if (!$tag || !$type) {
2426 return array();
2429 $tagobject = core_tag_tag::get_by_name(core_tag_area::get_collection('', $type), $tag);
2430 return $tagobject->get_tagged_items('', $type, $limitfrom, $limitnum);
2434 * Adds one or more tag in the database. This function should not be called directly : you should
2435 * use tag_set.
2437 * @package core_tag
2438 * @deprecated since 3.1
2439 * @param mixed $tags one tag, or an array of tags, to be created
2440 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
2441 * value at this time). An official tag is kept even if there are no records tagged with it.
2442 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
2443 * adding the tag.
2445 function tag_add($tags, $type="default") {
2446 debugging('Function tag_add() is deprecated. You can use core_tag_tag::create_if_missing(), however it should not be necessary ' .
2447 'since tags are created automatically when assigned to items', DEBUG_DEVELOPER);
2448 if (!is_array($tags)) {
2449 $tags = array($tags);
2451 $objects = core_tag_tag::create_if_missing(core_tag_collection::get_default(), $tags,
2452 $type === 'official');
2454 // New function returns the tags in different format, for BC we keep the format that this function used to have.
2455 $rv = array();
2456 foreach ($objects as $name => $tagobject) {
2457 if (isset($tagobject->id)) {
2458 $rv[$tagobject->name] = $tagobject->id;
2459 } else {
2460 $rv[$name] = false;
2463 return $rv;
2467 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
2469 * @package core_tag
2470 * @deprecated since 3.1
2471 * @param string $record_type the type of the record that will be tagged
2472 * @param int $record_id the id of the record that will be tagged
2473 * @param string $tagid the tag id to set on the record.
2474 * @param int $ordering the order of the instance for this record
2475 * @param int $userid (optional) only required for course tagging
2476 * @param string|null $component the component that was tagged
2477 * @param int|null $contextid the context id of where this tag was assigned
2478 * @return bool true on success, false otherwise
2480 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
2481 global $DB;
2482 $message = 'Function tag_assign() is deprecated. Use core_tag_tag::set_item_tags() or core_tag_tag::add_item_tag() instead. ' .
2483 'Tag instance ordering should not be set manually';
2484 if ($component === null || $contextid === null) {
2485 $message .= '. You should specify the component and contextid of the item being tagged in your call to tag_assign.';
2487 debugging($message, DEBUG_DEVELOPER);
2489 if ($contextid) {
2490 $context = context::instance_by_id($contextid);
2491 } else {
2492 $context = context_system::instance();
2495 // Get the tag.
2496 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
2498 $taginstanceid = core_tag_tag::add_item_tag($component, $record_type, $record_id, $context, $tag->rawname, $userid);
2500 // Alter the "ordering" of tag_instance. This should never be done manually and only remains here for the backward compatibility.
2501 $taginstance = new stdClass();
2502 $taginstance->id = $taginstanceid;
2503 $taginstance->ordering = $ordering;
2504 $taginstance->timemodified = time();
2506 $DB->update_record('tag_instance', $taginstance);
2508 return true;
2512 * Count how many records are tagged with a specific tag.
2514 * @package core_tag
2515 * @deprecated since 3.1
2516 * @param string $record_type record to look for ('post', 'user', etc.)
2517 * @param int $tagid is a single tag id
2518 * @return int number of mathing tags.
2520 function tag_record_count($record_type, $tagid) {
2521 debugging('Method tag_record_count() is deprecated and replaced with core_tag_tag::get($tagid)->count_tagged_items(). '.
2522 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2523 return core_tag_tag::get($tagid)->count_tagged_items('', $record_type);
2527 * Determine if a record is tagged with a specific tag
2529 * @package core_tag
2530 * @deprecated since 3.1
2531 * @param string $record_type the record type to look for
2532 * @param int $record_id the record id to look for
2533 * @param string $tag a tag name
2534 * @return bool/int true if it is tagged, 0 (false) otherwise
2536 function tag_record_tagged_with($record_type, $record_id, $tag) {
2537 debugging('Method tag_record_tagged_with() is deprecated and replaced with core_tag_tag::get($tagid)->is_item_tagged_with(). '.
2538 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2539 return core_tag_tag::is_item_tagged_with('', $record_type, $record_id, $tag);
2543 * Flag a tag as inappropriate.
2545 * @deprecated since 3.1
2546 * @param int|array $tagids a single tagid, or an array of tagids
2548 function tag_set_flag($tagids) {
2549 debugging('Function tag_set_flag() is deprecated and replaced with core_tag_tag::get($tagid)->flag().', DEBUG_DEVELOPER);
2550 $tagids = (array) $tagids;
2551 foreach ($tagids as $tagid) {
2552 if ($tag = core_tag_tag::get($tagid, '*')) {
2553 $tag->flag();
2559 * Remove the inappropriate flag on a tag.
2561 * @deprecated since 3.1
2562 * @param int|array $tagids a single tagid, or an array of tagids
2564 function tag_unset_flag($tagids) {
2565 debugging('Function tag_unset_flag() is deprecated and replaced with core_tag_tag::get($tagid)->reset_flag().', DEBUG_DEVELOPER);
2566 $tagids = (array) $tagids;
2567 foreach ($tagids as $tagid) {
2568 if ($tag = core_tag_tag::get($tagid, '*')) {
2569 $tag->reset_flag();
2575 * Prints or returns a HTML tag cloud with varying classes styles depending on the popularity and type of each tag.
2577 * @deprecated since 3.1
2579 * @param array $tagset Array of tags to display
2580 * @param int $nr_of_tags Limit for the number of tags to return/display, used if $tagset is null
2581 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2582 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
2583 * @return string|null a HTML string or null if this function does the output
2585 function tag_print_cloud($tagset=null, $nr_of_tags=150, $return=false, $sort='') {
2586 global $OUTPUT;
2588 debugging('Function tag_print_cloud() is deprecated and replaced with function core_tag_collection::get_tag_cloud(), '
2589 . 'templateable core_tag\output\tagcloud and template core_tag/tagcloud.', DEBUG_DEVELOPER);
2591 // Set up sort global - used to pass sort type into core_tag_collection::cloud_sort through usort() avoiding multiple sort functions.
2592 if ($sort == 'popularity') {
2593 $sort = 'count';
2594 } else if ($sort == 'date') {
2595 $sort = 'timemodified';
2596 } else {
2597 $sort = 'name';
2600 if (is_null($tagset)) {
2601 // No tag set received, so fetch tags from database.
2602 // Always add query by tagcollid even when it's not known to make use of the table index.
2603 $tagcloud = core_tag_collection::get_tag_cloud(0, false, $nr_of_tags, $sort);
2604 } else {
2605 $tagsincloud = $tagset;
2607 $etags = array();
2608 foreach ($tagsincloud as $tag) {
2609 $etags[] = $tag;
2612 core_tag_collection::$cloudsortfield = $sort;
2613 usort($tagsincloud, "core_tag_collection::cloud_sort");
2615 $tagcloud = new \core_tag\output\tagcloud($tagsincloud);
2618 $output = $OUTPUT->render_from_template('core_tag/tagcloud', $tagcloud->export_for_template($OUTPUT));
2619 if ($return) {
2620 return $output;
2621 } else {
2622 echo $output;
2627 * Function that returns tags that start with some text, for use by the autocomplete feature
2629 * @package core_tag
2630 * @deprecated since 3.0
2631 * @access private
2632 * @param string $text string that the tag names will be matched against
2633 * @return mixed an array of objects, or false if no records were found or an error occured.
2635 function tag_autocomplete($text) {
2636 debugging('Function tag_autocomplete() is deprecated without replacement. ' .
2637 'New form element "tags" does proper autocomplete.', DEBUG_DEVELOPER);
2638 global $DB;
2639 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
2640 FROM {tag} tg
2641 WHERE tg.name LIKE ?", array(core_text::strtolower($text)."%"));
2645 * Prints a box with the description of a tag and its related tags
2647 * @package core_tag
2648 * @deprecated since 3.1
2649 * @param stdClass $tag_object
2650 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2651 * @return string/null a HTML box showing a description of the tag object and it's relationsips or null if output is done directly
2652 * in the function.
2654 function tag_print_description_box($tag_object, $return=false) {
2655 global $USER, $CFG, $OUTPUT;
2656 require_once($CFG->libdir.'/filelib.php');
2658 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2659 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2661 $relatedtags = array();
2662 if ($tag = core_tag_tag::get($tag_object->id)) {
2663 $relatedtags = $tag->get_related_tags();
2666 $content = !empty($tag_object->description);
2667 $output = '';
2669 if ($content) {
2670 $output .= $OUTPUT->box_start('generalbox tag-description');
2673 if (!empty($tag_object->description)) {
2674 $options = new stdClass();
2675 $options->para = false;
2676 $options->overflowdiv = true;
2677 $tag_object->description = file_rewrite_pluginfile_urls($tag_object->description, 'pluginfile.php', context_system::instance()->id, 'tag', 'description', $tag_object->id);
2678 $output .= format_text($tag_object->description, $tag_object->descriptionformat, $options);
2681 if ($content) {
2682 $output .= $OUTPUT->box_end();
2685 if ($relatedtags) {
2686 $output .= $OUTPUT->tag_list($relatedtags, get_string('relatedtags', 'tag'), 'tag-relatedtags');
2689 if ($return) {
2690 return $output;
2691 } else {
2692 echo $output;
2697 * Prints a box that contains the management links of a tag
2699 * @deprecated since 3.1
2700 * @param core_tag_tag|stdClass $tag_object
2701 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2702 * @return string|null a HTML string or null if this function does the output
2704 function tag_print_management_box($tag_object, $return=false) {
2705 global $USER, $CFG, $OUTPUT;
2707 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2708 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2710 $tagname = core_tag_tag::make_display_name($tag_object);
2711 $output = '';
2713 if (!isguestuser()) {
2714 $output .= $OUTPUT->box_start('box','tag-management-box');
2715 $systemcontext = context_system::instance();
2716 $links = array();
2718 // Add a link for users to add/remove this from their interests
2719 if (core_tag_tag::is_enabled('core', 'user') && core_tag_area::get_collection('core', 'user') == $tag_object->tagcollid) {
2720 if (core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $tag_object->name)) {
2721 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=removeinterest&amp;sesskey='. sesskey() .
2722 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
2723 get_string('removetagfrommyinterests', 'tag', $tagname) .'</a>';
2724 } else {
2725 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=addinterest&amp;sesskey='. sesskey() .
2726 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
2727 get_string('addtagtomyinterests', 'tag', $tagname) .'</a>';
2731 // Flag as inappropriate link. Only people with moodle/tag:flag capability.
2732 if (has_capability('moodle/tag:flag', $systemcontext)) {
2733 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=flaginappropriate&amp;sesskey='.
2734 sesskey() . '&amp;id='. $tag_object->id . '">'. get_string('flagasinappropriate',
2735 'tag', rawurlencode($tagname)) .'</a>';
2738 // Edit tag: Only people with moodle/tag:edit capability who either have it as an interest or can manage tags
2739 if (has_capability('moodle/tag:edit', $systemcontext) ||
2740 has_capability('moodle/tag:manage', $systemcontext)) {
2741 $links[] = '<a href="' . $CFG->wwwroot . '/tag/edit.php?id=' . $tag_object->id . '">' .
2742 get_string('edittag', 'tag') . '</a>';
2745 $output .= implode(' | ', $links);
2746 $output .= $OUTPUT->box_end();
2749 if ($return) {
2750 return $output;
2751 } else {
2752 echo $output;
2757 * Prints the tag search box
2759 * @deprecated since 3.1
2760 * @param bool $return if true return html string
2761 * @return string|null a HTML string or null if this function does the output
2763 function tag_print_search_box($return=false) {
2764 global $CFG, $OUTPUT;
2766 debugging('Function tag_print_search_box() is deprecated without replacement. ' .
2767 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2769 $query = optional_param('query', '', PARAM_RAW);
2771 $output = $OUTPUT->box_start('','tag-search-box');
2772 $output .= '<form action="'.$CFG->wwwroot.'/tag/search.php" style="display:inline">';
2773 $output .= '<div>';
2774 $output .= '<label class="accesshide" for="searchform_search">'.get_string('searchtags', 'tag').'</label>';
2775 $output .= '<input id="searchform_search" name="query" type="text" size="40" value="'.s($query).'" />';
2776 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
2777 $output .= '</div>';
2778 $output .= '</form>';
2779 $output .= $OUTPUT->box_end();
2781 if ($return) {
2782 return $output;
2784 else {
2785 echo $output;
2790 * Prints the tag search results
2792 * @deprecated since 3.1
2793 * @param string $query text that tag names will be matched against
2794 * @param int $page current page
2795 * @param int $perpage nr of users displayed per page
2796 * @param bool $return if true return html string
2797 * @return string|null a HTML string or null if this function does the output
2799 function tag_print_search_results($query, $page, $perpage, $return=false) {
2800 global $CFG, $USER, $OUTPUT;
2802 debugging('Function tag_print_search_results() is deprecated without replacement. ' .
2803 'In /tag/search.php the search results are printed using the core_tag/tagcloud template.', DEBUG_DEVELOPER);
2805 $query = clean_param($query, PARAM_TAG);
2807 $count = count(tag_find_tags($query, false));
2808 $tags = array();
2810 if ( $found_tags = tag_find_tags($query, true, $page * $perpage, $perpage) ) {
2811 $tags = array_values($found_tags);
2814 $baseurl = $CFG->wwwroot.'/tag/search.php?query='. rawurlencode($query);
2815 $output = '';
2817 // link "Add $query to my interests"
2818 $addtaglink = '';
2819 if (core_tag_tag::is_enabled('core', 'user') && !core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $query)) {
2820 $addtaglink = html_writer::link(new moodle_url('/tag/user.php', array('action' => 'addinterest', 'sesskey' => sesskey(),
2821 'tag' => $query)), get_string('addtagtomyinterests', 'tag', s($query)));
2824 if ( !empty($tags) ) { // there are results to display!!
2825 $output .= $OUTPUT->heading(get_string('searchresultsfor', 'tag', htmlspecialchars($query)) ." : {$count}", 3, 'main');
2827 //print a link "Add $query to my interests"
2828 if (!empty($addtaglink)) {
2829 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2832 $nr_of_lis_per_ul = 6;
2833 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul );
2835 $output .= '<ul id="tag-search-results">';
2836 for($i = 0; $i < $nr_of_uls; $i++) {
2837 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul) as $tag) {
2838 $output .= '<li>';
2839 $tag_link = html_writer::link(core_tag_tag::make_url($tag->tagcollid, $tag->rawname),
2840 core_tag_tag::make_display_name($tag));
2841 $output .= $tag_link;
2842 $output .= '</li>';
2845 $output .= '</ul>';
2846 $output .= '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
2848 $output .= $OUTPUT->paging_bar($count, $page, $perpage, $baseurl);
2850 else { //no results were found!!
2851 $output .= $OUTPUT->heading(get_string('noresultsfor', 'tag', htmlspecialchars($query)), 3, 'main');
2853 //print a link "Add $query to my interests"
2854 if (!empty($addtaglink)) {
2855 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2859 if ($return) {
2860 return $output;
2862 else {
2863 echo $output;
2868 * Prints a table of the users tagged with the tag passed as argument
2870 * @deprecated since 3.1
2871 * @param stdClass $tagobject the tag we wish to return data for
2872 * @param int $limitfrom (optional, required if $limitnum is set) prints users starting at this point.
2873 * @param int $limitnum (optional, required if $limitfrom is set) prints this many users.
2874 * @param bool $return if true return html string
2875 * @return string|null a HTML string or null if this function does the output
2877 function tag_print_tagged_users_table($tagobject, $limitfrom='', $limitnum='', $return=false) {
2879 debugging('Function tag_print_tagged_users_table() is deprecated without replacement. ' .
2880 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2882 //List of users with this tag
2883 $tagobject = core_tag_tag::get($tagobject->id);
2884 $userlist = $tagobject->get_tagged_items('core', 'user', $limitfrom, $limitnum);
2886 $output = tag_print_user_list($userlist, true);
2888 if ($return) {
2889 return $output;
2891 else {
2892 echo $output;
2897 * Prints an individual user box
2899 * @deprecated since 3.1
2900 * @param user_object $user (contains the following fields: id, firstname, lastname and picture)
2901 * @param bool $return if true return html string
2902 * @return string|null a HTML string or null if this function does the output
2904 function tag_print_user_box($user, $return=false) {
2905 global $CFG, $OUTPUT;
2907 debugging('Function tag_print_user_box() is deprecated without replacement. ' .
2908 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2910 $usercontext = context_user::instance($user->id);
2911 $profilelink = '';
2913 if ($usercontext and (has_capability('moodle/user:viewdetails', $usercontext) || has_coursecontact_role($user->id))) {
2914 $profilelink = $CFG->wwwroot .'/user/view.php?id='. $user->id;
2917 $output = $OUTPUT->box_start('user-box', 'user'. $user->id);
2918 $fullname = fullname($user);
2919 $alt = '';
2921 if (!empty($profilelink)) {
2922 $output .= '<a href="'. $profilelink .'">';
2923 $alt = $fullname;
2926 $output .= $OUTPUT->user_picture($user, array('size'=>100));
2927 $output .= '<br />';
2929 if (!empty($profilelink)) {
2930 $output .= '</a>';
2933 //truncate name if it's too big
2934 if (core_text::strlen($fullname) > 26) {
2935 $fullname = core_text::substr($fullname, 0, 26) .'...';
2938 $output .= '<strong>'. $fullname .'</strong>';
2939 $output .= $OUTPUT->box_end();
2941 if ($return) {
2942 return $output;
2944 else {
2945 echo $output;
2950 * Prints a list of users
2952 * @deprecated since 3.1
2953 * @param array $userlist an array of user objects
2954 * @param bool $return if true return html string, otherwise output the result
2955 * @return string|null a HTML string or null if this function does the output
2957 function tag_print_user_list($userlist, $return=false) {
2959 debugging('Function tag_print_user_list() is deprecated without replacement. ' .
2960 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2962 $output = '<div><ul class="inline-list">';
2964 foreach ($userlist as $user){
2965 $output .= '<li>'. tag_print_user_box($user, true) ."</li>\n";
2967 $output .= "</ul></div>\n";
2969 if ($return) {
2970 return $output;
2972 else {
2973 echo $output;
2978 * Function that returns the name that should be displayed for a specific tag
2980 * @package core_tag
2981 * @category tag
2982 * @deprecated since 3.1
2983 * @param stdClass|core_tag_tag $tagobject a line out of tag table, as returned by the adobd functions
2984 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
2985 * @return string
2987 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
2988 debugging('Function tag_display_name() is deprecated. Use core_tag_tag::make_display_name().', DEBUG_DEVELOPER);
2989 if (!isset($tagobject->name)) {
2990 return '';
2992 return core_tag_tag::make_display_name($tagobject, $html != TAG_RETURN_TEXT);
2996 * Function that normalizes a list of tag names.
2998 * @package core_tag
2999 * @deprecated since 3.1
3000 * @param array/string $rawtags array of tags, or a single tag.
3001 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
3002 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
3003 * (Eg: 'Banana' => 'banana').
3005 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
3006 debugging('Function tag_normalize() is deprecated. Use core_tag_tag::normalize().', DEBUG_DEVELOPER);
3008 if ( !is_array($rawtags) ) {
3009 $rawtags = array($rawtags);
3012 return core_tag_tag::normalize($rawtags, $case == TAG_CASE_LOWER);
3016 * Get a comma-separated list of tags related to another tag.
3018 * @package core_tag
3019 * @deprecated since 3.1
3020 * @param array $related_tags the array returned by tag_get_related_tags
3021 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
3022 * @return string comma-separated list
3024 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
3025 global $OUTPUT;
3026 debugging('Method tag_get_related_tags_csv() is deprecated. Consider '
3027 . 'looping through array or using $OUTPUT->tag_list(core_tag_tag::get_item_tags())',
3028 DEBUG_DEVELOPER);
3029 if ($html != TAG_RETURN_TEXT) {
3030 return $OUTPUT->tag_list($related_tags, '');
3033 $tagsnames = array();
3034 foreach ($related_tags as $tag) {
3035 $tagsnames[] = core_tag_tag::make_display_name($tag, false);
3037 return implode(', ', $tagsnames);
3041 * Used to require that the return value from a function is an array.
3042 * Only used in the deprecated function {@link tag_get_id()}
3043 * @deprecated since 3.1
3045 define('TAG_RETURN_ARRAY', 0);
3047 * Used to require that the return value from a function is an object.
3048 * Only used in the deprecated function {@link tag_get_id()}
3049 * @deprecated since 3.1
3051 define('TAG_RETURN_OBJECT', 1);
3053 * Use to specify that HTML free text is expected to be returned from a function.
3054 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3055 * {@link tag_get_related_tags_csv()}
3056 * @deprecated since 3.1
3058 define('TAG_RETURN_TEXT', 2);
3060 * Use to specify that encoded HTML is expected to be returned from a function.
3061 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3062 * {@link tag_get_related_tags_csv()}
3063 * @deprecated since 3.1
3065 define('TAG_RETURN_HTML', 3);
3068 * Used to specify that we wish a lowercased string to be returned
3069 * Only used in deprecated function {@link tag_normalize()}
3070 * @deprecated since 3.1
3072 define('TAG_CASE_LOWER', 0);
3074 * Used to specify that we do not wish the case of the returned string to change
3075 * Only used in deprecated function {@link tag_normalize()}
3076 * @deprecated since 3.1
3078 define('TAG_CASE_ORIGINAL', 1);
3081 * Used to specify that we want all related tags returned, no matter how they are related.
3082 * Only used in deprecated function {@link tag_get_related_tags()}
3083 * @deprecated since 3.1
3085 define('TAG_RELATED_ALL', 0);
3087 * Used to specify that we only want back tags that were manually related.
3088 * Only used in deprecated function {@link tag_get_related_tags()}
3089 * @deprecated since 3.1
3091 define('TAG_RELATED_MANUAL', 1);
3093 * Used to specify that we only want back tags where the relationship was automatically correlated.
3094 * Only used in deprecated function {@link tag_get_related_tags()}
3095 * @deprecated since 3.1
3097 define('TAG_RELATED_CORRELATED', 2);
3100 * Set the tags assigned to a record. This overwrites the current tags.
3102 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
3104 * Due to API change $component and $contextid are now required. Instead of
3105 * calling this function you can use {@link core_tag_tag::set_item_tags()} or
3106 * {@link core_tag_tag::set_related_tags()}
3108 * @package core_tag
3109 * @deprecated since 3.1
3110 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, 'tag' for tags, etc.)
3111 * @param int $itemid the id of the record to tag
3112 * @param array $tags the array of tags to set on the record. If given an empty array, all tags will be removed.
3113 * @param string|null $component the component that was tagged
3114 * @param int|null $contextid the context id of where this tag was assigned
3115 * @return bool|null
3117 function tag_set($itemtype, $itemid, $tags, $component = null, $contextid = null) {
3118 debugging('Function tag_set() is deprecated. Use ' .
3119 ' core_tag_tag::set_item_tags() instead', DEBUG_DEVELOPER);
3121 if ($itemtype === 'tag') {
3122 return core_tag_tag::get($itemid, '*', MUST_EXIST)->set_related_tags($tags);
3123 } else {
3124 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3125 return core_tag_tag::set_item_tags($component, $itemtype, $itemid, $context, $tags);
3130 * Adds a tag to a record, without overwriting the current tags.
3132 * This function remains here for backward compatiblity. It is recommended to use
3133 * {@link core_tag_tag::add_item_tag()} or {@link core_tag_tag::add_related_tags()} instead
3135 * @package core_tag
3136 * @deprecated since 3.1
3137 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3138 * @param int $itemid the id of the record to tag
3139 * @param string $tag the tag to add
3140 * @param string|null $component the component that was tagged
3141 * @param int|null $contextid the context id of where this tag was assigned
3142 * @return bool|null
3144 function tag_set_add($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3145 debugging('Function tag_set_add() is deprecated. Use ' .
3146 ' core_tag_tag::add_item_tag() instead', DEBUG_DEVELOPER);
3148 if ($itemtype === 'tag') {
3149 return core_tag_tag::get($itemid, '*', MUST_EXIST)->add_related_tags(array($tag));
3150 } else {
3151 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3152 return core_tag_tag::add_item_tag($component, $itemtype, $itemid, $context, $tag);
3157 * Removes a tag from a record, without overwriting other current tags.
3159 * This function remains here for backward compatiblity. It is recommended to use
3160 * {@link core_tag_tag::remove_item_tag()} instead
3162 * @package core_tag
3163 * @deprecated since 3.1
3164 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3165 * @param int $itemid the id of the record to tag
3166 * @param string $tag the tag to delete
3167 * @param string|null $component the component that was tagged
3168 * @param int|null $contextid the context id of where this tag was assigned
3169 * @return bool|null
3171 function tag_set_delete($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3172 debugging('Function tag_set_delete() is deprecated. Use ' .
3173 ' core_tag_tag::remove_item_tag() instead', DEBUG_DEVELOPER);
3174 return core_tag_tag::remove_item_tag($component, $itemtype, $itemid, $tag);
3178 * Simple function to just return a single tag object when you know the name or something
3180 * See also {@link core_tag_tag::get()} and {@link core_tag_tag::get_by_name()}
3182 * @package core_tag
3183 * @deprecated since 3.1
3184 * @param string $field which field do we use to identify the tag: id, name or rawname
3185 * @param string $value the required value of the aforementioned field
3186 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
3187 * 'id', 'name', 'rawname' or '*' to include all fields.
3188 * @return mixed tag object
3190 function tag_get($field, $value, $returnfields='id, name, rawname, tagcollid') {
3191 global $DB;
3192 debugging('Function tag_get() is deprecated. Use ' .
3193 ' core_tag_tag::get() or core_tag_tag::get_by_name()',
3194 DEBUG_DEVELOPER);
3195 if ($field === 'id') {
3196 $tag = core_tag_tag::get((int)$value, $returnfields);
3197 } else if ($field === 'name') {
3198 $tag = core_tag_tag::get_by_name(0, $value, $returnfields);
3199 } else {
3200 $params = array($field => $value);
3201 return $DB->get_record('tag', $params, $returnfields);
3203 if ($tag) {
3204 return $tag->to_object();
3206 return null;
3210 * Returns tags related to a tag
3212 * Related tags of a tag come from two sources:
3213 * - manually added related tags, which are tag_instance entries for that tag
3214 * - correlated tags, which are calculated
3216 * @package core_tag
3217 * @deprecated since 3.1
3218 * @param string $tagid is a single **normalized** tag name or the id of a tag
3219 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
3220 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
3221 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
3222 * @return array an array of tag objects
3224 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
3225 debugging('Method tag_get_related_tags() is deprecated, '
3226 . 'use core_tag_tag::get_correlated_tags(), core_tag_tag::get_related_tags() or '
3227 . 'core_tag_tag::get_manual_related_tags()', DEBUG_DEVELOPER);
3228 $result = array();
3229 if ($tag = core_tag_tag::get($tagid)) {
3230 if ($type == TAG_RELATED_CORRELATED) {
3231 $tags = $tag->get_correlated_tags();
3232 } else if ($type == TAG_RELATED_MANUAL) {
3233 $tags = $tag->get_manual_related_tags();
3234 } else {
3235 $tags = $tag->get_related_tags();
3237 $tags = array_slice($tags, 0, $limitnum);
3238 foreach ($tags as $id => $tag) {
3239 $result[$id] = $tag->to_object();
3242 return $result;
3246 * Delete one or more tag, and all their instances if there are any left.
3248 * @package core_tag
3249 * @deprecated since 3.1
3250 * @param mixed $tagids one tagid (int), or one array of tagids to delete
3251 * @return bool true on success, false otherwise
3253 function tag_delete($tagids) {
3254 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_tags()',
3255 DEBUG_DEVELOPER);
3256 return core_tag_tag::delete_tags($tagids);
3260 * Deletes all the tag instances given a component and an optional contextid.
3262 * @deprecated since 3.1
3263 * @param string $component
3264 * @param int $contextid if null, then we delete all tag instances for the $component
3266 function tag_delete_instances($component, $contextid = null) {
3267 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_instances()',
3268 DEBUG_DEVELOPER);
3269 core_tag_tag::delete_instances($component, null, $contextid);
3273 * Clean up the tag tables, making sure all tagged object still exists.
3275 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
3276 * done once in a while, perhaps on an occasional cron run. On a site with lots of tags, this could become an expensive function to
3277 * call: don't run at peak time.
3279 * @package core_tag
3280 * @deprecated since 3.1
3282 function tag_cleanup() {
3283 debugging('Method tag_cleanup() is deprecated, use \core\task\tag_cron_task::cleanup()',
3284 DEBUG_DEVELOPER);
3286 $task = new \core\task\tag_cron_task();
3287 return $task->cleanup();
3291 * This function will delete numerous tag instances efficiently.
3292 * This removes tag instances only. It doesn't check to see if it is the last use of a tag.
3294 * @deprecated since 3.1
3295 * @param array $instances An array of tag instance objects with the addition of the tagname and tagrawname
3296 * (used for recording a delete event).
3298 function tag_bulk_delete_instances($instances) {
3299 debugging('Method tag_bulk_delete_instances() is deprecated, '
3300 . 'use \core\task\tag_cron_task::bulk_delete_instances()',
3301 DEBUG_DEVELOPER);
3303 $task = new \core\task\tag_cron_task();
3304 return $task->bulk_delete_instances($instances);
3308 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
3310 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
3312 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
3313 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
3315 * @package core_tag
3316 * @deprecated since 3.1
3317 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
3319 function tag_compute_correlations($mincorrelation = 2) {
3320 debugging('Method tag_compute_correlations() is deprecated, '
3321 . 'use \core\task\tag_cron_task::compute_correlations()',
3322 DEBUG_DEVELOPER);
3324 $task = new \core\task\tag_cron_task();
3325 return $task->compute_correlations($mincorrelation);
3329 * This function processes a tag correlation and makes changes in the database as required.
3331 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
3333 * @package core_tag
3334 * @deprecated since 3.1
3335 * @param stdClass $tagcorrelation
3336 * @return int/bool The id of the tag correlation that was just processed or false.
3338 function tag_process_computed_correlation(stdClass $tagcorrelation) {
3339 debugging('Method tag_process_computed_correlation() is deprecated, '
3340 . 'use \core\task\tag_cron_task::process_computed_correlation()',
3341 DEBUG_DEVELOPER);
3343 $task = new \core\task\tag_cron_task();
3344 return $task->process_computed_correlation($tagcorrelation);
3348 * Tasks that should be performed at cron time
3350 * @package core_tag
3351 * @deprecated since 3.1
3353 function tag_cron() {
3354 debugging('Method tag_cron() is deprecated, use \core\task\tag_cron_task::execute()',
3355 DEBUG_DEVELOPER);
3357 $task = new \core\task\tag_cron_task();
3358 $task->execute();
3362 * Search for tags with names that match some text
3364 * @package core_tag
3365 * @deprecated since 3.1
3366 * @param string $text escaped string that the tag names will be matched against
3367 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
3368 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
3369 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
3370 * @param int $tagcollid
3371 * @return array/boolean an array of objects, or false if no records were found or an error occured.
3373 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='', $tagcollid = null) {
3374 debugging('Method tag_find_tags() is deprecated without replacement', DEBUG_DEVELOPER);
3375 global $DB;
3377 $text = core_text::strtolower(clean_param($text, PARAM_TAG));
3379 list($sql, $params) = $DB->get_in_or_equal($tagcollid ? array($tagcollid) :
3380 array_keys(core_tag_collection::get_collections(true)));
3381 array_unshift($params, "%{$text}%");
3383 if ($ordered) {
3384 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid, COUNT(ti.id) AS count
3385 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
3386 WHERE tg.name LIKE ? AND tg.tagcollid $sql
3387 GROUP BY tg.id, tg.name, tg.rawname
3388 ORDER BY count DESC";
3389 } else {
3390 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid
3391 FROM {tag} tg
3392 WHERE tg.name LIKE ? AND tg.tagcollid $sql";
3394 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
3398 * Get the name of a tag
3400 * @package core_tag
3401 * @deprecated since 3.1
3402 * @param mixed $tagids the id of the tag, or an array of ids
3403 * @return mixed string name of one tag, or id-indexed array of strings
3405 function tag_get_name($tagids) {
3406 debugging('Method tag_get_name() is deprecated without replacement', DEBUG_DEVELOPER);
3407 global $DB;
3409 if (!is_array($tagids)) {
3410 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
3411 return $tag->name;
3413 return false;
3416 $tag_names = array();
3417 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
3418 $tag_names[$tag->id] = $tag->name;
3421 return $tag_names;
3425 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
3426 * empty and this function won't return anything.
3428 * Correlated tags are calculated in cron based on existing tag instances.
3430 * @package core_tag
3431 * @deprecated since 3.1
3432 * @param int $tagid is a single tag id
3433 * @param int $notused this argument is no longer used
3434 * @return array an array of tag objects or an empty if no correlated tags are found
3436 function tag_get_correlated($tagid, $notused = null) {
3437 debugging('Method tag_get_correlated() is deprecated, '
3438 . 'use core_tag_tag::get_correlated_tags()', DEBUG_DEVELOPER);
3439 $result = array();
3440 if ($tag = core_tag_tag::get($tagid)) {
3441 $tags = $tag->get_correlated_tags(true);
3442 // Convert to objects for backward-compatibility.
3443 foreach ($tags as $id => $tag) {
3444 $result[$id] = $tag->to_object();
3447 return $result;
3451 * This function is used by print_tag_cloud, to usort() the tags in the cloud. See php.net/usort for the parameters documentation.
3452 * This was originally in blocks/blog_tags/block_blog_tags.php, named blog_tags_sort().
3454 * @package core_tag
3455 * @deprecated since 3.1
3456 * @param string $a Tag name to compare against $b
3457 * @param string $b Tag name to compare against $a
3458 * @return int The result of the comparison/validation 1, 0 or -1
3460 function tag_cloud_sort($a, $b) {
3461 debugging('Method tag_cloud_sort() is deprecated, similar method can be found in core_tag_collection::cloud_sort()', DEBUG_DEVELOPER);
3462 global $CFG;
3464 if (empty($CFG->tagsort)) {
3465 $tagsort = 'name'; // by default, sort by name
3466 } else {
3467 $tagsort = $CFG->tagsort;
3470 if (is_numeric($a->$tagsort)) {
3471 return ($a->$tagsort == $b->$tagsort) ? 0 : ($a->$tagsort > $b->$tagsort) ? 1 : -1;
3472 } elseif (is_string($a->$tagsort)) {
3473 return strcmp($a->$tagsort, $b->$tagsort);
3474 } else {
3475 return 0;
3480 * @deprecated since Moodle 3.1
3482 function events_load_def() {
3483 throw new coding_exception('events_load_def() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3488 * @deprecated since Moodle 3.1
3490 function events_queue_handler() {
3491 throw new coding_exception('events_queue_handler() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3495 * @deprecated since Moodle 3.1
3497 function events_dispatch() {
3498 throw new coding_exception('events_dispatch() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3502 * @deprecated since Moodle 3.1
3504 function events_process_queued_handler() {
3505 throw new coding_exception(
3506 'events_process_queued_handler() has been deprecated along with all Events 1 API in favour of Events 2 API.'
3511 * @deprecated since Moodle 3.1
3513 function events_update_definition() {
3514 throw new coding_exception(
3515 'events_update_definition has been deprecated along with all Events 1 API in favour of Events 2 API.'
3520 * @deprecated since Moodle 3.1
3522 function events_cron() {
3523 throw new coding_exception('events_cron() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3527 * @deprecated since Moodle 3.1
3529 function events_trigger_legacy() {
3530 throw new coding_exception('events_trigger_legacy() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3534 * @deprecated since Moodle 3.1
3536 function events_is_registered() {
3537 throw new coding_exception('events_is_registered() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3541 * @deprecated since Moodle 3.1
3543 function events_pending_count() {
3544 throw new coding_exception('events_pending_count() has been deprecated along with all Events 1 API in favour of Events 2 API.');
3548 * Emails admins about a clam outcome
3550 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
3551 * @param string $notice The body of the email to be sent.
3552 * @return void
3554 function clam_message_admins($notice) {
3555 debugging('clam_message_admins() is deprecated, please use message_admins() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
3557 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
3558 $antivirus->message_admins($notice);
3562 * Returns the string equivalent of a numeric clam error code
3564 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
3565 * @param int $returncode The numeric error code in question.
3566 * @return string The definition of the error code
3568 function get_clam_error_code($returncode) {
3569 debugging('get_clam_error_code() is deprecated, please use get_clam_error_code() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
3571 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
3572 return $antivirus->get_clam_error_code($returncode);
3576 * Returns the rename action.
3578 * @deprecated since 3.1
3579 * @param cm_info $mod The module to produce editing buttons for
3580 * @param int $sr The section to link back to (used for creating the links)
3581 * @return The markup for the rename action, or an empty string if not available.
3583 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
3584 global $COURSE, $OUTPUT;
3586 static $str;
3587 static $baseurl;
3589 debugging('Function course_get_cm_rename_action() is deprecated. Please use inplace_editable ' .
3590 'https://docs.moodle.org/dev/Inplace_editable', DEBUG_DEVELOPER);
3592 $modcontext = context_module::instance($mod->id);
3593 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3595 if (!isset($str)) {
3596 $str = get_strings(array('edittitle'));
3599 if (!isset($baseurl)) {
3600 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3603 if ($sr !== null) {
3604 $baseurl->param('sr', $sr);
3607 // AJAX edit title.
3608 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
3609 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
3610 // we will not display link if we are on some other-course page (where we should not see this module anyway)
3611 return html_writer::span(
3612 html_writer::link(
3613 new moodle_url($baseurl, array('update' => $mod->id)),
3614 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
3615 array(
3616 'class' => 'editing_title',
3617 'data-action' => 'edittitle',
3618 'title' => $str->edittitle,
3623 return '';
3627 * This function returns the number of activities using the given scale in the given course.
3629 * @deprecated since Moodle 3.1
3630 * @param int $courseid The course ID to check.
3631 * @param int $scaleid The scale ID to check
3632 * @return int
3634 function course_scale_used($courseid, $scaleid) {
3635 global $CFG, $DB;
3637 debugging('course_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
3638 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
3640 $return = 0;
3642 if (!empty($scaleid)) {
3643 if ($cms = get_course_mods($courseid)) {
3644 foreach ($cms as $cm) {
3645 // Check cm->name/lib.php exists.
3646 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
3647 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
3648 $functionname = $cm->modname.'_scale_used';
3649 if (function_exists($functionname)) {
3650 if ($functionname($cm->instance, $scaleid)) {
3651 $return++;
3658 // Check if any course grade item makes use of the scale.
3659 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
3661 // Check if any outcome in the course makes use of the scale.
3662 $return += $DB->count_records_sql("SELECT COUNT('x')
3663 FROM {grade_outcomes_courses} goc,
3664 {grade_outcomes} go
3665 WHERE go.id = goc.outcomeid
3666 AND go.scaleid = ? AND goc.courseid = ?",
3667 array($scaleid, $courseid));
3669 return $return;
3673 * This function returns the number of activities using scaleid in the entire site
3675 * @deprecated since Moodle 3.1
3676 * @param int $scaleid
3677 * @param array $courses
3678 * @return int
3680 function site_scale_used($scaleid, &$courses) {
3681 $return = 0;
3683 debugging('site_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
3684 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
3686 if (!is_array($courses) || count($courses) == 0) {
3687 $courses = get_courses("all", false, "c.id, c.shortname");
3690 if (!empty($scaleid)) {
3691 if (is_array($courses) && count($courses) > 0) {
3692 foreach ($courses as $course) {
3693 $return += course_scale_used($course->id, $scaleid);
3697 return $return;
3701 * @deprecated since Moodle 3.1. Use external_api::external_function_info().
3703 function external_function_info($function, $strictness=MUST_EXIST) {
3704 throw new coding_exception('external_function_info() can not be used any'.
3705 'more. Please use external_api::external_function_info() instead.');
3709 * Retrieves an array of records from a CSV file and places
3710 * them into a given table structure
3711 * This function is deprecated. Please use csv_import_reader() instead.
3713 * @deprecated since Moodle 3.2 MDL-55126
3714 * @todo MDL-55195 for final deprecation in Moodle 3.6
3715 * @see csv_import_reader::load_csv_content()
3716 * @global stdClass $CFG
3717 * @global moodle_database $DB
3718 * @param string $file The path to a CSV file
3719 * @param string $table The table to retrieve columns from
3720 * @return bool|array Returns an array of CSV records or false
3722 function get_records_csv($file, $table) {
3723 global $CFG, $DB;
3725 debugging('get_records_csv() is deprecated. Please use lib/csvlib.class.php csv_import_reader() instead.');
3727 if (!$metacolumns = $DB->get_columns($table)) {
3728 return false;
3731 if(!($handle = @fopen($file, 'r'))) {
3732 print_error('get_records_csv failed to open '.$file);
3735 $fieldnames = fgetcsv($handle, 4096);
3736 if(empty($fieldnames)) {
3737 fclose($handle);
3738 return false;
3741 $columns = array();
3743 foreach($metacolumns as $metacolumn) {
3744 $ord = array_search($metacolumn->name, $fieldnames);
3745 if(is_int($ord)) {
3746 $columns[$metacolumn->name] = $ord;
3750 $rows = array();
3752 while (($data = fgetcsv($handle, 4096)) !== false) {
3753 $item = new stdClass;
3754 foreach($columns as $name => $ord) {
3755 $item->$name = $data[$ord];
3757 $rows[] = $item;
3760 fclose($handle);
3761 return $rows;
3765 * Create a file with CSV contents
3766 * This function is deprecated. Please use download_as_dataformat() instead.
3768 * @deprecated since Moodle 3.2 MDL-55126
3769 * @todo MDL-55195 for final deprecation in Moodle 3.6
3770 * @see download_as_dataformat (lib/dataformatlib.php)
3771 * @global stdClass $CFG
3772 * @global moodle_database $DB
3773 * @param string $file The file to put the CSV content into
3774 * @param array $records An array of records to write to a CSV file
3775 * @param string $table The table to get columns from
3776 * @return bool success
3778 function put_records_csv($file, $records, $table = NULL) {
3779 global $CFG, $DB;
3781 debugging('put_records_csv() is deprecated. Please use lib/dataformatlib.php download_as_dataformat()');
3783 if (empty($records)) {
3784 return true;
3787 $metacolumns = NULL;
3788 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
3789 return false;
3792 echo "x";
3794 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
3795 print_error('put_records_csv failed to open '.$file);
3798 $proto = reset($records);
3799 if(is_object($proto)) {
3800 $fields_records = array_keys(get_object_vars($proto));
3802 else if(is_array($proto)) {
3803 $fields_records = array_keys($proto);
3805 else {
3806 return false;
3808 echo "x";
3810 if(!empty($metacolumns)) {
3811 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
3812 $fields = array_intersect($fields_records, $fields_table);
3814 else {
3815 $fields = $fields_records;
3818 fwrite($fp, implode(',', $fields));
3819 fwrite($fp, "\r\n");
3821 foreach($records as $record) {
3822 $array = (array)$record;
3823 $values = array();
3824 foreach($fields as $field) {
3825 if(strpos($array[$field], ',')) {
3826 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
3828 else {
3829 $values[] = $array[$field];
3832 fwrite($fp, implode(',', $values)."\r\n");
3835 fclose($fp);
3836 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
3837 return true;
3841 * Determines if the given value is a valid CSS colour.
3843 * A CSS colour can be one of the following:
3844 * - Hex colour: #AA66BB
3845 * - RGB colour: rgb(0-255, 0-255, 0-255)
3846 * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
3847 * - HSL colour: hsl(0-360, 0-100%, 0-100%)
3848 * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
3850 * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
3852 * @deprecated since Moodle 3.2
3853 * @todo MDL-56173 for final deprecation in Moodle 3.6
3854 * @param string $value The colour value to check
3855 * @return bool
3857 function css_is_colour($value) {
3858 debugging('css_is_colour() is deprecated without a replacement. Please copy the implementation '.
3859 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
3861 $value = trim($value);
3863 $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
3864 $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
3865 $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
3866 $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
3867 $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
3869 if (in_array(strtolower($value), array('inherit'))) {
3870 return true;
3871 } else if (preg_match($hex, $value)) {
3872 return true;
3873 } else if (in_array(strtolower($value), array_keys(css_optimiser::$htmlcolours))) {
3874 return true;
3875 } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
3876 // It is an RGB colour.
3877 return true;
3878 } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
3879 // It is an RGBA colour.
3880 return true;
3881 } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
3882 // It is an HSL colour.
3883 return true;
3884 } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
3885 // It is an HSLA colour.
3886 return true;
3888 // Doesn't look like a colour.
3889 return false;
3893 * Returns true is the passed value looks like a CSS width.
3894 * In order to pass this test the value must be purely numerical or end with a
3895 * valid CSS unit term.
3897 * @param string|int $value
3898 * @return boolean
3899 * @deprecated since Moodle 3.2
3900 * @todo MDL-56173 for final deprecation in Moodle 3.6
3902 function css_is_width($value) {
3903 debugging('css_is_width() is deprecated without a replacement. Please copy the implementation '.
3904 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
3906 $value = trim($value);
3907 if (in_array(strtolower($value), array('auto', 'inherit'))) {
3908 return true;
3910 if ((string)$value === '0' || preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
3911 return true;
3913 return false;
3917 * A simple sorting function to sort two array values on the number of items they contain
3919 * @param array $a
3920 * @param array $b
3921 * @return int
3922 * @deprecated since Moodle 3.2
3923 * @todo MDL-56173 for final deprecation in Moodle 3.6
3925 function css_sort_by_count(array $a, array $b) {
3926 debugging('css_sort_by_count() is deprecated without a replacement. Please copy the implementation '.
3927 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
3929 $a = count($a);
3930 $b = count($b);
3931 if ($a == $b) {
3932 return 0;
3934 return ($a > $b) ? -1 : 1;
3938 * A basic CSS optimiser that strips out unwanted things and then processes CSS organising and cleaning styles.
3939 * @deprecated since Moodle 3.2
3940 * @todo MDL-56173 for final deprecation in Moodle 3.6
3942 class css_optimiser {
3944 * An array of the common HTML colours that are supported by most browsers.
3946 * This reference table is used to allow us to unify colours, and will aid
3947 * us in identifying buggy CSS using unsupported colours.
3949 * @var string[]
3950 * @deprecated since Moodle 3.2
3951 * @todo MDL-56173 for final deprecation in Moodle 3.6
3953 public static $htmlcolours = array(
3954 'aliceblue' => '#F0F8FF',
3955 'antiquewhite' => '#FAEBD7',
3956 'aqua' => '#00FFFF',
3957 'aquamarine' => '#7FFFD4',
3958 'azure' => '#F0FFFF',
3959 'beige' => '#F5F5DC',
3960 'bisque' => '#FFE4C4',
3961 'black' => '#000000',
3962 'blanchedalmond' => '#FFEBCD',
3963 'blue' => '#0000FF',
3964 'blueviolet' => '#8A2BE2',
3965 'brown' => '#A52A2A',
3966 'burlywood' => '#DEB887',
3967 'cadetblue' => '#5F9EA0',
3968 'chartreuse' => '#7FFF00',
3969 'chocolate' => '#D2691E',
3970 'coral' => '#FF7F50',
3971 'cornflowerblue' => '#6495ED',
3972 'cornsilk' => '#FFF8DC',
3973 'crimson' => '#DC143C',
3974 'cyan' => '#00FFFF',
3975 'darkblue' => '#00008B',
3976 'darkcyan' => '#008B8B',
3977 'darkgoldenrod' => '#B8860B',
3978 'darkgray' => '#A9A9A9',
3979 'darkgrey' => '#A9A9A9',
3980 'darkgreen' => '#006400',
3981 'darkKhaki' => '#BDB76B',
3982 'darkmagenta' => '#8B008B',
3983 'darkolivegreen' => '#556B2F',
3984 'arkorange' => '#FF8C00',
3985 'darkorchid' => '#9932CC',
3986 'darkred' => '#8B0000',
3987 'darksalmon' => '#E9967A',
3988 'darkseagreen' => '#8FBC8F',
3989 'darkslateblue' => '#483D8B',
3990 'darkslategray' => '#2F4F4F',
3991 'darkslategrey' => '#2F4F4F',
3992 'darkturquoise' => '#00CED1',
3993 'darkviolet' => '#9400D3',
3994 'deeppink' => '#FF1493',
3995 'deepskyblue' => '#00BFFF',
3996 'dimgray' => '#696969',
3997 'dimgrey' => '#696969',
3998 'dodgerblue' => '#1E90FF',
3999 'firebrick' => '#B22222',
4000 'floralwhite' => '#FFFAF0',
4001 'forestgreen' => '#228B22',
4002 'fuchsia' => '#FF00FF',
4003 'gainsboro' => '#DCDCDC',
4004 'ghostwhite' => '#F8F8FF',
4005 'gold' => '#FFD700',
4006 'goldenrod' => '#DAA520',
4007 'gray' => '#808080',
4008 'grey' => '#808080',
4009 'green' => '#008000',
4010 'greenyellow' => '#ADFF2F',
4011 'honeydew' => '#F0FFF0',
4012 'hotpink' => '#FF69B4',
4013 'indianred ' => '#CD5C5C',
4014 'indigo ' => '#4B0082',
4015 'ivory' => '#FFFFF0',
4016 'khaki' => '#F0E68C',
4017 'lavender' => '#E6E6FA',
4018 'lavenderblush' => '#FFF0F5',
4019 'lawngreen' => '#7CFC00',
4020 'lemonchiffon' => '#FFFACD',
4021 'lightblue' => '#ADD8E6',
4022 'lightcoral' => '#F08080',
4023 'lightcyan' => '#E0FFFF',
4024 'lightgoldenrodyellow' => '#FAFAD2',
4025 'lightgray' => '#D3D3D3',
4026 'lightgrey' => '#D3D3D3',
4027 'lightgreen' => '#90EE90',
4028 'lightpink' => '#FFB6C1',
4029 'lightsalmon' => '#FFA07A',
4030 'lightseagreen' => '#20B2AA',
4031 'lightskyblue' => '#87CEFA',
4032 'lightslategray' => '#778899',
4033 'lightslategrey' => '#778899',
4034 'lightsteelblue' => '#B0C4DE',
4035 'lightyellow' => '#FFFFE0',
4036 'lime' => '#00FF00',
4037 'limegreen' => '#32CD32',
4038 'linen' => '#FAF0E6',
4039 'magenta' => '#FF00FF',
4040 'maroon' => '#800000',
4041 'mediumaquamarine' => '#66CDAA',
4042 'mediumblue' => '#0000CD',
4043 'mediumorchid' => '#BA55D3',
4044 'mediumpurple' => '#9370D8',
4045 'mediumseagreen' => '#3CB371',
4046 'mediumslateblue' => '#7B68EE',
4047 'mediumspringgreen' => '#00FA9A',
4048 'mediumturquoise' => '#48D1CC',
4049 'mediumvioletred' => '#C71585',
4050 'midnightblue' => '#191970',
4051 'mintcream' => '#F5FFFA',
4052 'mistyrose' => '#FFE4E1',
4053 'moccasin' => '#FFE4B5',
4054 'navajowhite' => '#FFDEAD',
4055 'navy' => '#000080',
4056 'oldlace' => '#FDF5E6',
4057 'olive' => '#808000',
4058 'olivedrab' => '#6B8E23',
4059 'orange' => '#FFA500',
4060 'orangered' => '#FF4500',
4061 'orchid' => '#DA70D6',
4062 'palegoldenrod' => '#EEE8AA',
4063 'palegreen' => '#98FB98',
4064 'paleturquoise' => '#AFEEEE',
4065 'palevioletred' => '#D87093',
4066 'papayawhip' => '#FFEFD5',
4067 'peachpuff' => '#FFDAB9',
4068 'peru' => '#CD853F',
4069 'pink' => '#FFC0CB',
4070 'plum' => '#DDA0DD',
4071 'powderblue' => '#B0E0E6',
4072 'purple' => '#800080',
4073 'red' => '#FF0000',
4074 'rosybrown' => '#BC8F8F',
4075 'royalblue' => '#4169E1',
4076 'saddlebrown' => '#8B4513',
4077 'salmon' => '#FA8072',
4078 'sandybrown' => '#F4A460',
4079 'seagreen' => '#2E8B57',
4080 'seashell' => '#FFF5EE',
4081 'sienna' => '#A0522D',
4082 'silver' => '#C0C0C0',
4083 'skyblue' => '#87CEEB',
4084 'slateblue' => '#6A5ACD',
4085 'slategray' => '#708090',
4086 'slategrey' => '#708090',
4087 'snow' => '#FFFAFA',
4088 'springgreen' => '#00FF7F',
4089 'steelblue' => '#4682B4',
4090 'tan' => '#D2B48C',
4091 'teal' => '#008080',
4092 'thistle' => '#D8BFD8',
4093 'tomato' => '#FF6347',
4094 'transparent' => 'transparent',
4095 'turquoise' => '#40E0D0',
4096 'violet' => '#EE82EE',
4097 'wheat' => '#F5DEB3',
4098 'white' => '#FFFFFF',
4099 'whitesmoke' => '#F5F5F5',
4100 'yellow' => '#FFFF00',
4101 'yellowgreen' => '#9ACD32'
4105 * Used to orocesses incoming CSS optimising it and then returning it. Now just returns
4106 * what is sent to it. Do not use.
4108 * @param string $css The raw CSS to optimise
4109 * @return string The optimised CSS
4110 * @deprecated since Moodle 3.2
4111 * @todo MDL-56173 for final deprecation in Moodle 3.6
4113 public function process($css) {
4114 debugging('class css_optimiser is deprecated and no longer does anything, '.
4115 'please consider using stylelint to optimise your css.', DEBUG_DEVELOPER);
4117 return $css;
4122 * Load the course contexts for all of the users courses
4124 * @deprecated since Moodle 3.2
4125 * @param array $courses array of course objects. The courses the user is enrolled in.
4126 * @return array of course contexts
4128 function message_get_course_contexts($courses) {
4129 debugging('message_get_course_contexts() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4131 $coursecontexts = array();
4133 foreach($courses as $course) {
4134 $coursecontexts[$course->id] = context_course::instance($course->id);
4137 return $coursecontexts;
4141 * strip off action parameters like 'removecontact'
4143 * @deprecated since Moodle 3.2
4144 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
4145 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
4147 function message_remove_url_params($moodleurl) {
4148 debugging('message_remove_url_params() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4150 $newurl = new moodle_url($moodleurl);
4151 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
4152 return $newurl->out();
4156 * Count the number of messages with a field having a specified value.
4157 * if $field is empty then return count of the whole array
4158 * if $field is non-existent then return 0
4160 * @deprecated since Moodle 3.2
4161 * @param array $messagearray array of message objects
4162 * @param string $field the field to inspect on the message objects
4163 * @param string $value the value to test the field against
4165 function message_count_messages($messagearray, $field='', $value='') {
4166 debugging('message_count_messages() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4168 if (!is_array($messagearray)) return 0;
4169 if ($field == '' or empty($messagearray)) return count($messagearray);
4171 $count = 0;
4172 foreach ($messagearray as $message) {
4173 $count += ($message->$field == $value) ? 1 : 0;
4175 return $count;
4179 * Count the number of users blocked by $user1
4181 * @deprecated since Moodle 3.2
4182 * @param object $user1 user object
4183 * @return int the number of blocked users
4185 function message_count_blocked_users($user1=null) {
4186 debugging('message_count_blocked_users() is deprecated, please use \core_message\api::count_blocked_users() instead.',
4187 DEBUG_DEVELOPER);
4189 return \core_message\api::count_blocked_users($user1);
4193 * Print a message contact link
4195 * @deprecated since Moodle 3.2
4196 * @param int $userid the ID of the user to apply to action to
4197 * @param string $linktype can be add, remove, block or unblock
4198 * @param bool $return if true return the link as a string. If false echo the link.
4199 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4200 * @param bool $text include text next to the icons?
4201 * @param bool $icon include a graphical icon?
4202 * @return string if $return is true otherwise bool
4204 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
4205 debugging('message_contact_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4207 global $OUTPUT, $PAGE;
4209 //hold onto the strings as we're probably creating a bunch of links
4210 static $str;
4212 if (empty($script)) {
4213 //strip off previous action params like 'removecontact'
4214 $script = message_remove_url_params($PAGE->url);
4217 if (empty($str->blockcontact)) {
4218 $str = new stdClass();
4219 $str->blockcontact = get_string('blockcontact', 'message');
4220 $str->unblockcontact = get_string('unblockcontact', 'message');
4221 $str->removecontact = get_string('removecontact', 'message');
4222 $str->addcontact = get_string('addcontact', 'message');
4225 $command = $linktype.'contact';
4226 $string = $str->{$command};
4228 $safealttext = s($string);
4230 $safestring = '';
4231 if (!empty($text)) {
4232 $safestring = $safealttext;
4235 $img = '';
4236 if ($icon) {
4237 $iconpath = null;
4238 switch ($linktype) {
4239 case 'block':
4240 $iconpath = 't/block';
4241 break;
4242 case 'unblock':
4243 $iconpath = 't/unblock';
4244 break;
4245 case 'remove':
4246 $iconpath = 't/removecontact';
4247 break;
4248 case 'add':
4249 default:
4250 $iconpath = 't/addcontact';
4253 $img = $OUTPUT->pix_icon($iconpath, $safealttext);
4256 $output = '<span class="'.$linktype.'contact">'.
4257 '<a href="'.$script.'&amp;'.$command.'='.$userid.
4258 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
4259 $img.
4260 $safestring.'</a></span>';
4262 if ($return) {
4263 return $output;
4264 } else {
4265 echo $output;
4266 return true;
4271 * @deprecated since Moodle 3.2
4273 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
4274 throw new coding_exception('message_get_recent_notifications() can not be used any more.', DEBUG_DEVELOPER);
4278 * echo or return a link to take the user to the full message history between themselves and another user
4280 * @deprecated since Moodle 3.2
4281 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
4282 * @param int $userid2 the ID of the other user
4283 * @param bool $return true to return the link as a string. False to echo the link.
4284 * @param string $keywords any keywords to highlight in the message history
4285 * @param string $position anchor name to jump to within the message history
4286 * @param string $linktext optionally specify the link text
4287 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
4289 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
4290 debugging('message_history_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4292 global $OUTPUT, $PAGE;
4293 static $strmessagehistory;
4295 if (empty($strmessagehistory)) {
4296 $strmessagehistory = get_string('messagehistory', 'message');
4299 if ($position) {
4300 $position = "#$position";
4302 if ($keywords) {
4303 $keywords = "&search=".urlencode($keywords);
4306 if ($linktext == 'icon') { // Icon only
4307 $fulllink = $OUTPUT->pix_icon('t/messages', $strmessagehistory);
4308 } else if ($linktext == 'both') { // Icon and standard name
4309 $fulllink = $OUTPUT->pix_icon('t/messages', '');
4310 $fulllink .= '&nbsp;'.$strmessagehistory;
4311 } else if ($linktext) { // Custom name
4312 $fulllink = $linktext;
4313 } else { // Standard name only
4314 $fulllink = $strmessagehistory;
4317 $popupoptions = array(
4318 'height' => 500,
4319 'width' => 500,
4320 'menubar' => false,
4321 'location' => false,
4322 'status' => true,
4323 'scrollbars' => true,
4324 'resizable' => true);
4326 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
4327 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
4328 $link->param('viewing', $PAGE->url->get_param('viewing'));
4330 $action = null;
4331 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
4333 $str = '<span class="history">'.$str.'</span>';
4335 if ($return) {
4336 return $str;
4337 } else {
4338 echo $str;
4339 return true;
4344 * @deprecated since Moodle 3.2
4346 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
4347 throw new coding_exception('message_search() can not be used any more.', DEBUG_DEVELOPER);
4351 * Given a message object that we already know has a long message
4352 * this function truncates the message nicely to the first
4353 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
4355 * @deprecated since Moodle 3.2
4356 * @param string $message the message
4357 * @param int $minlength the minimum length to trim the message to
4358 * @return string the shortened message
4360 function message_shorten_message($message, $minlength = 0) {
4361 debugging('message_shorten_message() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4363 $i = 0;
4364 $tag = false;
4365 $length = strlen($message);
4366 $count = 0;
4367 $stopzone = false;
4368 $truncate = 0;
4369 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
4372 for ($i=0; $i<$length; $i++) {
4373 $char = $message[$i];
4375 switch ($char) {
4376 case "<":
4377 $tag = true;
4378 break;
4379 case ">":
4380 $tag = false;
4381 break;
4382 default:
4383 if (!$tag) {
4384 if ($stopzone) {
4385 if ($char == '.' or $char == ' ') {
4386 $truncate = $i+1;
4387 break 2;
4390 $count++;
4392 break;
4394 if (!$stopzone) {
4395 if ($count > $minlength) {
4396 $stopzone = true;
4401 if (!$truncate) {
4402 $truncate = $i;
4405 return substr($message, 0, $truncate);
4409 * Given a string and an array of keywords, this function looks
4410 * for the first keyword in the string, and then chops out a
4411 * small section from the text that shows that word in context.
4413 * @deprecated since Moodle 3.2
4414 * @param string $message the text to search
4415 * @param array $keywords array of keywords to find
4417 function message_get_fragment($message, $keywords) {
4418 debugging('message_get_fragment() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4420 $fullsize = 160;
4421 $halfsize = (int)($fullsize/2);
4423 $message = strip_tags($message);
4425 foreach ($keywords as $keyword) { // Just get the first one
4426 if ($keyword !== '') {
4427 break;
4430 if (empty($keyword)) { // None found, so just return start of message
4431 return message_shorten_message($message, 30);
4434 $leadin = $leadout = '';
4436 /// Find the start of the fragment
4437 $start = 0;
4438 $length = strlen($message);
4440 $pos = strpos($message, $keyword);
4441 if ($pos > $halfsize) {
4442 $start = $pos - $halfsize;
4443 $leadin = '...';
4445 /// Find the end of the fragment
4446 $end = $start + $fullsize;
4447 if ($end > $length) {
4448 $end = $length;
4449 } else {
4450 $leadout = '...';
4453 /// Pull out the fragment and format it
4455 $fragment = substr($message, $start, $end - $start);
4456 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
4457 return $fragment;
4461 * @deprecated since Moodle 3.2
4463 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
4464 throw new coding_exception('message_get_history() can not be used any more.', DEBUG_DEVELOPER);
4468 * Constructs the add/remove contact link to display next to other users
4470 * @deprecated since Moodle 3.2
4471 * @param bool $incontactlist is the user a contact
4472 * @param bool $isblocked is the user blocked
4473 * @param stdClass $contact contact object
4474 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4475 * @param bool $text include text next to the icons?
4476 * @param bool $icon include a graphical icon?
4477 * @return string
4479 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
4480 debugging('message_get_contact_add_remove_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4482 $strcontact = '';
4484 if($incontactlist){
4485 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
4486 } else if ($isblocked) {
4487 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
4488 } else{
4489 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
4492 return $strcontact;
4496 * Constructs the block contact link to display next to other users
4498 * @deprecated since Moodle 3.2
4499 * @param bool $incontactlist is the user a contact?
4500 * @param bool $isblocked is the user blocked?
4501 * @param stdClass $contact contact object
4502 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4503 * @param bool $text include text next to the icons?
4504 * @param bool $icon include a graphical icon?
4505 * @return string
4507 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
4508 debugging('message_get_contact_block_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4510 $strblock = '';
4512 //commented out to allow the user to block a contact without having to remove them first
4513 /*if ($incontactlist) {
4514 //$strblock = '';
4515 } else*/
4516 if ($isblocked) {
4517 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
4518 } else{
4519 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
4522 return $strblock;
4526 * marks ALL messages being sent from $fromuserid to $touserid as read
4528 * @deprecated since Moodle 3.2
4529 * @param int $touserid the id of the message recipient
4530 * @param int $fromuserid the id of the message sender
4531 * @return void
4533 function message_mark_messages_read($touserid, $fromuserid) {
4534 debugging('message_mark_messages_read() is deprecated and is no longer used, please use
4535 \core_message\api::mark_all_messages_as_read() instead.', DEBUG_DEVELOPER);
4537 \core_message\api::mark_all_messages_as_read($touserid, $fromuserid);
4541 * Return a list of page types
4543 * @deprecated since Moodle 3.2
4544 * @param string $pagetype current page type
4545 * @param stdClass $parentcontext Block's parent context
4546 * @param stdClass $currentcontext Current context of block
4548 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
4549 debugging('message_page_type_list() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4551 return array('messages-*'=>get_string('page-message-x', 'message'));
4555 * Determines if a user is permitted to send another user a private message.
4556 * If no sender is provided then it defaults to the logged in user.
4558 * @deprecated since Moodle 3.2
4559 * @param object $recipient User object.
4560 * @param object $sender User object.
4561 * @return bool true if user is permitted, false otherwise.
4563 function message_can_post_message($recipient, $sender = null) {
4564 debugging('message_can_post_message() is deprecated and is no longer used, please use
4565 \core_message\api::can_post_message() instead.', DEBUG_DEVELOPER);
4567 return \core_message\api::can_post_message($recipient, $sender);
4571 * Checks if the recipient is allowing messages from users that aren't a
4572 * contact. If not then it checks to make sure the sender is in the
4573 * recipient's contacts.
4575 * @deprecated since Moodle 3.2
4576 * @param object $recipient User object.
4577 * @param object $sender User object.
4578 * @return bool true if $sender is blocked, false otherwise.
4580 function message_is_user_non_contact_blocked($recipient, $sender = null) {
4581 debugging('message_is_user_non_contact_blocked() is deprecated and is no longer used, please use
4582 \core_message\api::is_user_non_contact_blocked() instead.', DEBUG_DEVELOPER);
4584 return \core_message\api::is_user_non_contact_blocked($recipient, $sender);
4588 * Checks if the recipient has specifically blocked the sending user.
4590 * Note: This function will always return false if the sender has the
4591 * readallmessages capability at the system context level.
4593 * @deprecated since Moodle 3.2
4594 * @param object $recipient User object.
4595 * @param object $sender User object.
4596 * @return bool true if $sender is blocked, false otherwise.
4598 function message_is_user_blocked($recipient, $sender = null) {
4599 debugging('message_is_user_blocked() is deprecated and is no longer used, please use
4600 \core_message\api::is_user_blocked() instead.', DEBUG_DEVELOPER);
4602 $senderid = null;
4603 if ($sender !== null && isset($sender->id)) {
4604 $senderid = $sender->id;
4606 return \core_message\api::is_user_blocked($recipient->id, $senderid);
4610 * Display logs.
4612 * @deprecated since 3.2
4614 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
4615 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
4616 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
4618 global $CFG, $DB, $OUTPUT;
4620 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
4621 $modname, $modid, $modaction, $groupid)) {
4622 echo $OUTPUT->notification("No logs found!");
4623 echo $OUTPUT->footer();
4624 exit;
4627 $courses = array();
4629 if ($course->id == SITEID) {
4630 $courses[0] = '';
4631 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
4632 foreach ($ccc as $cc) {
4633 $courses[$cc->id] = $cc->shortname;
4636 } else {
4637 $courses[$course->id] = $course->shortname;
4640 $totalcount = $logs['totalcount'];
4641 $ldcache = array();
4643 $strftimedatetime = get_string("strftimedatetime");
4645 echo "<div class=\"info\">\n";
4646 print_string("displayingrecords", "", $totalcount);
4647 echo "</div>\n";
4649 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
4651 $table = new html_table();
4652 $table->classes = array('logtable','generaltable');
4653 $table->align = array('right', 'left', 'left');
4654 $table->head = array(
4655 get_string('time'),
4656 get_string('ip_address'),
4657 get_string('fullnameuser'),
4658 get_string('action'),
4659 get_string('info')
4661 $table->data = array();
4663 if ($course->id == SITEID) {
4664 array_unshift($table->align, 'left');
4665 array_unshift($table->head, get_string('course'));
4668 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
4669 if (empty($logs['logs'])) {
4670 $logs['logs'] = array();
4673 foreach ($logs['logs'] as $log) {
4675 if (isset($ldcache[$log->module][$log->action])) {
4676 $ld = $ldcache[$log->module][$log->action];
4677 } else {
4678 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
4679 $ldcache[$log->module][$log->action] = $ld;
4681 if ($ld && is_numeric($log->info)) {
4682 // ugly hack to make sure fullname is shown correctly
4683 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
4684 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
4685 } else {
4686 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
4690 //Filter log->info
4691 $log->info = format_string($log->info);
4693 // If $log->url has been trimmed short by the db size restriction
4694 // code in add_to_log, keep a note so we don't add a link to a broken url
4695 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
4697 $row = array();
4698 if ($course->id == SITEID) {
4699 if (empty($log->course)) {
4700 $row[] = get_string('site');
4701 } else {
4702 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
4706 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
4708 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
4709 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
4711 $row[] = html_writer::link(new moodle_url("/user/view.php?id={$log->userid}&course={$log->course}"), fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))));
4713 $displayaction="$log->module $log->action";
4714 if ($brokenurl) {
4715 $row[] = $displayaction;
4716 } else {
4717 $link = make_log_url($log->module,$log->url);
4718 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
4720 $row[] = $log->info;
4721 $table->data[] = $row;
4724 echo html_writer::table($table);
4725 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
4729 * Display MNET logs.
4731 * @deprecated since 3.2
4733 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
4734 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
4735 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
4737 global $CFG, $DB, $OUTPUT;
4739 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
4740 $modname, $modid, $modaction, $groupid)) {
4741 echo $OUTPUT->notification("No logs found!");
4742 echo $OUTPUT->footer();
4743 exit;
4746 if ($course->id == SITEID) {
4747 $courses[0] = '';
4748 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
4749 foreach ($ccc as $cc) {
4750 $courses[$cc->id] = $cc->shortname;
4755 $totalcount = $logs['totalcount'];
4756 $ldcache = array();
4758 $strftimedatetime = get_string("strftimedatetime");
4760 echo "<div class=\"info\">\n";
4761 print_string("displayingrecords", "", $totalcount);
4762 echo "</div>\n";
4764 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
4766 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
4767 echo "<tr>";
4768 if ($course->id == SITEID) {
4769 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
4771 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
4772 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
4773 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
4774 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
4775 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
4776 echo "</tr>\n";
4778 if (empty($logs['logs'])) {
4779 echo "</table>\n";
4780 return;
4783 $row = 1;
4784 foreach ($logs['logs'] as $log) {
4786 $log->info = $log->coursename;
4787 $row = ($row + 1) % 2;
4789 if (isset($ldcache[$log->module][$log->action])) {
4790 $ld = $ldcache[$log->module][$log->action];
4791 } else {
4792 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
4793 $ldcache[$log->module][$log->action] = $ld;
4795 if (0 && $ld && !empty($log->info)) {
4796 // ugly hack to make sure fullname is shown correctly
4797 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
4798 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
4799 } else {
4800 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
4804 //Filter log->info
4805 $log->info = format_string($log->info);
4807 echo '<tr class="r'.$row.'">';
4808 if ($course->id == SITEID) {
4809 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
4810 echo "<td class=\"r$row c0\" >\n";
4811 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
4812 echo "</td>\n";
4814 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
4815 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
4816 echo "<td class=\"r$row c2\" >\n";
4817 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
4818 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
4819 echo "</td>\n";
4820 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
4821 echo "<td class=\"r$row c3\" >\n";
4822 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
4823 echo "</td>\n";
4824 echo "<td class=\"r$row c4\">\n";
4825 echo $log->action .': '.$log->module;
4826 echo "</td>\n";
4827 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
4828 echo "</tr>\n";
4830 echo "</table>\n";
4832 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
4836 * Display logs in CSV format.
4838 * @deprecated since 3.2
4840 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
4841 $modid, $modaction, $groupid) {
4842 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
4844 global $DB, $CFG;
4846 require_once($CFG->libdir . '/csvlib.class.php');
4848 $csvexporter = new csv_export_writer('tab');
4850 $header = array();
4851 $header[] = get_string('course');
4852 $header[] = get_string('time');
4853 $header[] = get_string('ip_address');
4854 $header[] = get_string('fullnameuser');
4855 $header[] = get_string('action');
4856 $header[] = get_string('info');
4858 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
4859 $modname, $modid, $modaction, $groupid)) {
4860 return false;
4863 $courses = array();
4865 if ($course->id == SITEID) {
4866 $courses[0] = '';
4867 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
4868 foreach ($ccc as $cc) {
4869 $courses[$cc->id] = $cc->shortname;
4872 } else {
4873 $courses[$course->id] = $course->shortname;
4876 $count=0;
4877 $ldcache = array();
4878 $tt = getdate(time());
4879 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
4881 $strftimedatetime = get_string("strftimedatetime");
4883 $csvexporter->set_filename('logs', '.txt');
4884 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
4885 $csvexporter->add_data($title);
4886 $csvexporter->add_data($header);
4888 if (empty($logs['logs'])) {
4889 return true;
4892 foreach ($logs['logs'] as $log) {
4893 if (isset($ldcache[$log->module][$log->action])) {
4894 $ld = $ldcache[$log->module][$log->action];
4895 } else {
4896 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
4897 $ldcache[$log->module][$log->action] = $ld;
4899 if ($ld && is_numeric($log->info)) {
4900 // ugly hack to make sure fullname is shown correctly
4901 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
4902 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
4903 } else {
4904 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
4908 //Filter log->info
4909 $log->info = format_string($log->info);
4910 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
4912 $coursecontext = context_course::instance($course->id);
4913 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
4914 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
4915 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
4916 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
4917 $csvexporter->add_data($row);
4919 $csvexporter->download_file();
4920 return true;
4924 * Display logs in XLS format.
4926 * @deprecated since 3.2
4928 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
4929 $modid, $modaction, $groupid) {
4930 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
4932 global $CFG, $DB;
4934 require_once("$CFG->libdir/excellib.class.php");
4936 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
4937 $modname, $modid, $modaction, $groupid)) {
4938 return false;
4941 $courses = array();
4943 if ($course->id == SITEID) {
4944 $courses[0] = '';
4945 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
4946 foreach ($ccc as $cc) {
4947 $courses[$cc->id] = $cc->shortname;
4950 } else {
4951 $courses[$course->id] = $course->shortname;
4954 $count=0;
4955 $ldcache = array();
4956 $tt = getdate(time());
4957 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
4959 $strftimedatetime = get_string("strftimedatetime");
4961 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
4962 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
4963 $filename .= '.xls';
4965 $workbook = new MoodleExcelWorkbook('-');
4966 $workbook->send($filename);
4968 $worksheet = array();
4969 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
4970 get_string('fullnameuser'), get_string('action'), get_string('info'));
4972 // Creating worksheets
4973 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
4974 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
4975 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
4976 $worksheet[$wsnumber]->set_column(1, 1, 30);
4977 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
4978 userdate(time(), $strftimedatetime));
4979 $col = 0;
4980 foreach ($headers as $item) {
4981 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
4982 $col++;
4986 if (empty($logs['logs'])) {
4987 $workbook->close();
4988 return true;
4991 $formatDate =& $workbook->add_format();
4992 $formatDate->set_num_format(get_string('log_excel_date_format'));
4994 $row = FIRSTUSEDEXCELROW;
4995 $wsnumber = 1;
4996 $myxls =& $worksheet[$wsnumber];
4997 foreach ($logs['logs'] as $log) {
4998 if (isset($ldcache[$log->module][$log->action])) {
4999 $ld = $ldcache[$log->module][$log->action];
5000 } else {
5001 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5002 $ldcache[$log->module][$log->action] = $ld;
5004 if ($ld && is_numeric($log->info)) {
5005 // ugly hack to make sure fullname is shown correctly
5006 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5007 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5008 } else {
5009 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5013 // Filter log->info
5014 $log->info = format_string($log->info);
5015 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5017 if ($nroPages>1) {
5018 if ($row > EXCELROWS) {
5019 $wsnumber++;
5020 $myxls =& $worksheet[$wsnumber];
5021 $row = FIRSTUSEDEXCELROW;
5025 $coursecontext = context_course::instance($course->id);
5027 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
5028 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
5029 $myxls->write($row, 2, $log->ip, '');
5030 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5031 $myxls->write($row, 3, $fullname, '');
5032 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5033 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
5034 $myxls->write($row, 5, $log->info, '');
5036 $row++;
5039 $workbook->close();
5040 return true;
5044 * Display logs in ODS format.
5046 * @deprecated since 3.2
5048 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
5049 $modid, $modaction, $groupid) {
5050 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5052 global $CFG, $DB;
5054 require_once("$CFG->libdir/odslib.class.php");
5056 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5057 $modname, $modid, $modaction, $groupid)) {
5058 return false;
5061 $courses = array();
5063 if ($course->id == SITEID) {
5064 $courses[0] = '';
5065 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5066 foreach ($ccc as $cc) {
5067 $courses[$cc->id] = $cc->shortname;
5070 } else {
5071 $courses[$course->id] = $course->shortname;
5074 $ldcache = array();
5076 $strftimedatetime = get_string("strftimedatetime");
5078 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
5079 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5080 $filename .= '.ods';
5082 $workbook = new MoodleODSWorkbook('-');
5083 $workbook->send($filename);
5085 $worksheet = array();
5086 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5087 get_string('fullnameuser'), get_string('action'), get_string('info'));
5089 // Creating worksheets
5090 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
5091 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5092 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5093 $worksheet[$wsnumber]->set_column(1, 1, 30);
5094 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5095 userdate(time(), $strftimedatetime));
5096 $col = 0;
5097 foreach ($headers as $item) {
5098 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
5099 $col++;
5103 if (empty($logs['logs'])) {
5104 $workbook->close();
5105 return true;
5108 $formatDate =& $workbook->add_format();
5109 $formatDate->set_num_format(get_string('log_excel_date_format'));
5111 $row = FIRSTUSEDEXCELROW;
5112 $wsnumber = 1;
5113 $myxls =& $worksheet[$wsnumber];
5114 foreach ($logs['logs'] as $log) {
5115 if (isset($ldcache[$log->module][$log->action])) {
5116 $ld = $ldcache[$log->module][$log->action];
5117 } else {
5118 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5119 $ldcache[$log->module][$log->action] = $ld;
5121 if ($ld && is_numeric($log->info)) {
5122 // ugly hack to make sure fullname is shown correctly
5123 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5124 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5125 } else {
5126 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5130 // Filter log->info
5131 $log->info = format_string($log->info);
5132 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5134 if ($nroPages>1) {
5135 if ($row > EXCELROWS) {
5136 $wsnumber++;
5137 $myxls =& $worksheet[$wsnumber];
5138 $row = FIRSTUSEDEXCELROW;
5142 $coursecontext = context_course::instance($course->id);
5144 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
5145 $myxls->write_date($row, 1, $log->time);
5146 $myxls->write_string($row, 2, $log->ip);
5147 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5148 $myxls->write_string($row, 3, $fullname);
5149 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5150 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
5151 $myxls->write_string($row, 5, $log->info);
5153 $row++;
5156 $workbook->close();
5157 return true;
5161 * Build an array of logs.
5163 * @deprecated since 3.2
5165 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
5166 $modname="", $modid=0, $modaction="", $groupid=0) {
5167 global $DB, $SESSION, $USER;
5169 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5170 // It is assumed that $date is the GMT time of midnight for that day,
5171 // and so the next 86400 seconds worth of logs are printed.
5173 // Setup for group handling.
5175 // If the group mode is separate, and this user does not have editing privileges,
5176 // then only the user's group can be viewed.
5177 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
5178 if (isset($SESSION->currentgroup[$course->id])) {
5179 $groupid = $SESSION->currentgroup[$course->id];
5180 } else {
5181 $groupid = groups_get_all_groups($course->id, $USER->id);
5182 if (is_array($groupid)) {
5183 $groupid = array_shift(array_keys($groupid));
5184 $SESSION->currentgroup[$course->id] = $groupid;
5185 } else {
5186 $groupid = 0;
5190 // If this course doesn't have groups, no groupid can be specified.
5191 else if (!$course->groupmode) {
5192 $groupid = 0;
5195 $joins = array();
5196 $params = array();
5198 if ($course->id != SITEID || $modid != 0) {
5199 $joins[] = "l.course = :courseid";
5200 $params['courseid'] = $course->id;
5203 if ($modname) {
5204 $joins[] = "l.module = :modname";
5205 $params['modname'] = $modname;
5208 if ('site_errors' === $modid) {
5209 $joins[] = "( l.action='error' OR l.action='infected' )";
5210 } else if ($modid) {
5211 $joins[] = "l.cmid = :modid";
5212 $params['modid'] = $modid;
5215 if ($modaction) {
5216 $firstletter = substr($modaction, 0, 1);
5217 if ($firstletter == '-') {
5218 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
5219 $params['modaction'] = '%'.substr($modaction, 1).'%';
5220 } else {
5221 $joins[] = $DB->sql_like('l.action', ':modaction', false);
5222 $params['modaction'] = '%'.$modaction.'%';
5227 /// Getting all members of a group.
5228 if ($groupid and !$user) {
5229 if ($gusers = groups_get_members($groupid)) {
5230 $gusers = array_keys($gusers);
5231 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
5232 } else {
5233 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
5236 else if ($user) {
5237 $joins[] = "l.userid = :userid";
5238 $params['userid'] = $user;
5241 if ($date) {
5242 $enddate = $date + 86400;
5243 $joins[] = "l.time > :date AND l.time < :enddate";
5244 $params['date'] = $date;
5245 $params['enddate'] = $enddate;
5248 $selector = implode(' AND ', $joins);
5250 $totalcount = 0; // Initialise
5251 $result = array();
5252 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
5253 $result['totalcount'] = $totalcount;
5254 return $result;
5258 * Select all log records for a given course and user.
5260 * @deprecated since 3.2
5261 * @param int $userid The id of the user as found in the 'user' table.
5262 * @param int $courseid The id of the course as found in the 'course' table.
5263 * @param string $coursestart unix timestamp representing course start date and time.
5264 * @return array
5266 function get_logs_usercourse($userid, $courseid, $coursestart) {
5267 global $DB;
5269 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5271 $params = array();
5273 $courseselect = '';
5274 if ($courseid) {
5275 $courseselect = "AND course = :courseid";
5276 $params['courseid'] = $courseid;
5278 $params['userid'] = $userid;
5279 // We have to sanitize this param ourselves here instead of relying on DB.
5280 // Postgres complains if you use name parameter or column alias in GROUP BY.
5281 // See MDL-27696 and 51c3e85 for details.
5282 $coursestart = (int)$coursestart;
5284 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
5285 FROM {log}
5286 WHERE userid = :userid
5287 AND time > $coursestart $courseselect
5288 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
5292 * Select all log records for a given course, user, and day.
5294 * @deprecated since 3.2
5295 * @param int $userid The id of the user as found in the 'user' table.
5296 * @param int $courseid The id of the course as found in the 'course' table.
5297 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
5298 * @return array
5300 function get_logs_userday($userid, $courseid, $daystart) {
5301 global $DB;
5303 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5305 $params = array('userid'=>$userid);
5307 $courseselect = '';
5308 if ($courseid) {
5309 $courseselect = "AND course = :courseid";
5310 $params['courseid'] = $courseid;
5312 // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
5313 $daystart = (int) $daystart;
5315 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
5316 FROM {log}
5317 WHERE userid = :userid
5318 AND time > $daystart $courseselect
5319 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
5323 * Select all log records based on SQL criteria.
5325 * @deprecated since 3.2
5326 * @param string $select SQL select criteria
5327 * @param array $params named sql type params
5328 * @param string $order SQL order by clause to sort the records returned
5329 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
5330 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
5331 * @param int $totalcount Passed in by reference.
5332 * @return array
5334 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
5335 global $DB;
5337 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5339 if ($order) {
5340 $order = "ORDER BY $order";
5343 if ($select) {
5344 $select = "WHERE $select";
5347 $sql = "SELECT COUNT(*)
5348 FROM {log} l
5349 $select";
5351 $totalcount = $DB->count_records_sql($sql, $params);
5352 $allnames = get_all_user_name_fields(true, 'u');
5353 $sql = "SELECT l.*, $allnames, u.picture
5354 FROM {log} l
5355 LEFT JOIN {user} u ON l.userid = u.id
5356 $select
5357 $order";
5359 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5363 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
5365 * @deprecated since Moodle 3.2 MDL-53048
5367 function prevent_form_autofill_password() {
5368 debugging('prevent_form_autofill_password has been deprecated and is no longer in use.', DEBUG_DEVELOPER);
5369 return '';
5373 * @deprecated since Moodle 3.3 MDL-57370
5375 function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
5376 throw new coding_exception('message_get_recent_conversations() can not be used any more. ' .
5377 'Please use \core_message\api::get_conversations() instead.', DEBUG_DEVELOPER);
5381 * Display calendar preference button.
5383 * @param stdClass $course course object
5384 * @deprecated since Moodle 3.2
5385 * @return string return preference button in html
5387 function calendar_preferences_button(stdClass $course) {
5388 debugging('This should no longer be used, the calendar preferences are now linked to the user preferences page.');
5390 global $OUTPUT;
5392 // Guests have no preferences.
5393 if (!isloggedin() || isguestuser()) {
5394 return '';
5397 return $OUTPUT->single_button(new moodle_url('/user/calendar.php'), get_string("preferences", "calendar"));
5401 * Return the name of the weekday
5403 * @deprecated since 3.3
5404 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5405 * @param string $englishname
5406 * @return string of the weekeday
5408 function calendar_wday_name($englishname) {
5409 debugging(__FUNCTION__ . '() is deprecated and no longer used in core.', DEBUG_DEVELOPER);
5410 return get_string(strtolower($englishname), 'calendar');
5414 * Get the upcoming event block.
5416 * @deprecated since 3.3
5417 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5418 * @param array $events list of events
5419 * @param moodle_url|string $linkhref link to event referer
5420 * @param boolean $showcourselink whether links to courses should be shown
5421 * @return string|null $content html block content
5423 function calendar_get_block_upcoming($events, $linkhref = null, $showcourselink = false) {
5424 global $CFG;
5426 debugging(
5427 __FUNCTION__ . '() has been deprecated. ' .
5428 'Please see block_calendar_upcoming::get_content() for the correct API usage.',
5429 DEBUG_DEVELOPER
5432 require_once($CFG->dirroot . '/blocks/moodleblock.class.php');
5433 require_once($CFG->dirroot . '/blocks/calendar_upcoming/block_calendar_upcoming.php');
5434 return block_calendar_upcoming::get_upcoming_content($events, $linkhref, $showcourselink);
5438 * Display month selector options.
5440 * @deprecated since 3.3
5441 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5442 * @param string $name for the select element
5443 * @param string|array $selected options for select elements
5445 function calendar_print_month_selector($name, $selected) {
5446 debugging(__FUNCTION__ . '() is deprecated and no longer used in core.', DEBUG_DEVELOPER);
5447 $months = array();
5448 for ($i = 1; $i <= 12; $i++) {
5449 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
5451 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
5452 echo html_writer::select($months, $name, $selected, false);
5456 * Update calendar subscriptions.
5458 * @deprecated since 3.3
5459 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5460 * @return bool
5462 function calendar_cron() {
5463 debugging(__FUNCTION__ . '() is deprecated and should not be used. Please use the core\task\calendar_cron_task instead.',
5464 DEBUG_DEVELOPER);
5466 global $CFG, $DB;
5468 require_once($CFG->dirroot . '/calendar/lib.php');
5469 // In order to execute this we need bennu.
5470 require_once($CFG->libdir.'/bennu/bennu.inc.php');
5472 mtrace('Updating calendar subscriptions:');
5473 cron_trace_time_and_memory();
5475 $time = time();
5476 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0
5477 AND lastupdated + pollinterval < ?', array($time));
5478 foreach ($subscriptions as $sub) {
5479 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
5480 try {
5481 $log = calendar_update_subscription_events($sub->id);
5482 mtrace(trim(strip_tags($log)));
5483 } catch (moodle_exception $ex) {
5484 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
5488 mtrace('Finished updating calendar subscriptions.');
5490 return true;
5494 * Previous internal API, it was not supposed to be used anywhere.
5496 * @access private
5497 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
5498 * @param int $userid the id of the user
5499 * @param context_course $coursecontext course context
5500 * @param array $accessdata accessdata array (modified)
5501 * @return void modifies $accessdata parameter
5503 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
5504 throw new coding_exception('load_course_context() is removed. Do not use private functions or data structures.');
5508 * Previous internal API, it was not supposed to be used anywhere.
5510 * @access private
5511 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
5512 * @param int $roleid the id of the user
5513 * @param context $context needs path!
5514 * @param array $accessdata accessdata array (is modified)
5515 * @return array
5517 function load_role_access_by_context($roleid, context $context, &$accessdata) {
5518 throw new coding_exception('load_role_access_by_context() is removed. Do not use private functions or data structures.');
5522 * Previous internal API, it was not supposed to be used anywhere.
5524 * @access private
5525 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
5526 * @return void
5528 function dedupe_user_access() {
5529 throw new coding_exception('dedupe_user_access() is removed. Do not use private functions or data structures.');
5533 * Previous internal API, it was not supposed to be used anywhere.
5534 * Return a nested array showing role assignments
5535 * and all relevant role capabilities for the user.
5537 * [ra] => [/path][roleid]=roleid
5538 * [rdef] => ["$contextpath:$roleid"][capability]=permission
5540 * @access private
5541 * @deprecated since Moodle 3.4. MDL-49398.
5542 * @param int $userid - the id of the user
5543 * @return array access info array
5545 function get_user_access_sitewide($userid) {
5546 debugging('get_user_access_sitewide() is deprecated. Do not use private functions or data structures.', DEBUG_DEVELOPER);
5548 $accessdata = get_user_accessdata($userid);
5549 $accessdata['rdef'] = array();
5550 $roles = array();
5552 foreach ($accessdata['ra'] as $path => $pathroles) {
5553 $roles = array_merge($pathroles, $roles);
5556 $rdefs = get_role_definitions($roles);
5558 foreach ($rdefs as $roleid => $rdef) {
5559 foreach ($rdef as $path => $caps) {
5560 $accessdata['rdef']["$path:$roleid"] = $caps;
5564 return $accessdata;
5568 * Generates the HTML for a miniature calendar.
5570 * @param array $courses list of course to list events from
5571 * @param array $groups list of group
5572 * @param array $users user's info
5573 * @param int|bool $calmonth calendar month in numeric, default is set to false
5574 * @param int|bool $calyear calendar month in numeric, default is set to false
5575 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
5576 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
5577 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
5578 * and $calyear to support multiple calendars
5579 * @return string $content return html table for mini calendar
5580 * @deprecated since Moodle 3.4. MDL-59333
5582 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
5583 $courseid = false, $time = 0) {
5584 global $PAGE;
5586 debugging('calendar_get_mini() has been deprecated. Please update your code to use calendar_get_view.',
5587 DEBUG_DEVELOPER);
5589 if (!empty($calmonth) && !empty($calyear)) {
5590 // Do this check for backwards compatibility.
5591 // The core should be passing a timestamp rather than month and year.
5592 // If a month and year are passed they will be in Gregorian.
5593 // Ensure it is a valid date, else we will just set it to the current timestamp.
5594 if (checkdate($calmonth, 1, $calyear)) {
5595 $time = make_timestamp($calyear, $calmonth, 1);
5596 } else {
5597 $time = time();
5599 } else if (empty($time)) {
5600 // Get the current date in the calendar type being used.
5601 $time = time();
5604 if ($courseid == SITEID) {
5605 $course = get_site();
5606 } else {
5607 $course = get_course($courseid);
5609 $calendar = new calendar_information(0, 0, 0, $time);
5610 $calendar->prepare_for_view($course, $courses);
5612 $renderer = $PAGE->get_renderer('core_calendar');
5613 list($data, $template) = calendar_get_view($calendar, 'mini');
5614 return $renderer->render_from_template($template, $data);
5618 * Gets the calendar upcoming event.
5620 * @param array $courses array of courses
5621 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
5622 * @param array|int|bool $users array of users, user id or boolean for all/no user events
5623 * @param int $daysinfuture number of days in the future we 'll look
5624 * @param int $maxevents maximum number of events
5625 * @param int $fromtime start time
5626 * @return array $output array of upcoming events
5627 * @deprecated since Moodle 3.4. MDL-59333
5629 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
5630 debugging(
5631 'calendar_get_upcoming() has been deprecated. ' .
5632 'Please see block_calendar_upcoming::get_content() for the correct API usage.',
5633 DEBUG_DEVELOPER
5636 global $COURSE;
5638 $display = new \stdClass;
5639 $display->range = $daysinfuture; // How many days in the future we 'll look.
5640 $display->maxevents = $maxevents;
5642 $output = array();
5644 $processed = 0;
5645 $now = time(); // We 'll need this later.
5646 $usermidnighttoday = usergetmidnight($now);
5648 if ($fromtime) {
5649 $display->tstart = $fromtime;
5650 } else {
5651 $display->tstart = $usermidnighttoday;
5654 // This works correctly with respect to the user's DST, but it is accurate
5655 // only because $fromtime is always the exact midnight of some day!
5656 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
5658 // Get the events matching our criteria.
5659 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
5661 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
5662 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
5663 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
5664 // arguments to this function.
5665 $hrefparams = array();
5666 if (!empty($courses)) {
5667 $courses = array_diff($courses, array(SITEID));
5668 if (count($courses) == 1) {
5669 $hrefparams['course'] = reset($courses);
5673 if ($events !== false) {
5674 foreach ($events as $event) {
5675 if (!empty($event->modulename)) {
5676 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
5677 if (empty($instances[$event->instance]->uservisible)) {
5678 continue;
5682 if ($processed >= $display->maxevents) {
5683 break;
5686 $event->time = calendar_format_event_time($event, $now, $hrefparams);
5687 $output[] = $event;
5688 $processed++;
5692 return $output;
5696 * Creates a record in the role_allow_override table
5698 * @param int $sroleid source roleid
5699 * @param int $troleid target roleid
5700 * @return void
5701 * @deprecated since Moodle 3.4. MDL-50666
5703 function allow_override($sroleid, $troleid) {
5704 debugging('allow_override() has been deprecated. Please update your code to use core_role_set_override_allowed.',
5705 DEBUG_DEVELOPER);
5707 core_role_set_override_allowed($sroleid, $troleid);
5711 * Creates a record in the role_allow_assign table
5713 * @param int $fromroleid source roleid
5714 * @param int $targetroleid target roleid
5715 * @return void
5716 * @deprecated since Moodle 3.4. MDL-50666
5718 function allow_assign($fromroleid, $targetroleid) {
5719 debugging('allow_assign() has been deprecated. Please update your code to use core_role_set_assign_allowed.',
5720 DEBUG_DEVELOPER);
5722 core_role_set_assign_allowed($fromroleid, $targetroleid);
5726 * Creates a record in the role_allow_switch table
5728 * @param int $fromroleid source roleid
5729 * @param int $targetroleid target roleid
5730 * @return void
5731 * @deprecated since Moodle 3.4. MDL-50666
5733 function allow_switch($fromroleid, $targetroleid) {
5734 debugging('allow_switch() has been deprecated. Please update your code to use core_role_set_switch_allowed.',
5735 DEBUG_DEVELOPER);
5737 core_role_set_switch_allowed($fromroleid, $targetroleid);
5741 * Organise categories into a single parent category (called the 'Top' category) per context.
5743 * @param array $categories List of question categories in the format of ["$categoryid,$contextid" => $category].
5744 * @param array $pcontexts List of context ids.
5745 * @return array
5746 * @deprecated since Moodle 3.5. MDL-61132
5748 function question_add_tops($categories, $pcontexts) {
5749 debugging('question_add_tops() has been deprecated. You may want to pass $top = true to get_categories_for_contexts().',
5750 DEBUG_DEVELOPER);
5752 $topcats = array();
5753 foreach ($pcontexts as $contextid) {
5754 $topcat = question_get_top_category($contextid, true);
5755 $context = context::instance_by_id($contextid);
5757 $newcat = new stdClass();
5758 $newcat->id = "{$topcat->id},$contextid";
5759 $newcat->name = get_string('topfor', 'question', $context->get_context_name(false));
5760 $newcat->parent = 0;
5761 $newcat->contextid = $contextid;
5762 $topcats["{$topcat->id},$contextid"] = $newcat;
5764 // Put topcats in at beginning of array - they'll be sorted into different contexts later.
5765 return array_merge($topcats, $categories);
5769 * Checks if the question category is the highest-level category in the context that can be edited, and has no siblings.
5771 * @param int $categoryid a category id.
5772 * @return bool
5773 * @deprecated since Moodle 3.5. MDL-61132
5775 function question_is_only_toplevel_category_in_context($categoryid) {
5776 debugging('question_is_only_toplevel_category_in_context() has been deprecated. '
5777 . 'Please update your code to use question_is_only_child_of_top_category_in_context() instead.',
5778 DEBUG_DEVELOPER);
5780 return question_is_only_child_of_top_category_in_context($categoryid);
5784 * Moves messages from a particular user from the message table (unread messages) to message_read
5785 * This is typically only used when a user is deleted
5787 * @param object $userid User id
5788 * @return boolean success
5789 * @deprecated since Moodle 3.5
5791 function message_move_userfrom_unread2read($userid) {
5792 debugging('message_move_userfrom_unread2read() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5794 global $DB;
5796 // Move all unread messages from message table to message_read.
5797 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
5798 foreach ($messages as $message) {
5799 message_mark_message_read($message, 0); // Set timeread to 0 as the message was never read.
5802 return true;
5806 * Retrieve users blocked by $user1
5808 * @param object $user1 the user whose messages are being viewed
5809 * @param object $user2 the user $user1 is talking to. If they are being blocked
5810 * they will have a variable called 'isblocked' added to their user object
5811 * @return array the users blocked by $user1
5812 * @deprecated since Moodle 3.5
5814 function message_get_blocked_users($user1=null, $user2=null) {
5815 debugging('message_get_blocked_users() is deprecated, please use \core_message\api::get_blocked_users() instead.',
5816 DEBUG_DEVELOPER);
5818 global $USER;
5820 if (empty($user1)) {
5821 $user1 = new stdClass();
5822 $user1->id = $USER->id;
5825 return \core_message\api::get_blocked_users($user1->id);
5829 * Retrieve $user1's contacts (online, offline and strangers)
5831 * @param object $user1 the user whose messages are being viewed
5832 * @param object $user2 the user $user1 is talking to. If they are a contact
5833 * they will have a variable called 'iscontact' added to their user object
5834 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
5835 * @deprecated since Moodle 3.5
5837 function message_get_contacts($user1=null, $user2=null) {
5838 debugging('message_get_contacts() is deprecated and is no longer used.', DEBUG_DEVELOPER);
5840 global $DB, $CFG, $USER;
5842 if (empty($user1)) {
5843 $user1 = $USER;
5846 if (!empty($user2)) {
5847 $user2->iscontact = false;
5850 $timetoshowusers = 300; // Seconds default.
5851 if (isset($CFG->block_online_users_timetosee)) {
5852 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
5855 // Rime which a user is counting as being active since.
5856 $timefrom = time() - $timetoshowusers;
5858 // People in our contactlist who are online.
5859 $onlinecontacts = array();
5860 // People in our contactlist who are offline.
5861 $offlinecontacts = array();
5862 // People who are not in our contactlist but have sent us a message.
5863 $strangers = array();
5865 // Get all in our contact list who are not blocked in our and count messages we have waiting from each of them.
5866 $rs = \core_message\api::get_contacts_with_unread_message_count($user1->id);
5867 foreach ($rs as $rd) {
5868 if ($rd->lastaccess >= $timefrom) {
5869 // They have been active recently, so are counted online.
5870 $onlinecontacts[] = $rd;
5872 } else {
5873 $offlinecontacts[] = $rd;
5876 if (!empty($user2) && $user2->id == $rd->id) {
5877 $user2->iscontact = true;
5881 // Get messages from anyone who isn't in our contact list and count the number of messages we have from each of them.
5882 $rs = \core_message\api::get_non_contacts_with_unread_message_count($user1->id);
5883 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
5884 foreach ($rs as $rd) {
5885 $strangers[$rd->id] = $rd;
5888 // Add noreply user and support user to the list, if they don't exist.
5889 $supportuser = core_user::get_support_user();
5890 if (!isset($strangers[$supportuser->id]) && !$supportuser->deleted) {
5891 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
5892 if ($supportuser->messagecount > 0) {
5893 $strangers[$supportuser->id] = $supportuser;
5897 $noreplyuser = core_user::get_noreply_user();
5898 if (!isset($strangers[$noreplyuser->id]) && !$noreplyuser->deleted) {
5899 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
5900 if ($noreplyuser->messagecount > 0) {
5901 $strangers[$noreplyuser->id] = $noreplyuser;
5905 return array($onlinecontacts, $offlinecontacts, $strangers);
5909 * Mark a single message as read
5911 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
5912 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
5913 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
5914 * @return int the ID of the message in the messags table
5915 * @deprecated since Moodle 3.5
5917 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
5918 debugging('message_mark_message_read() is deprecated, please use \core_message\api::mark_message_as_read()
5919 or \core_message\api::mark_notification_as_read().', DEBUG_DEVELOPER);
5921 if (!empty($message->notification)) {
5922 \core_message\api::mark_notification_as_read($message, $timeread);
5923 } else {
5924 \core_message\api::mark_message_as_read($message->useridto, $message, $timeread);
5927 return $message->id;
5932 * Checks if a user can delete a message.
5934 * @param stdClass $message the message to delete
5935 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
5936 * but will still seem as if it was by the user)
5937 * @return bool Returns true if a user can delete the message, false otherwise.
5938 * @deprecated since Moodle 3.5
5940 function message_can_delete_message($message, $userid) {
5941 debugging('message_can_delete_message() is deprecated, please use \core_message\api::can_delete_message() instead.',
5942 DEBUG_DEVELOPER);
5944 return \core_message\api::can_delete_message($userid, $message->id);
5948 * Deletes a message.
5950 * This function does not verify any permissions.
5952 * @param stdClass $message the message to delete
5953 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
5954 * but will still seem as if it was by the user)
5955 * @return bool
5956 * @deprecated since Moodle 3.5
5958 function message_delete_message($message, $userid) {
5959 debugging('message_delete_message() is deprecated, please use \core_message\api::delete_message() instead.',
5960 DEBUG_DEVELOPER);
5962 return \core_message\api::delete_message($userid, $message->id);
5966 * Get all of the allowed types for all of the courses and groups
5967 * the logged in user belongs to.
5969 * The returned array will optionally have 5 keys:
5970 * 'user' : true if the logged in user can create user events
5971 * 'site' : true if the logged in user can create site events
5972 * 'category' : array of course categories that the user can create events for
5973 * 'course' : array of courses that the user can create events for
5974 * 'group': array of groups that the user can create events for
5975 * 'groupcourses' : array of courses that the groups belong to (can
5976 * be different from the list in 'course'.
5977 * @deprecated since 3.6
5978 * @return array The array of allowed types.
5980 function calendar_get_all_allowed_types() {
5981 debugging('calendar_get_all_allowed_types() is deprecated. Please use calendar_get_allowed_types() instead.',
5982 DEBUG_DEVELOPER);
5984 global $CFG, $USER, $DB;
5986 require_once($CFG->libdir . '/enrollib.php');
5988 $types = [];
5990 $allowed = new stdClass();
5992 calendar_get_allowed_types($allowed);
5994 if ($allowed->user) {
5995 $types['user'] = true;
5998 if ($allowed->site) {
5999 $types['site'] = true;
6002 if (coursecat::has_manage_capability_on_any()) {
6003 $types['category'] = coursecat::make_categories_list('moodle/category:manage');
6006 // This function warms the context cache for the course so the calls
6007 // to load the course context in calendar_get_allowed_types don't result
6008 // in additional DB queries.
6009 $courses = calendar_get_default_courses(null, 'id, groupmode, groupmodeforce', true);
6011 // We want to pre-fetch all of the groups for each course in a single
6012 // query to avoid calendar_get_allowed_types from hitting the DB for
6013 // each separate course.
6014 $groups = groups_get_all_groups_for_courses($courses);
6016 foreach ($courses as $course) {
6017 $coursegroups = isset($groups[$course->id]) ? $groups[$course->id] : null;
6018 calendar_get_allowed_types($allowed, $course, $coursegroups);
6020 if (!empty($allowed->courses)) {
6021 $types['course'][$course->id] = $course;
6024 if (!empty($allowed->groups)) {
6025 $types['groupcourses'][$course->id] = $course;
6027 if (!isset($types['group'])) {
6028 $types['group'] = array_values($allowed->groups);
6029 } else {
6030 $types['group'] = array_merge($types['group'], array_values($allowed->groups));
6035 return $types;
6039 * Gets array of all groups in a set of course.
6041 * @category group
6042 * @param array $courses Array of course objects or course ids.
6043 * @return array Array of groups indexed by course id.
6045 function groups_get_all_groups_for_courses($courses) {
6046 global $DB;
6048 if (empty($courses)) {
6049 return [];
6052 $groups = [];
6053 $courseids = [];
6055 foreach ($courses as $course) {
6056 $courseid = is_object($course) ? $course->id : $course;
6057 $groups[$courseid] = [];
6058 $courseids[] = $courseid;
6061 $groupfields = [
6062 'g.id as gid',
6063 'g.courseid',
6064 'g.idnumber',
6065 'g.name',
6066 'g.description',
6067 'g.descriptionformat',
6068 'g.enrolmentkey',
6069 'g.picture',
6070 'g.hidepicture',
6071 'g.timecreated',
6072 'g.timemodified'
6075 $groupsmembersfields = [
6076 'gm.id as gmid',
6077 'gm.groupid',
6078 'gm.userid',
6079 'gm.timeadded',
6080 'gm.component',
6081 'gm.itemid'
6084 $concatidsql = $DB->sql_concat_join("'-'", ['g.id', 'COALESCE(gm.id, 0)']) . ' AS uniqid';
6085 list($courseidsql, $params) = $DB->get_in_or_equal($courseids);
6086 $groupfieldssql = implode(',', $groupfields);
6087 $groupmembersfieldssql = implode(',', $groupsmembersfields);
6088 $sql = "SELECT {$concatidsql}, {$groupfieldssql}, {$groupmembersfieldssql}
6089 FROM {groups} g
6090 LEFT JOIN {groups_members} gm
6091 ON gm.groupid = g.id
6092 WHERE g.courseid {$courseidsql}";
6094 $results = $DB->get_records_sql($sql, $params);
6096 // The results will come back as a flat dataset thanks to the left
6097 // join so we will need to do some post processing to blow it out
6098 // into a more usable data structure.
6100 // This loop will extract the distinct groups from the result set
6101 // and add it's list of members to the object as a property called
6102 // 'members'. Then each group will be added to the result set indexed
6103 // by it's course id.
6105 // The resulting data structure for $groups should be:
6106 // $groups = [
6107 // '1' = [
6108 // '1' => (object) [
6109 // 'id' => 1,
6110 // <rest of group properties>
6111 // 'members' => [
6112 // '1' => (object) [
6113 // <group member properties>
6114 // ],
6115 // '2' => (object) [
6116 // <group member properties>
6117 // ]
6118 // ]
6119 // ],
6120 // '2' => (object) [
6121 // 'id' => 2,
6122 // <rest of group properties>
6123 // 'members' => [
6124 // '1' => (object) [
6125 // <group member properties>
6126 // ],
6127 // '3' => (object) [
6128 // <group member properties>
6129 // ]
6130 // ]
6131 // ]
6132 // ]
6133 // ]
6135 foreach ($results as $key => $result) {
6136 $groupid = $result->gid;
6137 $courseid = $result->courseid;
6138 $coursegroups = $groups[$courseid];
6139 $groupsmembersid = $result->gmid;
6140 $reducefunc = function($carry, $field) use ($result) {
6141 // Iterate over the groups properties and pull
6142 // them out into a separate object.
6143 list($prefix, $field) = explode('.', $field);
6145 if (property_exists($result, $field)) {
6146 $carry[$field] = $result->{$field};
6149 return $carry;
6152 if (isset($coursegroups[$groupid])) {
6153 $group = $coursegroups[$groupid];
6154 } else {
6155 $initial = [
6156 'id' => $groupid,
6157 'members' => []
6159 $group = (object) array_reduce(
6160 $groupfields,
6161 $reducefunc,
6162 $initial
6166 if (!empty($groupsmembersid)) {
6167 $initial = ['id' => $groupsmembersid];
6168 $groupsmembers = (object) array_reduce(
6169 $groupsmembersfields,
6170 $reducefunc,
6171 $initial
6174 $group->members[$groupsmembers->userid] = $groupsmembers;
6177 $coursegroups[$groupid] = $group;
6178 $groups[$courseid] = $coursegroups;
6181 return $groups;
6185 * Gets the capabilities that have been cached in the database for this
6186 * component.
6187 * @deprecated since Moodle 3.6. Please use the Events 2 API.
6188 * @todo final deprecation. To be removed in Moodle 4.0
6190 * @access protected To be used from eventslib only
6192 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
6193 * @return array of events
6195 function events_get_cached($component) {
6196 global $DB;
6198 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.',
6199 DEBUG_DEVELOPER);
6201 $cachedhandlers = array();
6203 if ($storedhandlers = $DB->get_records('events_handlers', array('component'=>$component))) {
6204 foreach ($storedhandlers as $handler) {
6205 $cachedhandlers[$handler->eventname] = array (
6206 'id' => $handler->id,
6207 'handlerfile' => $handler->handlerfile,
6208 'handlerfunction' => $handler->handlerfunction,
6209 'schedule' => $handler->schedule,
6210 'internal' => $handler->internal);
6214 return $cachedhandlers;
6218 * Remove all event handlers and queued events
6219 * @deprecated since Moodle 3.6. Please use the Events 2 API.
6220 * @todo final deprecation. To be removed in Moodle 4.0
6222 * @category event
6223 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
6225 function events_uninstall($component) {
6226 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.',
6227 DEBUG_DEVELOPER);
6228 $cachedhandlers = events_get_cached($component);
6229 events_cleanup($component, $cachedhandlers);
6231 events_get_handlers('reset');
6235 * Deletes cached events that are no longer needed by the component.
6236 * @deprecated since Moodle 3.6. Please use the Events 2 API.
6237 * @todo final deprecation. To be removed in Moodle 4.0
6239 * @access protected To be used from eventslib only
6241 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
6242 * @param array $cachedhandlers array of the cached events definitions that will be
6243 * @return int number of unused handlers that have been removed
6245 function events_cleanup($component, $cachedhandlers) {
6246 global $DB;
6247 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.',
6248 DEBUG_DEVELOPER);
6249 $deletecount = 0;
6250 foreach ($cachedhandlers as $eventname => $cachedhandler) {
6251 if ($qhandlers = $DB->get_records('events_queue_handlers', array('handlerid'=>$cachedhandler['id']))) {
6252 //debugging("Removing pending events from queue before deleting of event handler: $component - $eventname");
6253 foreach ($qhandlers as $qhandler) {
6254 events_dequeue($qhandler);
6257 $DB->delete_records('events_handlers', array('eventname'=>$eventname, 'component'=>$component));
6258 $deletecount++;
6261 return $deletecount;
6265 * Removes this queued handler from the events_queued_handler table
6267 * Removes events_queue record from events_queue if no more references to this event object exists
6268 * @deprecated since Moodle 3.6. Please use the Events 2 API.
6269 * @todo final deprecation. To be removed in Moodle 4.0
6271 * @access protected To be used from eventslib only
6273 * @param stdClass $qhandler A row from the events_queued_handler table
6275 function events_dequeue($qhandler) {
6276 global $DB;
6277 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.',
6278 DEBUG_DEVELOPER);
6279 // first delete the queue handler
6280 $DB->delete_records('events_queue_handlers', array('id'=>$qhandler->id));
6282 // if no more queued handler is pointing to the same event - delete the event too
6283 if (!$DB->record_exists('events_queue_handlers', array('queuedeventid'=>$qhandler->queuedeventid))) {
6284 $DB->delete_records('events_queue', array('id'=>$qhandler->queuedeventid));
6289 * Returns handlers for given event. Uses caching for better perf.
6290 * @deprecated since Moodle 3.6. Please use the Events 2 API.
6291 * @todo final deprecation. To be removed in Moodle 4.0
6293 * @access protected To be used from eventslib only
6295 * @staticvar array $handlers
6296 * @param string $eventname name of event or 'reset'
6297 * @return array|false array of handlers or false otherwise
6299 function events_get_handlers($eventname) {
6300 global $DB;
6301 static $handlers = array();
6302 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.',
6303 DEBUG_DEVELOPER);
6305 if ($eventname === 'reset') {
6306 $handlers = array();
6307 return false;
6310 if (!array_key_exists($eventname, $handlers)) {
6311 $handlers[$eventname] = $DB->get_records('events_handlers', array('eventname'=>$eventname));
6314 return $handlers[$eventname];