Merge branch 'install_master' of https://git.in.moodle.com/amosbot/moodle-install
[moodle.git] / lib / deprecatedlib.php
blob9e9b5198a7129d4d4ee6ed63f4e2882dcdfd7c10
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 * Function to call all event handlers when triggering an event
63 * @deprecated since 2.6
65 * @param string $eventname name of the event
66 * @param mixed $eventdata event data object
67 * @return int number of failed events
69 function events_trigger($eventname, $eventdata) {
70 debugging('events_trigger() is deprecated, please use new events instead', DEBUG_DEVELOPER);
71 return events_trigger_legacy($eventname, $eventdata);
74 /**
75 * List all core subsystems and their location
77 * This is a whitelist of components that are part of the core and their
78 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
79 * plugin is not listed here and it does not have proper plugintype prefix,
80 * then it is considered as course activity module.
82 * The location is optionally dirroot relative path. NULL means there is no special
83 * directory for this subsystem. If the location is set, the subsystem's
84 * renderer.php is expected to be there.
86 * @deprecated since 2.6, use core_component::get_core_subsystems()
88 * @param bool $fullpaths false means relative paths from dirroot, use true for performance reasons
89 * @return array of (string)name => (string|null)location
91 function get_core_subsystems($fullpaths = false) {
92 global $CFG;
94 // NOTE: do not add any other debugging here, keep forever.
96 $subsystems = core_component::get_core_subsystems();
98 if ($fullpaths) {
99 return $subsystems;
102 debugging('Short paths are deprecated when using get_core_subsystems(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
104 $dlength = strlen($CFG->dirroot);
106 foreach ($subsystems as $k => $v) {
107 if ($v === null) {
108 continue;
110 $subsystems[$k] = substr($v, $dlength+1);
113 return $subsystems;
117 * Lists all plugin types.
119 * @deprecated since 2.6, use core_component::get_plugin_types()
121 * @param bool $fullpaths false means relative paths from dirroot
122 * @return array Array of strings - name=>location
124 function get_plugin_types($fullpaths = true) {
125 global $CFG;
127 // NOTE: do not add any other debugging here, keep forever.
129 $types = core_component::get_plugin_types();
131 if ($fullpaths) {
132 return $types;
135 debugging('Short paths are deprecated when using get_plugin_types(), please fix the code to use fullpaths instead.', DEBUG_DEVELOPER);
137 $dlength = strlen($CFG->dirroot);
139 foreach ($types as $k => $v) {
140 if ($k === 'theme') {
141 $types[$k] = 'theme';
142 continue;
144 $types[$k] = substr($v, $dlength+1);
147 return $types;
151 * Use when listing real plugins of one type.
153 * @deprecated since 2.6, use core_component::get_plugin_list()
155 * @param string $plugintype type of plugin
156 * @return array name=>fulllocation pairs of plugins of given type
158 function get_plugin_list($plugintype) {
160 // NOTE: do not add any other debugging here, keep forever.
162 if ($plugintype === '') {
163 $plugintype = 'mod';
166 return core_component::get_plugin_list($plugintype);
170 * Get a list of all the plugins of a given type that define a certain class
171 * in a certain file. The plugin component names and class names are returned.
173 * @deprecated since 2.6, use core_component::get_plugin_list_with_class()
175 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
176 * @param string $class the part of the name of the class after the
177 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
178 * names like report_courselist_thing. If you are looking for classes with
179 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
180 * @param string $file the name of file within the plugin that defines the class.
181 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
182 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
184 function get_plugin_list_with_class($plugintype, $class, $file) {
186 // NOTE: do not add any other debugging here, keep forever.
188 return core_component::get_plugin_list_with_class($plugintype, $class, $file);
192 * Returns the exact absolute path to plugin directory.
194 * @deprecated since 2.6, use core_component::get_plugin_directory()
196 * @param string $plugintype type of plugin
197 * @param string $name name of the plugin
198 * @return string full path to plugin directory; NULL if not found
200 function get_plugin_directory($plugintype, $name) {
202 // NOTE: do not add any other debugging here, keep forever.
204 if ($plugintype === '') {
205 $plugintype = 'mod';
208 return core_component::get_plugin_directory($plugintype, $name);
212 * Normalize the component name using the "frankenstyle" names.
214 * @deprecated since 2.6, use core_component::normalize_component()
216 * @param string $component
217 * @return array two-items list of [(string)type, (string|null)name]
219 function normalize_component($component) {
221 // NOTE: do not add any other debugging here, keep forever.
223 return core_component::normalize_component($component);
227 * Return exact absolute path to a plugin directory.
229 * @deprecated since 2.6, use core_component::normalize_component()
231 * @param string $component name such as 'moodle', 'mod_forum'
232 * @return string full path to component directory; NULL if not found
234 function get_component_directory($component) {
236 // NOTE: do not add any other debugging here, keep forever.
238 return core_component::get_component_directory($component);
242 * Get the context instance as an object. This function will create the
243 * context instance if it does not exist yet.
245 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
246 * @todo This will be deleted in Moodle 2.8, refer MDL-34472
247 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
248 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
249 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
250 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
251 * MUST_EXIST means throw exception if no record or multiple records found
252 * @return context The context object.
254 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
256 debugging('get_context_instance() is deprecated, please use context_xxxx::instance() instead.', DEBUG_DEVELOPER);
258 $instances = (array)$instance;
259 $contexts = array();
261 $classname = context_helper::get_class_for_level($contextlevel);
263 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
264 foreach ($instances as $inst) {
265 $contexts[$inst] = $classname::instance($inst, $strictness);
268 if (is_array($instance)) {
269 return $contexts;
270 } else {
271 return $contexts[$instance];
274 /* === End of long term deprecated api list === */
277 * Adds a file upload to the log table so that clam can resolve the filename to the user later if necessary
279 * @deprecated since 2.7 - use new file picker instead
282 function clam_log_upload($newfilepath, $course=null, $nourl=false) {
283 throw new coding_exception('clam_log_upload() can not be used any more, please use file picker instead');
287 * This function logs to error_log and to the log table that an infected file has been found and what's happened to it.
289 * @deprecated since 2.7 - use new file picker instead
292 function clam_log_infected($oldfilepath='', $newfilepath='', $userid=0) {
293 throw new coding_exception('clam_log_infected() can not be used any more, please use file picker instead');
297 * Some of the modules allow moving attachments (glossary), in which case we need to hunt down an original log and change the path.
299 * @deprecated since 2.7 - use new file picker instead
302 function clam_change_log($oldpath, $newpath, $update=true) {
303 throw new coding_exception('clam_change_log() can not be used any more, please use file picker instead');
307 * Replaces the given file with a string.
309 * @deprecated since 2.7 - infected files are now deleted in file picker
312 function clam_replace_infected_file($file) {
313 throw new coding_exception('clam_replace_infected_file() can not be used any more, please use file picker instead');
317 * Deals with an infected file - either moves it to a quarantinedir
318 * (specified in CFG->quarantinedir) or deletes it.
320 * If moving it fails, it deletes it.
322 * @deprecated since 2.7
324 function clam_handle_infected_file($file, $userid=0, $basiconly=false) {
325 throw new coding_exception('clam_handle_infected_file() can not be used any more, please use file picker instead');
329 * If $CFG->runclamonupload is set, we scan a given file. (called from {@link preprocess_files()})
331 * @deprecated since 2.7
333 function clam_scan_moodle_file(&$file, $course) {
334 throw new coding_exception('clam_scan_moodle_file() can not be used any more, please use file picker instead');
339 * Checks whether the password compatibility library will work with the current
340 * version of PHP. This cannot be done using PHP version numbers since the fix
341 * has been backported to earlier versions in some distributions.
343 * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
345 * @deprecated since 2.7 PHP 5.4.x should be always compatible.
348 function password_compat_not_supported() {
349 throw new coding_exception('Do not use password_compat_not_supported() - bcrypt is now always available');
353 * Factory method that was returning moodle_session object.
355 * @deprecated since 2.6
357 function session_get_instance() {
358 throw new coding_exception('session_get_instance() is removed, use \core\session\manager instead');
362 * Returns true if legacy session used.
364 * @deprecated since 2.6
366 function session_is_legacy() {
367 throw new coding_exception('session_is_legacy() is removed, do not use any more');
371 * Terminates all sessions, auth hooks are not executed.
373 * @deprecated since 2.6
375 function session_kill_all() {
376 throw new coding_exception('session_kill_all() is removed, use \core\session\manager::kill_all_sessions() instead');
380 * Mark session as accessed, prevents timeouts.
382 * @deprecated since 2.6
384 function session_touch($sid) {
385 throw new coding_exception('session_touch() is removed, use \core\session\manager::touch_session() instead');
389 * Terminates one sessions, auth hooks are not executed.
391 * @deprecated since 2.6
393 function session_kill($sid) {
394 throw new coding_exception('session_kill() is removed, use \core\session\manager::kill_session() instead');
398 * Terminates all sessions of one user, auth hooks are not executed.
400 * @deprecated since 2.6
402 function session_kill_user($userid) {
403 throw new coding_exception('session_kill_user() is removed, use \core\session\manager::kill_user_sessions() instead');
407 * Setup $USER object - called during login, loginas, etc.
409 * Call sync_user_enrolments() manually after log-in, or log-in-as.
411 * @deprecated since 2.6
413 function session_set_user($user) {
414 throw new coding_exception('session_set_user() is removed, use \core\session\manager::set_user() instead');
418 * Is current $USER logged-in-as somebody else?
419 * @deprecated since 2.6
421 function session_is_loggedinas() {
422 throw new coding_exception('session_is_loggedinas() is removed, use \core\session\manager::is_loggedinas() instead');
426 * Returns the $USER object ignoring current login-as session
427 * @deprecated since 2.6
429 function session_get_realuser() {
430 throw new coding_exception('session_get_realuser() is removed, use \core\session\manager::get_realuser() instead');
434 * Login as another user - no security checks here.
435 * @deprecated since 2.6
437 function session_loginas($userid, $context) {
438 throw new coding_exception('session_loginas() is removed, use \core\session\manager::loginas() instead');
442 * Minify JavaScript files.
444 * @deprecated since 2.6
446 function js_minify($files) {
447 throw new coding_exception('js_minify() is removed, use core_minify::js_files() or core_minify::js() instead.');
451 * Minify CSS files.
453 * @deprecated since 2.6
455 function css_minify_css($files) {
456 throw new coding_exception('css_minify_css() is removed, use core_minify::css_files() or core_minify::css() instead.');
459 // === Deprecated before 2.6.0 ===
462 * Hack to find out the GD version by parsing phpinfo output
464 * @deprecated
466 function check_gd_version() {
467 throw new coding_exception('check_gd_version() is removed, GD extension is always available now');
471 * Not used any more, the account lockout handling is now
472 * part of authenticate_user_login().
473 * @deprecated
475 function update_login_count() {
476 throw new coding_exception('update_login_count() is removed, all calls need to be removed');
480 * Not used any more, replaced by proper account lockout.
481 * @deprecated
483 function reset_login_count() {
484 throw new coding_exception('reset_login_count() is removed, all calls need to be removed');
488 * @deprecated
490 function update_log_display_entry($module, $action, $mtable, $field) {
492 throw new coding_exception('The update_log_display_entry() is removed, please use db/log.php description file instead.');
496 * @deprecated use the text formatting in a standard way instead (http://docs.moodle.org/dev/Output_functions)
497 * this was abused mostly for embedding of attachments
499 function filter_text($text, $courseid = NULL) {
500 throw new coding_exception('filter_text() can not be used anymore, use format_text(), format_string() etc instead.');
504 * @deprecated Loginhttps is no longer supported
506 function httpsrequired() {
507 throw new coding_exception('httpsrequired() can not be used any more. Loginhttps is no longer supported.');
511 * Given a physical path to a file, returns the URL through which it can be reached in Moodle.
513 * @deprecated since 3.1 - replacement legacy file API methods can be found on the moodle_url class, for example:
514 * The moodle_url::make_legacyfile_url() method can be used to generate a legacy course file url. To generate
515 * course module file.php url the moodle_url::make_file_url() should be used.
517 * @param string $path Physical path to a file
518 * @param array $options associative array of GET variables to append to the URL
519 * @param string $type (questionfile|rssfile|httpscoursefile|coursefile)
520 * @return string URL to file
522 function get_file_url($path, $options=null, $type='coursefile') {
523 debugging('Function get_file_url() is deprecated, please use moodle_url factory methods instead.', DEBUG_DEVELOPER);
524 global $CFG;
526 $path = str_replace('//', '/', $path);
527 $path = trim($path, '/'); // no leading and trailing slashes
529 // type of file
530 switch ($type) {
531 case 'questionfile':
532 $url = $CFG->wwwroot."/question/exportfile.php";
533 break;
534 case 'rssfile':
535 $url = $CFG->wwwroot."/rss/file.php";
536 break;
537 case 'coursefile':
538 default:
539 $url = $CFG->wwwroot."/file.php";
542 if ($CFG->slasharguments) {
543 $parts = explode('/', $path);
544 foreach ($parts as $key => $part) {
545 /// anchor dash character should not be encoded
546 $subparts = explode('#', $part);
547 $subparts = array_map('rawurlencode', $subparts);
548 $parts[$key] = implode('#', $subparts);
550 $path = implode('/', $parts);
551 $ffurl = $url.'/'.$path;
552 $separator = '?';
553 } else {
554 $path = rawurlencode('/'.$path);
555 $ffurl = $url.'?file='.$path;
556 $separator = '&amp;';
559 if ($options) {
560 foreach ($options as $name=>$value) {
561 $ffurl = $ffurl.$separator.$name.'='.$value;
562 $separator = '&amp;';
566 return $ffurl;
570 * @deprecated use get_enrolled_users($context) instead.
572 function get_course_participants($courseid) {
573 throw new coding_exception('get_course_participants() can not be used any more, use get_enrolled_users() instead.');
577 * @deprecated use is_enrolled($context, $userid) instead.
579 function is_course_participant($userid, $courseid) {
580 throw new coding_exception('is_course_participant() can not be used any more, use is_enrolled() instead.');
584 * @deprecated
586 function get_recent_enrolments($courseid, $timestart) {
587 throw new coding_exception('get_recent_enrolments() is removed as it returned inaccurate results.');
591 * @deprecated use clean_param($string, PARAM_FILE) instead.
593 function detect_munged_arguments($string, $allowdots=1) {
594 throw new coding_exception('detect_munged_arguments() can not be used any more, please use clean_param(,PARAM_FILE) instead.');
599 * Unzip one zip file to a destination dir
600 * Both parameters must be FULL paths
601 * If destination isn't specified, it will be the
602 * SAME directory where the zip file resides.
604 * @global object
605 * @param string $zipfile The zip file to unzip
606 * @param string $destination The location to unzip to
607 * @param bool $showstatus_ignored Unused
608 * @deprecated since 2.0 MDL-15919
610 function unzip_file($zipfile, $destination = '', $showstatus_ignored = true) {
611 debugging(__FUNCTION__ . '() is deprecated. '
612 . 'Please use the application/zip file_packer implementation instead.', DEBUG_DEVELOPER);
614 // Extract everything from zipfile.
615 $path_parts = pathinfo(cleardoubleslashes($zipfile));
616 $zippath = $path_parts["dirname"]; //The path of the zip file
617 $zipfilename = $path_parts["basename"]; //The name of the zip file
618 $extension = $path_parts["extension"]; //The extension of the file
620 //If no file, error
621 if (empty($zipfilename)) {
622 return false;
625 //If no extension, error
626 if (empty($extension)) {
627 return false;
630 //Clear $zipfile
631 $zipfile = cleardoubleslashes($zipfile);
633 //Check zipfile exists
634 if (!file_exists($zipfile)) {
635 return false;
638 //If no destination, passed let's go with the same directory
639 if (empty($destination)) {
640 $destination = $zippath;
643 //Clear $destination
644 $destpath = rtrim(cleardoubleslashes($destination), "/");
646 //Check destination path exists
647 if (!is_dir($destpath)) {
648 return false;
651 $packer = get_file_packer('application/zip');
653 $result = $packer->extract_to_pathname($zipfile, $destpath);
655 if ($result === false) {
656 return false;
659 foreach ($result as $status) {
660 if ($status !== true) {
661 return false;
665 return true;
669 * Zip an array of files/dirs to a destination zip file
670 * Both parameters must be FULL paths to the files/dirs
672 * @global object
673 * @param array $originalfiles Files to zip
674 * @param string $destination The destination path
675 * @return bool Outcome
677 * @deprecated since 2.0 MDL-15919
679 function zip_files($originalfiles, $destination) {
680 debugging(__FUNCTION__ . '() is deprecated. '
681 . 'Please use the application/zip file_packer implementation instead.', DEBUG_DEVELOPER);
683 // Extract everything from destination.
684 $path_parts = pathinfo(cleardoubleslashes($destination));
685 $destpath = $path_parts["dirname"]; //The path of the zip file
686 $destfilename = $path_parts["basename"]; //The name of the zip file
687 $extension = $path_parts["extension"]; //The extension of the file
689 //If no file, error
690 if (empty($destfilename)) {
691 return false;
694 //If no extension, add it
695 if (empty($extension)) {
696 $extension = 'zip';
697 $destfilename = $destfilename.'.'.$extension;
700 //Check destination path exists
701 if (!is_dir($destpath)) {
702 return false;
705 //Check destination path is writable. TODO!!
707 //Clean destination filename
708 $destfilename = clean_filename($destfilename);
710 //Now check and prepare every file
711 $files = array();
712 $origpath = NULL;
714 foreach ($originalfiles as $file) { //Iterate over each file
715 //Check for every file
716 $tempfile = cleardoubleslashes($file); // no doubleslashes!
717 //Calculate the base path for all files if it isn't set
718 if ($origpath === NULL) {
719 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
721 //See if the file is readable
722 if (!is_readable($tempfile)) { //Is readable
723 continue;
725 //See if the file/dir is in the same directory than the rest
726 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
727 continue;
729 //Add the file to the array
730 $files[] = $tempfile;
733 $zipfiles = array();
734 $start = strlen($origpath)+1;
735 foreach($files as $file) {
736 $zipfiles[substr($file, $start)] = $file;
739 $packer = get_file_packer('application/zip');
741 return $packer->archive_to_pathname($zipfiles, $destpath . '/' . $destfilename);
745 * @deprecated use groups_get_all_groups() instead.
747 function mygroupid($courseid) {
748 throw new coding_exception('mygroupid() can not be used any more, please use groups_get_all_groups() instead.');
752 * @deprecated since Moodle 2.0 MDL-14617 - please do not use this function any more.
754 function groupmode($course, $cm=null) {
755 throw new coding_exception('groupmode() can not be used any more, please use groups_get_* instead.');
759 * @deprecated Since year 2006 - please do not use this function any more.
761 function set_current_group($courseid, $groupid) {
762 throw new coding_exception('set_current_group() can not be used anymore, please use $SESSION->currentgroup[$courseid] instead');
766 * @deprecated Since year 2006 - please do not use this function any more.
768 function get_current_group($courseid, $full = false) {
769 throw new coding_exception('get_current_group() can not be used any more, please use groups_get_* instead');
773 * @deprecated Since Moodle 2.8
775 function groups_filter_users_by_course_module_visible($cm, $users) {
776 throw new coding_exception('groups_filter_users_by_course_module_visible() is removed. ' .
777 'Replace with a call to \core_availability\info_module::filter_user_list(), ' .
778 'which does basically the same thing but includes other restrictions such ' .
779 'as profile restrictions.');
783 * @deprecated Since Moodle 2.8
785 function groups_course_module_visible($cm, $userid=null) {
786 throw new coding_exception('groups_course_module_visible() is removed, use $cm->uservisible to decide whether the current
787 user can ' . 'access an activity.', DEBUG_DEVELOPER);
791 * @deprecated since 2.0
793 function error($message, $link='') {
794 throw new coding_exception('notlocalisederrormessage', 'error', $link, $message, 'error() is a removed, please call
795 print_error() instead of error()');
800 * @deprecated use $PAGE->theme->name instead.
802 function current_theme() {
803 throw new coding_exception('current_theme() can not be used any more, please use $PAGE->theme->name instead');
807 * @deprecated
809 function formerr($error) {
810 throw new coding_exception('formerr() is removed. Please change your code to use $OUTPUT->error_text($string).');
814 * @deprecated use $OUTPUT->skip_link_target() in instead.
816 function skip_main_destination() {
817 throw new coding_exception('skip_main_destination() can not be used any more, please use $OUTPUT->skip_link_target() instead.');
821 * @deprecated use $OUTPUT->container() instead.
823 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
824 throw new coding_exception('print_container() can not be used any more. Please use $OUTPUT->container() instead.');
828 * @deprecated use $OUTPUT->container_start() instead.
830 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
831 throw new coding_exception('print_container_start() can not be used any more. Please use $OUTPUT->container_start() instead.');
835 * @deprecated use $OUTPUT->container_end() instead.
837 function print_container_end($return=false) {
838 throw new coding_exception('print_container_end() can not be used any more. Please use $OUTPUT->container_end() instead.');
842 * @deprecated since Moodle 2.0 MDL-19077 - use $OUTPUT->notification instead.
844 function notify() {
845 throw new coding_exception('notify() is removed, please use $OUTPUT->notification() instead');
849 * @deprecated use $OUTPUT->continue_button() instead.
851 function print_continue($link, $return = false) {
852 throw new coding_exception('print_continue() can not be used any more. Please use $OUTPUT->continue_button() instead.');
856 * @deprecated use $PAGE methods instead.
858 function print_header($title='', $heading='', $navigation='', $focus='',
859 $meta='', $cache=true, $button='&nbsp;', $menu=null,
860 $usexml=false, $bodytags='', $return=false) {
862 throw new coding_exception('print_header() can not be used any more. Please use $PAGE methods instead.');
866 * @deprecated use $PAGE methods instead.
868 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
869 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
871 throw new coding_exception('print_header_simple() can not be used any more. Please use $PAGE methods instead.');
875 * @deprecated use $OUTPUT->block() instead.
877 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
878 throw new coding_exception('print_side_block() can not be used any more, please use $OUTPUT->block() instead.');
882 * Prints a basic textarea field.
884 * @deprecated since Moodle 2.0
886 * When using this function, you should
888 * @global object
889 * @param bool $unused No longer used.
890 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
891 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
892 * @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.
893 * @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.
894 * @param string $name Name to use for the textarea element.
895 * @param string $value Initial content to display in the textarea.
896 * @param int $obsolete deprecated
897 * @param bool $return If false, will output string. If true, will return string value.
898 * @param string $id CSS ID to add to the textarea element.
899 * @return string|void depending on the value of $return
901 function print_textarea($unused, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='') {
902 /// $width and height are legacy fields and no longer used as pixels like they used to be.
903 /// However, you can set them to zero to override the mincols and minrows values below.
905 // Disabling because there is not yet a viable $OUTPUT option for cases when mforms can't be used
906 // debugging('print_textarea() has been deprecated. You should be using mforms and the editor element.');
908 global $CFG;
910 $mincols = 65;
911 $minrows = 10;
912 $str = '';
914 if ($id === '') {
915 $id = 'edit-'.$name;
918 if ($height && ($rows < $minrows)) {
919 $rows = $minrows;
921 if ($width && ($cols < $mincols)) {
922 $cols = $mincols;
925 editors_head_setup();
926 $editor = editors_get_preferred_editor(FORMAT_HTML);
927 $editor->set_text($value);
928 $editor->use_editor($id, array('legacy'=>true));
930 $str .= "\n".'<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'" spellcheck="true">'."\n";
931 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
932 $str .= '</textarea>'."\n";
934 if ($return) {
935 return $str;
937 echo $str;
941 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
942 * provide this function with the language strings for sortasc and sortdesc.
944 * @deprecated use $OUTPUT->arrow() instead.
945 * @todo final deprecation of this function once MDL-45448 is resolved
947 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
949 * @global object
950 * @param string $direction 'up' or 'down'
951 * @param string $strsort The language string used for the alt attribute of this image
952 * @param bool $return Whether to print directly or return the html string
953 * @return string|void depending on $return
956 function print_arrow($direction='up', $strsort=null, $return=false) {
957 global $OUTPUT;
959 debugging('print_arrow() is deprecated. Please use $OUTPUT->arrow() instead.', DEBUG_DEVELOPER);
961 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
962 return null;
965 $return = null;
967 switch ($direction) {
968 case 'up':
969 $sortdir = 'asc';
970 break;
971 case 'down':
972 $sortdir = 'desc';
973 break;
974 case 'move':
975 $sortdir = 'asc';
976 break;
977 default:
978 $sortdir = null;
979 break;
982 // Prepare language string
983 $strsort = '';
984 if (empty($strsort) && !empty($sortdir)) {
985 $strsort = get_string('sort' . $sortdir, 'grades');
988 $return = ' ' . $OUTPUT->pix_icon('t/' . $direction, $strsort) . ' ';
990 if ($return) {
991 return $return;
992 } else {
993 echo $return;
998 * @deprecated since Moodle 2.0
1000 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1001 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
1002 $id='', $listbox=false, $multiple=false, $class='') {
1003 throw new coding_exception('choose_from_menu() is removed. Please change your code to use html_writer::select().');
1008 * @deprecated use $OUTPUT->help_icon_scale($courseid, $scale) instead.
1010 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
1011 throw new coding_exception('print_scale_menu_helpbutton() can not be used any more. '.
1012 'Please use $OUTPUT->help_icon_scale($courseid, $scale) instead.');
1016 * @deprecated use html_writer::checkbox() instead.
1018 function print_checkbox($name, $value, $checked = true, $label = '', $alt = '', $script='', $return=false) {
1019 throw new coding_exception('print_checkbox() can not be used any more. Please use html_writer::checkbox() instead.');
1023 * Prints the 'update this xxx' button that appears on module pages.
1025 * @deprecated since Moodle 3.2
1027 * @param string $cmid the course_module id.
1028 * @param string $ignored not used any more. (Used to be courseid.)
1029 * @param string $string the module name - get_string('modulename', 'xxx')
1030 * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
1032 function update_module_button($cmid, $ignored, $string) {
1033 global $CFG, $OUTPUT;
1035 debugging('update_module_button() has been deprecated and should not be used anymore. Activity modules should not add the ' .
1036 'edit module button, the link is already available in the Administration block. Themes can choose to display the link ' .
1037 'in the buttons row consistently for all module types.', DEBUG_DEVELOPER);
1039 if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1040 $string = get_string('updatethis', '', $string);
1042 $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
1043 return $OUTPUT->single_button($url, $string);
1044 } else {
1045 return '';
1050 * @deprecated use $OUTPUT->navbar() instead
1052 function print_navigation ($navigation, $separator=0, $return=false) {
1053 throw new coding_exception('print_navigation() can not be used any more, please update use $OUTPUT->navbar() instead.');
1057 * @deprecated Please use $PAGE->navabar methods instead.
1059 function build_navigation($extranavlinks, $cm = null) {
1060 throw new coding_exception('build_navigation() can not be used any more, please use $PAGE->navbar methods instead.');
1064 * @deprecated not relevant with global navigation in Moodle 2.x+
1066 function navmenu($course, $cm=NULL, $targetwindow='self') {
1067 throw new coding_exception('navmenu() can not be used any more, it is no longer relevant with global navigation.');
1070 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1074 * @deprecated please use calendar_event::create() instead.
1076 function add_event($event) {
1077 throw new coding_exception('add_event() can not be used any more, please use calendar_event::create() instead.');
1081 * @deprecated please calendar_event->update() instead.
1083 function update_event($event) {
1084 throw new coding_exception('update_event() is removed, please use calendar_event->update() instead.');
1088 * @deprecated please use calendar_event->delete() instead.
1090 function delete_event($id) {
1091 throw new coding_exception('delete_event() can not be used any more, please use '.
1092 'calendar_event->delete() instead.');
1096 * @deprecated please use calendar_event->toggle_visibility(false) instead.
1098 function hide_event($event) {
1099 throw new coding_exception('hide_event() can not be used any more, please use '.
1100 'calendar_event->toggle_visibility(false) instead.');
1104 * @deprecated please use calendar_event->toggle_visibility(true) instead.
1106 function show_event($event) {
1107 throw new coding_exception('show_event() can not be used any more, please use '.
1108 'calendar_event->toggle_visibility(true) instead.');
1112 * @deprecated since Moodle 2.2 use core_text::xxxx() instead.
1113 * @see core_text
1115 function textlib_get_instance() {
1116 throw new coding_exception('textlib_get_instance() can not be used any more, please use '.
1117 'core_text::functioname() instead.');
1121 * @deprecated since 2.4
1122 * @see get_section_name()
1123 * @see format_base::get_section_name()
1126 function get_generic_section_name($format, stdClass $section) {
1127 throw new coding_exception('get_generic_section_name() is deprecated. Please use appropriate functionality from class format_base');
1131 * Returns an array of sections for the requested course id
1133 * It is usually not recommended to display the list of sections used
1134 * in course because the course format may have it's own way to do it.
1136 * If you need to just display the name of the section please call:
1137 * get_section_name($course, $section)
1138 * {@link get_section_name()}
1139 * from 2.4 $section may also be just the field course_sections.section
1141 * If you need the list of all sections it is more efficient to get this data by calling
1142 * $modinfo = get_fast_modinfo($courseorid);
1143 * $sections = $modinfo->get_section_info_all()
1144 * {@link get_fast_modinfo()}
1145 * {@link course_modinfo::get_section_info_all()}
1147 * Information about one section (instance of section_info):
1148 * get_fast_modinfo($courseorid)->get_sections_info($section)
1149 * {@link course_modinfo::get_section_info()}
1151 * @deprecated since 2.4
1153 function get_all_sections($courseid) {
1155 throw new coding_exception('get_all_sections() is removed. See phpdocs for this function');
1159 * This function is deprecated, please use {@link course_add_cm_to_section()}
1160 * Note that course_add_cm_to_section() also updates field course_modules.section and
1161 * calls rebuild_course_cache()
1163 * @deprecated since 2.4
1165 function add_mod_to_section($mod, $beforemod = null) {
1166 throw new coding_exception('Function add_mod_to_section() is removed, please use course_add_cm_to_section()');
1170 * Returns a number of useful structures for course displays
1172 * Function get_all_mods() is deprecated in 2.4
1173 * Instead of:
1174 * <code>
1175 * get_all_mods($courseid, $mods, $modnames, $modnamesplural, $modnamesused);
1176 * </code>
1177 * please use:
1178 * <code>
1179 * $mods = get_fast_modinfo($courseorid)->get_cms();
1180 * $modnames = get_module_types_names();
1181 * $modnamesplural = get_module_types_names(true);
1182 * $modnamesused = get_fast_modinfo($courseorid)->get_used_module_names();
1183 * </code>
1185 * @deprecated since 2.4
1187 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1188 throw new coding_exception('Function get_all_mods() is removed. Use get_fast_modinfo() and get_module_types_names() instead. See phpdocs for details');
1192 * Returns course section - creates new if does not exist yet
1194 * This function is deprecated. To create a course section call:
1195 * course_create_sections_if_missing($courseorid, $sections);
1196 * to get the section call:
1197 * get_fast_modinfo($courseorid)->get_section_info($sectionnum);
1199 * @see course_create_sections_if_missing()
1200 * @see get_fast_modinfo()
1201 * @deprecated since 2.4
1203 function get_course_section($section, $courseid) {
1204 throw new coding_exception('Function get_course_section() is removed. Please use course_create_sections_if_missing() and get_fast_modinfo() instead.');
1208 * @deprecated since 2.4
1209 * @see format_weeks::get_section_dates()
1211 function format_weeks_get_section_dates($section, $course) {
1212 throw new coding_exception('Function format_weeks_get_section_dates() is removed. It is not recommended to'.
1213 ' use it outside of format_weeks plugin');
1217 * Deprecated. Instead of:
1218 * list($content, $name) = get_print_section_cm_text($cm, $course);
1219 * use:
1220 * $content = $cm->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
1221 * $name = $cm->get_formatted_name();
1223 * @deprecated since 2.5
1224 * @see cm_info::get_formatted_content()
1225 * @see cm_info::get_formatted_name()
1227 function get_print_section_cm_text(cm_info $cm, $course) {
1228 throw new coding_exception('Function get_print_section_cm_text() is removed. Please use '.
1229 'cm_info::get_formatted_content() and cm_info::get_formatted_name()');
1233 * Deprecated. Please use:
1234 * $courserenderer = $PAGE->get_renderer('core', 'course');
1235 * $output = $courserenderer->course_section_add_cm_control($course, $section, $sectionreturn,
1236 * array('inblock' => $vertical));
1237 * echo $output;
1239 * @deprecated since 2.5
1240 * @see core_course_renderer::course_section_add_cm_control()
1242 function print_section_add_menus($course, $section, $modnames = null, $vertical=false, $return=false, $sectionreturn=null) {
1243 throw new coding_exception('Function print_section_add_menus() is removed. Please use course renderer '.
1244 'function course_section_add_cm_control()');
1248 * Deprecated. Please use:
1249 * $courserenderer = $PAGE->get_renderer('core', 'course');
1250 * $actions = course_get_cm_edit_actions($mod, $indent, $section);
1251 * return ' ' . $courserenderer->course_section_cm_edit_actions($actions);
1253 * @deprecated since 2.5
1254 * @see course_get_cm_edit_actions()
1255 * @see core_course_renderer->course_section_cm_edit_actions()
1257 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=null) {
1258 throw new coding_exception('Function make_editing_buttons() is removed, please see PHPdocs in '.
1259 'lib/deprecatedlib.php on how to replace it');
1263 * Deprecated. Please use:
1264 * $courserenderer = $PAGE->get_renderer('core', 'course');
1265 * echo $courserenderer->course_section_cm_list($course, $section, $sectionreturn,
1266 * array('hidecompletion' => $hidecompletion));
1268 * @deprecated since 2.5
1269 * @see core_course_renderer::course_section_cm_list()
1271 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false, $sectionreturn=null) {
1272 throw new coding_exception('Function print_section() is removed. Please use course renderer function '.
1273 'course_section_cm_list() instead.');
1277 * @deprecated since 2.5
1279 function print_overview($courses, array $remote_courses=array()) {
1280 throw new coding_exception('Function print_overview() is removed. Use block course_overview to display this information');
1284 * @deprecated since 2.5
1286 function print_recent_activity($course) {
1287 throw new coding_exception('Function print_recent_activity() is removed. It is not recommended to'.
1288 ' use it outside of block_recent_activity');
1292 * @deprecated since 2.5
1294 function delete_course_module($id) {
1295 throw new coding_exception('Function delete_course_module() is removed. Please use course_delete_module() instead.');
1299 * @deprecated since 2.5
1301 function update_category_button($categoryid = 0) {
1302 throw new coding_exception('Function update_category_button() is removed. Pages to view '.
1303 'and edit courses are now separate and no longer depend on editing mode.');
1307 * This function is deprecated! For list of categories use
1308 * coursecat::make_all_categories($requiredcapability, $excludeid, $separator)
1309 * For parents of one particular category use
1310 * coursecat::get($id)->get_parents()
1312 * @deprecated since 2.5
1314 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1315 $excludeid = 0, $category = NULL, $path = "") {
1316 throw new coding_exception('Global function make_categories_list() is removed. Please use '.
1317 'coursecat::make_categories_list() and coursecat::get_parents()');
1321 * @deprecated since 2.5
1323 function category_delete_move($category, $newparentid, $showfeedback=true) {
1324 throw new coding_exception('Function category_delete_move() is removed. Please use coursecat::delete_move() instead.');
1328 * @deprecated since 2.5
1330 function category_delete_full($category, $showfeedback=true) {
1331 throw new coding_exception('Function category_delete_full() is removed. Please use coursecat::delete_full() instead.');
1335 * This function is deprecated. Please use
1336 * $coursecat = coursecat::get($category->id);
1337 * if ($coursecat->can_change_parent($newparentcat->id)) {
1338 * $coursecat->change_parent($newparentcat->id);
1341 * Alternatively you can use
1342 * $coursecat->update(array('parent' => $newparentcat->id));
1344 * @see coursecat::change_parent()
1345 * @see coursecat::update()
1346 * @deprecated since 2.5
1348 function move_category($category, $newparentcat) {
1349 throw new coding_exception('Function move_category() is removed. Please use coursecat::change_parent() instead.');
1353 * This function is deprecated. Please use
1354 * coursecat::get($category->id)->hide();
1356 * @see coursecat::hide()
1357 * @deprecated since 2.5
1359 function course_category_hide($category) {
1360 throw new coding_exception('Function course_category_hide() is removed. Please use coursecat::hide() instead.');
1364 * This function is deprecated. Please use
1365 * coursecat::get($category->id)->show();
1367 * @see coursecat::show()
1368 * @deprecated since 2.5
1370 function course_category_show($category) {
1371 throw new coding_exception('Function course_category_show() is removed. Please use coursecat::show() instead.');
1375 * This function is deprecated.
1376 * To get the category with the specified it please use:
1377 * coursecat::get($catid, IGNORE_MISSING);
1378 * or
1379 * coursecat::get($catid, MUST_EXIST);
1381 * To get the first available category please use
1382 * coursecat::get_default();
1384 * @deprecated since 2.5
1386 function get_course_category($catid=0) {
1387 throw new coding_exception('Function get_course_category() is removed. Please use coursecat::get(), see phpdocs for more details');
1391 * This function is deprecated. It is replaced with the method create() in class coursecat.
1392 * {@link coursecat::create()} also verifies the data, fixes sortorder and logs the action
1394 * @deprecated since 2.5
1396 function create_course_category($category) {
1397 throw new coding_exception('Function create_course_category() is removed. Please use coursecat::create(), see phpdocs for more details');
1401 * This function is deprecated.
1403 * To get visible children categories of the given category use:
1404 * coursecat::get($categoryid)->get_children();
1405 * This function will return the array or coursecat objects, on each of them
1406 * you can call get_children() again
1408 * @see coursecat::get()
1409 * @see coursecat::get_children()
1411 * @deprecated since 2.5
1413 function get_all_subcategories($catid) {
1414 throw new coding_exception('Function get_all_subcategories() is removed. Please use appropriate methods() of coursecat
1415 class. See phpdocs for more details');
1419 * This function is deprecated. Please use functions in class coursecat:
1420 * - coursecat::get($parentid)->has_children()
1421 * tells if the category has children (visible or not to the current user)
1423 * - coursecat::get($parentid)->get_children()
1424 * returns an array of coursecat objects, each of them represents a children category visible
1425 * to the current user (i.e. visible=1 or user has capability to view hidden categories)
1427 * - coursecat::get($parentid)->get_children_count()
1428 * returns number of children categories visible to the current user
1430 * - coursecat::count_all()
1431 * returns total count of all categories in the system (both visible and not)
1433 * - coursecat::get_default()
1434 * returns the first category (usually to be used if count_all() == 1)
1436 * @deprecated since 2.5
1438 function get_child_categories($parentid) {
1439 throw new coding_exception('Function get_child_categories() is removed. Use coursecat::get_children() or see phpdocs for
1440 more details.');
1445 * @deprecated since 2.5
1447 * This function is deprecated. Use appropriate functions from class coursecat.
1448 * Examples:
1450 * coursecat::get($categoryid)->get_children()
1451 * - returns all children of the specified category as instances of class
1452 * coursecat, which means on each of them method get_children() can be called again.
1453 * Only categories visible to the current user are returned.
1455 * coursecat::get(0)->get_children()
1456 * - returns all top-level categories visible to the current user.
1458 * Sort fields can be specified, see phpdocs to {@link coursecat::get_children()}
1460 * coursecat::make_categories_list()
1461 * - returns an array of all categories id/names in the system.
1462 * Also only returns categories visible to current user and can additionally be
1463 * filetered by capability, see phpdocs to {@link coursecat::make_categories_list()}
1465 * make_categories_options()
1466 * - Returns full course categories tree to be used in html_writer::select()
1468 * Also see functions {@link coursecat::get_children_count()}, {@link coursecat::count_all()},
1469 * {@link coursecat::get_default()}
1471 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1472 throw new coding_exception('Function get_categories() is removed. Please use coursecat::get_children() or see phpdocs for other alternatives');
1476 * This function is deprecated, please use course renderer:
1477 * $renderer = $PAGE->get_renderer('core', 'course');
1478 * echo $renderer->course_search_form($value, $format);
1480 * @deprecated since 2.5
1482 function print_course_search($value="", $return=false, $format="plain") {
1483 throw new coding_exception('Function print_course_search() is removed, please use course renderer');
1487 * This function is deprecated, please use:
1488 * $renderer = $PAGE->get_renderer('core', 'course');
1489 * echo $renderer->frontpage_my_courses()
1491 * @deprecated since 2.5
1493 function print_my_moodle() {
1494 throw new coding_exception('Function print_my_moodle() is removed, please use course renderer function frontpage_my_courses()');
1498 * This function is deprecated, it is replaced with protected function
1499 * {@link core_course_renderer::frontpage_remote_course()}
1500 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1502 * @deprecated since 2.5
1504 function print_remote_course($course, $width="100%") {
1505 throw new coding_exception('Function print_remote_course() is removed, please use course renderer');
1509 * This function is deprecated, it is replaced with protected function
1510 * {@link core_course_renderer::frontpage_remote_host()}
1511 * It is only used from function {@link core_course_renderer::frontpage_my_courses()}
1513 * @deprecated since 2.5
1515 function print_remote_host($host, $width="100%") {
1516 throw new coding_exception('Function print_remote_host() is removed, please use course renderer');
1520 * @deprecated since 2.5
1522 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1524 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true, $categorycourses=NULL) {
1525 throw new coding_exception('Function print_whole_category_list() is removed, please use course renderer');
1529 * @deprecated since 2.5
1531 function print_category_info($category, $depth = 0, $showcourses = false, array $courses = null) {
1532 throw new coding_exception('Function print_category_info() is removed, please use course renderer');
1536 * @deprecated since 2.5
1538 * This function is not used any more in moodle core and course renderer does not have render function for it.
1539 * Combo list on the front page is displayed as:
1540 * $renderer = $PAGE->get_renderer('core', 'course');
1541 * echo $renderer->frontpage_combo_list()
1543 * The new class {@link coursecat} stores the information about course category tree
1544 * To get children categories use:
1545 * coursecat::get($id)->get_children()
1546 * To get list of courses use:
1547 * coursecat::get($id)->get_courses()
1549 * See http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
1551 function get_course_category_tree($id = 0, $depth = 0) {
1552 throw new coding_exception('Function get_course_category_tree() is removed, please use course renderer or coursecat class,
1553 see function phpdocs for more info');
1557 * @deprecated since 2.5
1559 * To print a generic list of courses use:
1560 * $renderer = $PAGE->get_renderer('core', 'course');
1561 * echo $renderer->courses_list($courses);
1563 * To print list of all courses:
1564 * $renderer = $PAGE->get_renderer('core', 'course');
1565 * echo $renderer->frontpage_available_courses();
1567 * To print list of courses inside category:
1568 * $renderer = $PAGE->get_renderer('core', 'course');
1569 * echo $renderer->course_category($category); // this will also print subcategories
1571 function print_courses($category) {
1572 throw new coding_exception('Function print_courses() is removed, please use course renderer');
1576 * @deprecated since 2.5
1578 * Please use course renderer to display a course information box.
1579 * $renderer = $PAGE->get_renderer('core', 'course');
1580 * echo $renderer->courses_list($courses); // will print list of courses
1581 * echo $renderer->course_info_box($course); // will print one course wrapped in div.generalbox
1583 function print_course($course, $highlightterms = '') {
1584 throw new coding_exception('Function print_course() is removed, please use course renderer');
1588 * @deprecated since 2.5
1590 * This function is not used any more in moodle core and course renderer does not have render function for it.
1591 * Combo list on the front page is displayed as:
1592 * $renderer = $PAGE->get_renderer('core', 'course');
1593 * echo $renderer->frontpage_combo_list()
1595 * The new class {@link coursecat} stores the information about course category tree
1596 * To get children categories use:
1597 * coursecat::get($id)->get_children()
1598 * To get list of courses use:
1599 * coursecat::get($id)->get_courses()
1601 function get_category_courses_array($categoryid = 0) {
1602 throw new coding_exception('Function get_category_courses_array() is removed, please use methods of coursecat class');
1606 * @deprecated since 2.5
1608 function get_category_courses_array_recursively(array &$flattened, $category) {
1609 throw new coding_exception('Function get_category_courses_array_recursively() is removed, please use methods of coursecat class', DEBUG_DEVELOPER);
1613 * @deprecated since Moodle 2.5 MDL-27814 - please do not use this function any more.
1615 function blog_get_context_url($context=null) {
1616 throw new coding_exception('Function blog_get_context_url() is removed, getting params from context is not reliable for blogs.');
1620 * @deprecated since 2.5
1622 * To get list of all courses with course contacts ('managers') use
1623 * coursecat::get(0)->get_courses(array('recursive' => true, 'coursecontacts' => true));
1625 * To get list of courses inside particular category use
1626 * coursecat::get($id)->get_courses(array('coursecontacts' => true));
1628 * Additionally you can specify sort order, offset and maximum number of courses,
1629 * see {@link coursecat::get_courses()}
1631 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
1632 throw new coding_exception('Function get_courses_wmanagers() is removed, please use coursecat::get_courses()');
1636 * @deprecated since 2.5
1638 function convert_tree_to_html($tree, $row=0) {
1639 throw new coding_exception('Function convert_tree_to_html() is removed. Consider using class tabtree and core_renderer::render_tabtree()');
1643 * @deprecated since 2.5
1645 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
1646 throw new coding_exception('Function convert_tabrows_to_tree() is removed. Consider using class tabtree');
1650 * @deprecated since 2.5 - do not use, the textrotate.js will work it out automatically
1652 function can_use_rotated_text() {
1653 debugging('can_use_rotated_text() is removed. JS feature detection is used automatically.');
1657 * @deprecated since Moodle 2.2 MDL-35009 - please do not use this function any more.
1658 * @see context::instance_by_id($id)
1660 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
1661 throw new coding_exception('get_context_instance_by_id() is now removed, please use context::instance_by_id($id) instead.');
1665 * Returns system context or null if can not be created yet.
1667 * @see context_system::instance()
1668 * @deprecated since 2.2
1669 * @param bool $cache use caching
1670 * @return context system context (null if context table not created yet)
1672 function get_system_context($cache = true) {
1673 debugging('get_system_context() is deprecated, please use context_system::instance() instead.', DEBUG_DEVELOPER);
1674 return context_system::instance(0, IGNORE_MISSING, $cache);
1678 * @see context::get_parent_context_ids()
1679 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
1681 function get_parent_contexts(context $context, $includeself = false) {
1682 throw new coding_exception('get_parent_contexts() is removed, please use $context->get_parent_context_ids() instead.');
1686 * @deprecated since Moodle 2.2
1687 * @see context::get_parent_context()
1689 function get_parent_contextid(context $context) {
1690 throw new coding_exception('get_parent_contextid() is removed, please use $context->get_parent_context() instead.');
1694 * @see context::get_child_contexts()
1695 * @deprecated since 2.2
1697 function get_child_contexts(context $context) {
1698 throw new coding_exception('get_child_contexts() is removed, please use $context->get_child_contexts() instead.');
1702 * @see context_helper::create_instances()
1703 * @deprecated since 2.2
1705 function create_contexts($contextlevel = null, $buildpaths = true) {
1706 throw new coding_exception('create_contexts() is removed, please use context_helper::create_instances() instead.');
1710 * @see context_helper::cleanup_instances()
1711 * @deprecated since 2.2
1713 function cleanup_contexts() {
1714 throw new coding_exception('cleanup_contexts() is removed, please use context_helper::cleanup_instances() instead.');
1718 * Populate context.path and context.depth where missing.
1720 * @deprecated since 2.2
1722 function build_context_path($force = false) {
1723 throw new coding_exception('build_context_path() is removed, please use context_helper::build_all_paths() instead.');
1727 * @deprecated since 2.2
1729 function rebuild_contexts(array $fixcontexts) {
1730 throw new coding_exception('rebuild_contexts() is removed, please use $context->reset_paths(true) instead.');
1734 * @deprecated since Moodle 2.2
1735 * @see context_helper::preload_course()
1737 function preload_course_contexts($courseid) {
1738 throw new coding_exception('preload_course_contexts() is removed, please use context_helper::preload_course() instead.');
1742 * @deprecated since Moodle 2.2
1743 * @see context::update_moved()
1745 function context_moved(context $context, context $newparent) {
1746 throw new coding_exception('context_moved() is removed, please use context::update_moved() instead.');
1750 * @see context::get_capabilities()
1751 * @deprecated since 2.2
1753 function fetch_context_capabilities(context $context) {
1754 throw new coding_exception('fetch_context_capabilities() is removed, please use $context->get_capabilities() instead.');
1758 * @deprecated since 2.2
1759 * @see context_helper::preload_from_record()
1761 function context_instance_preload(stdClass $rec) {
1762 throw new coding_exception('context_instance_preload() is removed, please use context_helper::preload_from_record() instead.');
1766 * Returns context level name
1768 * @deprecated since 2.2
1769 * @see context_helper::get_level_name()
1771 function get_contextlevel_name($contextlevel) {
1772 throw new coding_exception('get_contextlevel_name() is removed, please use context_helper::get_level_name() instead.');
1776 * @deprecated since 2.2
1777 * @see context::get_context_name()
1779 function print_context_name(context $context, $withprefix = true, $short = false) {
1780 throw new coding_exception('print_context_name() is removed, please use $context->get_context_name() instead.');
1784 * @deprecated since 2.2, use $context->mark_dirty() instead
1785 * @see context::mark_dirty()
1787 function mark_context_dirty($path) {
1788 throw new coding_exception('mark_context_dirty() is removed, please use $context->mark_dirty() instead.');
1792 * @deprecated since Moodle 2.2
1793 * @see context_helper::delete_instance() or context::delete_content()
1795 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1796 if ($deleterecord) {
1797 throw new coding_exception('delete_context() is removed, please use context_helper::delete_instance() instead.');
1798 } else {
1799 throw new coding_exception('delete_context() is removed, please use $context->delete_content() instead.');
1804 * @deprecated since 2.2
1805 * @see context::get_url()
1807 function get_context_url(context $context) {
1808 throw new coding_exception('get_context_url() is removed, please use $context->get_url() instead.');
1812 * @deprecated since 2.2
1813 * @see context::get_course_context()
1815 function get_course_context(context $context) {
1816 throw new coding_exception('get_course_context() is removed, please use $context->get_course_context(true) instead.');
1820 * @deprecated since 2.2
1821 * @see enrol_get_users_courses()
1823 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1825 throw new coding_exception('get_user_courses_bycap() is removed, please use enrol_get_users_courses() instead.');
1829 * @deprecated since Moodle 2.2
1831 function get_role_context_caps($roleid, context $context) {
1832 throw new coding_exception('get_role_context_caps() is removed, it is really slow. Don\'t use it.');
1836 * @see context::get_course_context()
1837 * @deprecated since 2.2
1839 function get_courseid_from_context(context $context) {
1840 throw new coding_exception('get_courseid_from_context() is removed, please use $context->get_course_context(false) instead.');
1844 * If you are using this methid, you should have something like this:
1846 * list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1848 * To prevent the use of this deprecated function, replace the line above with something similar to this:
1850 * $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1852 * $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1853 * ^ ^ ^ ^
1854 * $params = array('contextlevel' => CONTEXT_COURSE);
1856 * @see context_helper:;get_preload_record_columns_sql()
1857 * @deprecated since 2.2
1859 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
1860 throw new coding_exception('context_instance_preload_sql() is removed, please use context_helper::get_preload_record_columns_sql() instead.');
1864 * @deprecated since 2.2
1865 * @see context::get_parent_context_ids()
1867 function get_related_contexts_string(context $context) {
1868 throw new coding_exception('get_related_contexts_string() is removed, please use $context->get_parent_context_ids(true) instead.');
1872 * @deprecated since 2.6
1873 * @see core_component::get_plugin_list_with_file()
1875 function get_plugin_list_with_file($plugintype, $file, $include = false) {
1876 throw new coding_exception('get_plugin_list_with_file() is removed, please use core_component::get_plugin_list_with_file() instead.');
1880 * @deprecated since 2.6
1882 function check_browser_operating_system($brand) {
1883 throw new coding_exception('check_browser_operating_system is removed, please update your code to use core_useragent instead.');
1887 * @deprecated since 2.6
1889 function check_browser_version($brand, $version = null) {
1890 throw new coding_exception('check_browser_version is removed, please update your code to use core_useragent instead.');
1894 * @deprecated since 2.6
1896 function get_device_type() {
1897 throw new coding_exception('get_device_type is removed, please update your code to use core_useragent instead.');
1901 * @deprecated since 2.6
1903 function get_device_type_list($incusertypes = true) {
1904 throw new coding_exception('get_device_type_list is removed, please update your code to use core_useragent instead.');
1908 * @deprecated since 2.6
1910 function get_selected_theme_for_device_type($devicetype = null) {
1911 throw new coding_exception('get_selected_theme_for_device_type is removed, please update your code to use core_useragent instead.');
1915 * @deprecated since 2.6
1917 function get_device_cfg_var_name($devicetype = null) {
1918 throw new coding_exception('get_device_cfg_var_name is removed, please update your code to use core_useragent instead.');
1922 * @deprecated since 2.6
1924 function set_user_device_type($newdevice) {
1925 throw new coding_exception('set_user_device_type is removed, please update your code to use core_useragent instead.');
1929 * @deprecated since 2.6
1931 function get_user_device_type() {
1932 throw new coding_exception('get_user_device_type is removed, please update your code to use core_useragent instead.');
1936 * @deprecated since 2.6
1938 function get_browser_version_classes() {
1939 throw new coding_exception('get_browser_version_classes is removed, please update your code to use core_useragent instead.');
1943 * @deprecated since Moodle 2.6
1944 * @see core_user::get_support_user()
1946 function generate_email_supportuser() {
1947 throw new coding_exception('generate_email_supportuser is removed, please use core_user::get_support_user');
1951 * @deprecated since Moodle 2.6
1953 function badges_get_issued_badge_info($hash) {
1954 throw new coding_exception('Function badges_get_issued_badge_info() is removed. Please use core_badges_assertion class and methods to generate badge assertion.');
1958 * @deprecated since 2.6
1960 function can_use_html_editor() {
1961 throw new coding_exception('can_use_html_editor is removed, please update your code to assume it returns true.');
1966 * @deprecated since Moodle 2.7, use {@link user_count_login_failures()} instead.
1968 function count_login_failures($mode, $username, $lastlogin) {
1969 throw new coding_exception('count_login_failures() can not be used any more, please use user_count_login_failures().');
1973 * @deprecated since 2.7 MDL-33099/MDL-44088 - please do not use this function any more.
1975 function ajaxenabled(array $browsers = null) {
1976 throw new coding_exception('ajaxenabled() can not be used anymore. Update your code to work with JS at all times.');
1980 * @deprecated Since Moodle 2.7 MDL-44070
1982 function coursemodule_visible_for_user($cm, $userid=0) {
1983 throw new coding_exception('coursemodule_visible_for_user() can not be used any more,
1984 please use \core_availability\info_module::is_user_visible()');
1988 * @deprecated since Moodle 2.8 MDL-36014, MDL-35618 this functionality is removed
1990 function enrol_cohort_get_cohorts(course_enrolment_manager $manager) {
1991 throw new coding_exception('Function enrol_cohort_get_cohorts() is removed, use enrol_cohort_search_cohorts() or '.
1992 'cohort_get_available_cohorts() instead');
1996 * This function is deprecated, use {@link cohort_can_view_cohort()} instead since it also
1997 * takes into account current context
1999 * @deprecated since Moodle 2.8 MDL-36014 please use cohort_can_view_cohort()
2001 function enrol_cohort_can_view_cohort($cohortid) {
2002 throw new coding_exception('Function enrol_cohort_can_view_cohort() is removed, use cohort_can_view_cohort() instead');
2006 * It is advisable to use {@link cohort_get_available_cohorts()} instead.
2008 * @deprecated since Moodle 2.8 MDL-36014 use cohort_get_available_cohorts() instead
2010 function cohort_get_visible_list($course, $onlyenrolled=true) {
2011 throw new coding_exception('Function cohort_get_visible_list() is removed. Please use function cohort_get_available_cohorts() ".
2012 "that correctly checks capabilities.');
2016 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2018 function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohortid, $roleid) {
2019 throw new coding_exception('enrol_cohort_enrol_all_users() is removed. This functionality is moved to enrol_manual.');
2023 * @deprecated since Moodle 2.8 MDL-35618 this functionality is removed
2025 function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '') {
2026 throw new coding_exception('enrol_cohort_search_cohorts() is removed. This functionality is moved to enrol_manual.');
2029 /* === Apis deprecated in since Moodle 2.9 === */
2032 * Is $USER one of the supplied users?
2034 * $user2 will be null if viewing a user's recent conversations
2036 * @deprecated since Moodle 2.9 MDL-49371 - please do not use this function any more.
2038 function message_current_user_is_involved($user1, $user2) {
2039 throw new coding_exception('message_current_user_is_involved() can not be used any more.');
2043 * Print badges on user profile page.
2045 * @deprecated since Moodle 2.9 MDL-45898 - please do not use this function any more.
2047 function profile_display_badges($userid, $courseid = 0) {
2048 throw new coding_exception('profile_display_badges() can not be used any more.');
2052 * Adds user preferences elements to user edit form.
2054 * @deprecated since Moodle 2.9 MDL-45774 - Please do not use this function any more.
2056 function useredit_shared_definition_preferences($user, &$mform, $editoroptions = null, $filemanageroptions = null) {
2057 throw new coding_exception('useredit_shared_definition_preferences() can not be used any more.');
2062 * Convert region timezone to php supported timezone
2064 * @deprecated since Moodle 2.9
2066 function calendar_normalize_tz($tz) {
2067 throw new coding_exception('calendar_normalize_tz() can not be used any more, please use core_date::normalise_timezone() instead.');
2071 * Returns a float which represents the user's timezone difference from GMT in hours
2072 * Checks various settings and picks the most dominant of those which have a value
2073 * @deprecated since Moodle 2.9
2075 function get_user_timezone_offset($tz = 99) {
2076 throw new coding_exception('get_user_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2081 * Returns an int which represents the systems's timezone difference from GMT in seconds
2082 * @deprecated since Moodle 2.9
2084 function get_timezone_offset($tz) {
2085 throw new coding_exception('get_timezone_offset() can not be used any more, please use standard PHP DateTimeZone class instead');
2089 * Returns a list of timezones in the current language.
2090 * @deprecated since Moodle 2.9
2092 function get_list_of_timezones() {
2093 throw new coding_exception('get_list_of_timezones() can not be used any more, please use core_date::get_list_of_timezones() instead');
2097 * Previous internal API, it was not supposed to be used anywhere.
2098 * @deprecated since Moodle 2.9
2100 function update_timezone_records($timezones) {
2101 throw new coding_exception('update_timezone_records() can not be used any more, please use standard PHP DateTime class instead');
2105 * Previous internal API, it was not supposed to be used anywhere.
2106 * @deprecated since Moodle 2.9
2108 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2109 throw new coding_exception('calculate_user_dst_table() can not be used any more, please use standard PHP DateTime class instead');
2113 * Previous internal API, it was not supposed to be used anywhere.
2114 * @deprecated since Moodle 2.9
2116 function dst_changes_for_year($year, $timezone) {
2117 throw new coding_exception('dst_changes_for_year() can not be used any more, please use standard DateTime class instead');
2121 * Previous internal API, it was not supposed to be used anywhere.
2122 * @deprecated since Moodle 2.9
2124 function get_timezone_record($timezonename) {
2125 throw new coding_exception('get_timezone_record() can not be used any more, please use standard PHP DateTime class instead');
2128 /* === Apis deprecated since Moodle 3.0 === */
2130 * @deprecated since Moodle 3.0 MDL-49360 - please do not use this function any more.
2132 function get_referer($stripquery = true) {
2133 throw new coding_exception('get_referer() can not be used any more. Please use get_local_referer() instead.');
2137 * @deprecated since Moodle 3.0 use \core_useragent::is_web_crawler instead.
2139 function is_web_crawler() {
2140 throw new coding_exception('is_web_crawler() can not be used any more. Please use core_useragent::is_web_crawler() instead.');
2144 * @deprecated since Moodle 3.0 MDL-50287 - please do not use this function any more.
2146 function completion_cron() {
2147 throw new coding_exception('completion_cron() can not be used any more. Functionality has been moved to scheduled tasks.');
2151 * @deprecated since 3.0
2153 function coursetag_get_tags($courseid, $userid=0, $tagtype='', $numtags=0, $unused = '') {
2154 throw new coding_exception('Function coursetag_get_tags() can not be used any more. Userid is no longer used for tagging courses.');
2158 * @deprecated since 3.0
2160 function coursetag_get_all_tags($unused='', $numtags=0) {
2161 throw new coding_exception('Function coursetag_get_all_tag() can not be used any more. Userid is no longer used for tagging courses.');
2165 * @deprecated since 3.0
2167 function coursetag_get_jscript() {
2168 throw new coding_exception('Function coursetag_get_jscript() can not be used any more and is obsolete.');
2172 * @deprecated since 3.0
2174 function coursetag_get_jscript_links($elementid, $coursetagslinks) {
2175 throw new coding_exception('Function coursetag_get_jscript_links() can not be used any more and is obsolete.');
2179 * @deprecated since 3.0
2181 function coursetag_get_records($courseid, $userid) {
2182 throw new coding_exception('Function coursetag_get_records() can not be used any more. Userid is no longer used for tagging courses.');
2186 * @deprecated since 3.0
2188 function coursetag_store_keywords($tags, $courseid, $userid=0, $tagtype='official', $myurl='') {
2189 throw new coding_exception('Function coursetag_store_keywords() can not be used any more. Userid is no longer used for tagging courses.');
2193 * @deprecated since 3.0
2195 function coursetag_delete_keyword($tagid, $userid, $courseid) {
2196 throw new coding_exception('Function coursetag_delete_keyword() can not be used any more. Userid is no longer used for tagging courses.');
2200 * @deprecated since 3.0
2202 function coursetag_get_tagged_courses($tagid) {
2203 throw new coding_exception('Function coursetag_get_tagged_courses() can not be used any more. Userid is no longer used for tagging courses.');
2207 * @deprecated since 3.0
2209 function coursetag_delete_course_tags($courseid, $showfeedback=false) {
2210 throw new coding_exception('Function coursetag_delete_course_tags() is deprecated. Use core_tag_tag::remove_all_item_tags().');
2214 * Set the type of a tag. At this time (version 2.2) the possible values are 'default' or 'official'. Official tags will be
2215 * displayed separately "at tagging time" (while selecting the tags to apply to a record).
2217 * @package core_tag
2218 * @deprecated since 3.1
2219 * @param string $tagid tagid to modify
2220 * @param string $type either 'default' or 'official'
2221 * @return bool true on success, false otherwise
2223 function tag_type_set($tagid, $type) {
2224 debugging('Function tag_type_set() is deprecated and can be replaced with use core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2225 if ($tag = core_tag_tag::get($tagid, '*')) {
2226 return $tag->update(array('isstandard' => ($type === 'official') ? 1 : 0));
2228 return false;
2232 * Set the description of a tag
2234 * @package core_tag
2235 * @deprecated since 3.1
2236 * @param int $tagid the id of the tag
2237 * @param string $description the tag's description string to be set
2238 * @param int $descriptionformat the moodle text format of the description
2239 * {@link http://docs.moodle.org/dev/Text_formats_2.0#Database_structure}
2240 * @return bool true on success, false otherwise
2242 function tag_description_set($tagid, $description, $descriptionformat) {
2243 debugging('Function tag_type_set() is deprecated and can be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2244 if ($tag = core_tag_tag::get($tagid, '*')) {
2245 return $tag->update(array('description' => $description, 'descriptionformat' => $descriptionformat));
2247 return false;
2251 * Get the array of db record of tags associated to a record (instances).
2253 * @package core_tag
2254 * @deprecated since 3.1
2255 * @param string $record_type the record type for which we want to get the tags
2256 * @param int $record_id the record id for which we want to get the tags
2257 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2258 * @param int $userid (optional) only required for course tagging
2259 * @return array the array of tags
2261 function tag_get_tags($record_type, $record_id, $type=null, $userid=0) {
2262 debugging('Method tag_get_tags() is deprecated and replaced with core_tag_tag::get_item_tags(). ' .
2263 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2264 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2265 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2266 $tags = core_tag_tag::get_item_tags(null, $record_type, $record_id, $standardonly, $userid);
2267 $rv = array();
2268 foreach ($tags as $id => $t) {
2269 $rv[$id] = $t->to_object();
2271 return $rv;
2275 * Get the array of tags display names, indexed by id.
2277 * @package core_tag
2278 * @deprecated since 3.1
2279 * @param string $record_type the record type for which we want to get the tags
2280 * @param int $record_id the record id for which we want to get the tags
2281 * @param string $type the tag type (either 'default' or 'official'). By default, all tags are returned.
2282 * @return array the array of tags (with the value returned by core_tag_tag::make_display_name), indexed by id
2284 function tag_get_tags_array($record_type, $record_id, $type=null) {
2285 debugging('Method tag_get_tags_array() is deprecated and replaced with core_tag_tag::get_item_tags_array(). ' .
2286 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2287 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2288 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2289 return core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly);
2293 * Get a comma-separated string of tags associated to a record.
2295 * Use {@link tag_get_tags()} to get the same information in an array.
2297 * @package core_tag
2298 * @deprecated since 3.1
2299 * @param string $record_type the record type for which we want to get the tags
2300 * @param int $record_id the record id for which we want to get the tags
2301 * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired
2302 * @param string $type either 'official' or 'default', if null, all tags are returned
2303 * @return string the comma-separated list of tags.
2305 function tag_get_tags_csv($record_type, $record_id, $html=null, $type=null) {
2306 global $CFG, $OUTPUT;
2307 debugging('Method tag_get_tags_csv() is deprecated. Instead you should use either ' .
2308 'core_tag_tag::get_item_tags_array() or $OUTPUT->tag_list(core_tag_tag::get_item_tags()). ' .
2309 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2310 $standardonly = ($type === 'official' ? core_tag_tag::STANDARD_ONLY :
2311 (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT));
2312 if ($html != TAG_RETURN_TEXT) {
2313 return $OUTPUT->tag_list(core_tag_tag::get_item_tags('', $record_type, $record_id, $standardonly), '');
2314 } else {
2315 return join(', ', core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly, 0, false));
2320 * Get an array of tag ids associated to a record.
2322 * @package core_tag
2323 * @deprecated since 3.1
2324 * @param string $record_type the record type for which we want to get the tags
2325 * @param int $record_id the record id for which we want to get the tags
2326 * @return array tag ids, indexed and sorted by 'ordering'
2328 function tag_get_tags_ids($record_type, $record_id) {
2329 debugging('Method tag_get_tags_ids() is deprecated. Please consider using core_tag_tag::get_item_tags() or similar methods.', DEBUG_DEVELOPER);
2330 $tag_ids = array();
2331 $tagobjects = core_tag_tag::get_item_tags(null, $record_type, $record_id);
2332 foreach ($tagobjects as $tagobject) {
2333 $tag = $tagobject->to_object();
2334 if ( array_key_exists($tag->ordering, $tag_ids) ) {
2335 $tag->ordering++;
2337 $tag_ids[$tag->ordering] = $tag->id;
2339 ksort($tag_ids);
2340 return $tag_ids;
2344 * Returns the database ID of a set of tags.
2346 * @deprecated since 3.1
2347 * @param mixed $tags one tag, or array of tags, to look for.
2348 * @param bool $return_value specify the type of the returned value. Either TAG_RETURN_OBJECT, or TAG_RETURN_ARRAY (default).
2349 * If TAG_RETURN_ARRAY is specified, an array will be returned even if only one tag was passed in $tags.
2350 * @return mixed tag-indexed array of ids (or objects, if second parameter is TAG_RETURN_OBJECT), or only an int, if only one tag
2351 * is given *and* the second parameter is null. No value for a key means the tag wasn't found.
2353 function tag_get_id($tags, $return_value = null) {
2354 global $CFG, $DB;
2355 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(). ' .
2356 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2358 if (!is_array($tags)) {
2359 if(is_null($return_value) || $return_value == TAG_RETURN_OBJECT) {
2360 if ($tagobject = core_tag_tag::get_by_name(core_tag_collection::get_default(), $tags)) {
2361 return $tagobject->id;
2362 } else {
2363 return 0;
2366 $tags = array($tags);
2369 $records = core_tag_tag::get_by_name_bulk(core_tag_collection::get_default(), $tags,
2370 $return_value == TAG_RETURN_OBJECT ? '*' : 'id, name');
2371 foreach ($records as $name => $record) {
2372 if ($return_value != TAG_RETURN_OBJECT) {
2373 $records[$name] = $record->id ? $record->id : null;
2374 } else {
2375 $records[$name] = $record->to_object();
2378 return $records;
2382 * Change the "value" of a tag, and update the associated 'name'.
2384 * @package core_tag
2385 * @deprecated since 3.1
2386 * @param int $tagid the id of the tag to modify
2387 * @param string $newrawname the new rawname
2388 * @return bool true on success, false otherwise
2390 function tag_rename($tagid, $newrawname) {
2391 debugging('Function tag_rename() is deprecated and may be replaced with core_tag_tag::get($tagid)->update().', DEBUG_DEVELOPER);
2392 if ($tag = core_tag_tag::get($tagid, '*')) {
2393 return $tag->update(array('rawname' => $newrawname));
2395 return false;
2399 * Delete one instance of a tag. If the last instance was deleted, it will also delete the tag, unless its type is 'official'.
2401 * @package core_tag
2402 * @deprecated since 3.1
2403 * @param string $record_type the type of the record for which to remove the instance
2404 * @param int $record_id the id of the record for which to remove the instance
2405 * @param int $tagid the tagid that needs to be removed
2406 * @param int $userid (optional) the userid
2407 * @return bool true on success, false otherwise
2409 function tag_delete_instance($record_type, $record_id, $tagid, $userid = null) {
2410 debugging('Function tag_delete_instance() is deprecated and replaced with core_tag_tag::remove_item_tag() instead. ' .
2411 'Component is required for retrieving instances', DEBUG_DEVELOPER);
2412 $tag = core_tag_tag::get($tagid);
2413 core_tag_tag::remove_item_tag('', $record_type, $record_id, $tag->rawname, $userid);
2417 * Find all records tagged with a tag of a given type ('post', 'user', etc.)
2419 * @package core_tag
2420 * @deprecated since 3.1
2421 * @category tag
2422 * @param string $tag tag to look for
2423 * @param string $type type to restrict search to. If null, every matching record will be returned
2424 * @param int $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
2425 * @param int $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
2426 * @return array of matching objects, indexed by record id, from the table containing the type requested
2428 function tag_find_records($tag, $type, $limitfrom='', $limitnum='') {
2429 debugging('Function tag_find_records() is deprecated and replaced with core_tag_tag::get_by_name()->get_tagged_items(). '.
2430 'You need to specify tag collection when retrieving tag by name', DEBUG_DEVELOPER);
2432 if (!$tag || !$type) {
2433 return array();
2436 $tagobject = core_tag_tag::get_by_name(core_tag_area::get_collection('', $type), $tag);
2437 return $tagobject->get_tagged_items('', $type, $limitfrom, $limitnum);
2441 * Adds one or more tag in the database. This function should not be called directly : you should
2442 * use tag_set.
2444 * @package core_tag
2445 * @deprecated since 3.1
2446 * @param mixed $tags one tag, or an array of tags, to be created
2447 * @param string $type type of tag to be created ("default" is the default value and "official" is the only other supported
2448 * value at this time). An official tag is kept even if there are no records tagged with it.
2449 * @return array $tags ids indexed by their lowercase normalized names. Any boolean false in the array indicates an error while
2450 * adding the tag.
2452 function tag_add($tags, $type="default") {
2453 debugging('Function tag_add() is deprecated. You can use core_tag_tag::create_if_missing(), however it should not be necessary ' .
2454 'since tags are created automatically when assigned to items', DEBUG_DEVELOPER);
2455 if (!is_array($tags)) {
2456 $tags = array($tags);
2458 $objects = core_tag_tag::create_if_missing(core_tag_collection::get_default(), $tags,
2459 $type === 'official');
2461 // New function returns the tags in different format, for BC we keep the format that this function used to have.
2462 $rv = array();
2463 foreach ($objects as $name => $tagobject) {
2464 if (isset($tagobject->id)) {
2465 $rv[$tagobject->name] = $tagobject->id;
2466 } else {
2467 $rv[$name] = false;
2470 return $rv;
2474 * Assigns a tag to a record; if the record already exists, the time and ordering will be updated.
2476 * @package core_tag
2477 * @deprecated since 3.1
2478 * @param string $record_type the type of the record that will be tagged
2479 * @param int $record_id the id of the record that will be tagged
2480 * @param string $tagid the tag id to set on the record.
2481 * @param int $ordering the order of the instance for this record
2482 * @param int $userid (optional) only required for course tagging
2483 * @param string|null $component the component that was tagged
2484 * @param int|null $contextid the context id of where this tag was assigned
2485 * @return bool true on success, false otherwise
2487 function tag_assign($record_type, $record_id, $tagid, $ordering, $userid = 0, $component = null, $contextid = null) {
2488 global $DB;
2489 $message = 'Function tag_assign() is deprecated. Use core_tag_tag::set_item_tags() or core_tag_tag::add_item_tag() instead. ' .
2490 'Tag instance ordering should not be set manually';
2491 if ($component === null || $contextid === null) {
2492 $message .= '. You should specify the component and contextid of the item being tagged in your call to tag_assign.';
2494 debugging($message, DEBUG_DEVELOPER);
2496 if ($contextid) {
2497 $context = context::instance_by_id($contextid);
2498 } else {
2499 $context = context_system::instance();
2502 // Get the tag.
2503 $tag = $DB->get_record('tag', array('id' => $tagid), 'name, rawname', MUST_EXIST);
2505 $taginstanceid = core_tag_tag::add_item_tag($component, $record_type, $record_id, $context, $tag->rawname, $userid);
2507 // Alter the "ordering" of tag_instance. This should never be done manually and only remains here for the backward compatibility.
2508 $taginstance = new stdClass();
2509 $taginstance->id = $taginstanceid;
2510 $taginstance->ordering = $ordering;
2511 $taginstance->timemodified = time();
2513 $DB->update_record('tag_instance', $taginstance);
2515 return true;
2519 * Count how many records are tagged with a specific tag.
2521 * @package core_tag
2522 * @deprecated since 3.1
2523 * @param string $record_type record to look for ('post', 'user', etc.)
2524 * @param int $tagid is a single tag id
2525 * @return int number of mathing tags.
2527 function tag_record_count($record_type, $tagid) {
2528 debugging('Method tag_record_count() is deprecated and replaced with core_tag_tag::get($tagid)->count_tagged_items(). '.
2529 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2530 return core_tag_tag::get($tagid)->count_tagged_items('', $record_type);
2534 * Determine if a record is tagged with a specific tag
2536 * @package core_tag
2537 * @deprecated since 3.1
2538 * @param string $record_type the record type to look for
2539 * @param int $record_id the record id to look for
2540 * @param string $tag a tag name
2541 * @return bool/int true if it is tagged, 0 (false) otherwise
2543 function tag_record_tagged_with($record_type, $record_id, $tag) {
2544 debugging('Method tag_record_tagged_with() is deprecated and replaced with core_tag_tag::get($tagid)->is_item_tagged_with(). '.
2545 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER);
2546 return core_tag_tag::is_item_tagged_with('', $record_type, $record_id, $tag);
2550 * Flag a tag as inappropriate.
2552 * @deprecated since 3.1
2553 * @param int|array $tagids a single tagid, or an array of tagids
2555 function tag_set_flag($tagids) {
2556 debugging('Function tag_set_flag() is deprecated and replaced with core_tag_tag::get($tagid)->flag().', DEBUG_DEVELOPER);
2557 $tagids = (array) $tagids;
2558 foreach ($tagids as $tagid) {
2559 if ($tag = core_tag_tag::get($tagid, '*')) {
2560 $tag->flag();
2566 * Remove the inappropriate flag on a tag.
2568 * @deprecated since 3.1
2569 * @param int|array $tagids a single tagid, or an array of tagids
2571 function tag_unset_flag($tagids) {
2572 debugging('Function tag_unset_flag() is deprecated and replaced with core_tag_tag::get($tagid)->reset_flag().', DEBUG_DEVELOPER);
2573 $tagids = (array) $tagids;
2574 foreach ($tagids as $tagid) {
2575 if ($tag = core_tag_tag::get($tagid, '*')) {
2576 $tag->reset_flag();
2582 * Prints or returns a HTML tag cloud with varying classes styles depending on the popularity and type of each tag.
2584 * @deprecated since 3.1
2586 * @param array $tagset Array of tags to display
2587 * @param int $nr_of_tags Limit for the number of tags to return/display, used if $tagset is null
2588 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2589 * @param string $sort (optional) selected sorting, default is alpha sort (name) also timemodified or popularity
2590 * @return string|null a HTML string or null if this function does the output
2592 function tag_print_cloud($tagset=null, $nr_of_tags=150, $return=false, $sort='') {
2593 global $OUTPUT;
2595 debugging('Function tag_print_cloud() is deprecated and replaced with function core_tag_collection::get_tag_cloud(), '
2596 . 'templateable core_tag\output\tagcloud and template core_tag/tagcloud.', DEBUG_DEVELOPER);
2598 // Set up sort global - used to pass sort type into core_tag_collection::cloud_sort through usort() avoiding multiple sort functions.
2599 if ($sort == 'popularity') {
2600 $sort = 'count';
2601 } else if ($sort == 'date') {
2602 $sort = 'timemodified';
2603 } else {
2604 $sort = 'name';
2607 if (is_null($tagset)) {
2608 // No tag set received, so fetch tags from database.
2609 // Always add query by tagcollid even when it's not known to make use of the table index.
2610 $tagcloud = core_tag_collection::get_tag_cloud(0, false, $nr_of_tags, $sort);
2611 } else {
2612 $tagsincloud = $tagset;
2614 $etags = array();
2615 foreach ($tagsincloud as $tag) {
2616 $etags[] = $tag;
2619 core_tag_collection::$cloudsortfield = $sort;
2620 usort($tagsincloud, "core_tag_collection::cloud_sort");
2622 $tagcloud = new \core_tag\output\tagcloud($tagsincloud);
2625 $output = $OUTPUT->render_from_template('core_tag/tagcloud', $tagcloud->export_for_template($OUTPUT));
2626 if ($return) {
2627 return $output;
2628 } else {
2629 echo $output;
2634 * Function that returns tags that start with some text, for use by the autocomplete feature
2636 * @package core_tag
2637 * @deprecated since 3.0
2638 * @access private
2639 * @param string $text string that the tag names will be matched against
2640 * @return mixed an array of objects, or false if no records were found or an error occured.
2642 function tag_autocomplete($text) {
2643 debugging('Function tag_autocomplete() is deprecated without replacement. ' .
2644 'New form element "tags" does proper autocomplete.', DEBUG_DEVELOPER);
2645 global $DB;
2646 return $DB->get_records_sql("SELECT tg.id, tg.name, tg.rawname
2647 FROM {tag} tg
2648 WHERE tg.name LIKE ?", array(core_text::strtolower($text)."%"));
2652 * Prints a box with the description of a tag and its related tags
2654 * @package core_tag
2655 * @deprecated since 3.1
2656 * @param stdClass $tag_object
2657 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2658 * @return string/null a HTML box showing a description of the tag object and it's relationsips or null if output is done directly
2659 * in the function.
2661 function tag_print_description_box($tag_object, $return=false) {
2662 global $USER, $CFG, $OUTPUT;
2663 require_once($CFG->libdir.'/filelib.php');
2665 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2666 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2668 $relatedtags = array();
2669 if ($tag = core_tag_tag::get($tag_object->id)) {
2670 $relatedtags = $tag->get_related_tags();
2673 $content = !empty($tag_object->description);
2674 $output = '';
2676 if ($content) {
2677 $output .= $OUTPUT->box_start('generalbox tag-description');
2680 if (!empty($tag_object->description)) {
2681 $options = new stdClass();
2682 $options->para = false;
2683 $options->overflowdiv = true;
2684 $tag_object->description = file_rewrite_pluginfile_urls($tag_object->description, 'pluginfile.php', context_system::instance()->id, 'tag', 'description', $tag_object->id);
2685 $output .= format_text($tag_object->description, $tag_object->descriptionformat, $options);
2688 if ($content) {
2689 $output .= $OUTPUT->box_end();
2692 if ($relatedtags) {
2693 $output .= $OUTPUT->tag_list($relatedtags, get_string('relatedtags', 'tag'), 'tag-relatedtags');
2696 if ($return) {
2697 return $output;
2698 } else {
2699 echo $output;
2704 * Prints a box that contains the management links of a tag
2706 * @deprecated since 3.1
2707 * @param core_tag_tag|stdClass $tag_object
2708 * @param bool $return if true the function will return the generated tag cloud instead of displaying it.
2709 * @return string|null a HTML string or null if this function does the output
2711 function tag_print_management_box($tag_object, $return=false) {
2712 global $USER, $CFG, $OUTPUT;
2714 debugging('Function tag_print_description_box() is deprecated without replacement. ' .
2715 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2717 $tagname = core_tag_tag::make_display_name($tag_object);
2718 $output = '';
2720 if (!isguestuser()) {
2721 $output .= $OUTPUT->box_start('box','tag-management-box');
2722 $systemcontext = context_system::instance();
2723 $links = array();
2725 // Add a link for users to add/remove this from their interests
2726 if (core_tag_tag::is_enabled('core', 'user') && core_tag_area::get_collection('core', 'user') == $tag_object->tagcollid) {
2727 if (core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $tag_object->name)) {
2728 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=removeinterest&amp;sesskey='. sesskey() .
2729 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
2730 get_string('removetagfrommyinterests', 'tag', $tagname) .'</a>';
2731 } else {
2732 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=addinterest&amp;sesskey='. sesskey() .
2733 '&amp;tag='. rawurlencode($tag_object->name) .'">'.
2734 get_string('addtagtomyinterests', 'tag', $tagname) .'</a>';
2738 // Flag as inappropriate link. Only people with moodle/tag:flag capability.
2739 if (has_capability('moodle/tag:flag', $systemcontext)) {
2740 $links[] = '<a href="'. $CFG->wwwroot .'/tag/user.php?action=flaginappropriate&amp;sesskey='.
2741 sesskey() . '&amp;id='. $tag_object->id . '">'. get_string('flagasinappropriate',
2742 'tag', rawurlencode($tagname)) .'</a>';
2745 // Edit tag: Only people with moodle/tag:edit capability who either have it as an interest or can manage tags
2746 if (has_capability('moodle/tag:edit', $systemcontext) ||
2747 has_capability('moodle/tag:manage', $systemcontext)) {
2748 $links[] = '<a href="' . $CFG->wwwroot . '/tag/edit.php?id=' . $tag_object->id . '">' .
2749 get_string('edittag', 'tag') . '</a>';
2752 $output .= implode(' | ', $links);
2753 $output .= $OUTPUT->box_end();
2756 if ($return) {
2757 return $output;
2758 } else {
2759 echo $output;
2764 * Prints the tag search box
2766 * @deprecated since 3.1
2767 * @param bool $return if true return html string
2768 * @return string|null a HTML string or null if this function does the output
2770 function tag_print_search_box($return=false) {
2771 global $CFG, $OUTPUT;
2773 debugging('Function tag_print_search_box() is deprecated without replacement. ' .
2774 'See core_tag_renderer for similar code.', DEBUG_DEVELOPER);
2776 $query = optional_param('query', '', PARAM_RAW);
2778 $output = $OUTPUT->box_start('','tag-search-box');
2779 $output .= '<form action="'.$CFG->wwwroot.'/tag/search.php" style="display:inline">';
2780 $output .= '<div>';
2781 $output .= '<label class="accesshide" for="searchform_search">'.get_string('searchtags', 'tag').'</label>';
2782 $output .= '<input id="searchform_search" name="query" type="text" size="40" value="'.s($query).'" />';
2783 $output .= '<button id="searchform_button" type="submit">'. get_string('search', 'tag') .'</button><br />';
2784 $output .= '</div>';
2785 $output .= '</form>';
2786 $output .= $OUTPUT->box_end();
2788 if ($return) {
2789 return $output;
2791 else {
2792 echo $output;
2797 * Prints the tag search results
2799 * @deprecated since 3.1
2800 * @param string $query text that tag names will be matched against
2801 * @param int $page current page
2802 * @param int $perpage nr of users displayed per page
2803 * @param bool $return if true return html string
2804 * @return string|null a HTML string or null if this function does the output
2806 function tag_print_search_results($query, $page, $perpage, $return=false) {
2807 global $CFG, $USER, $OUTPUT;
2809 debugging('Function tag_print_search_results() is deprecated without replacement. ' .
2810 'In /tag/search.php the search results are printed using the core_tag/tagcloud template.', DEBUG_DEVELOPER);
2812 $query = clean_param($query, PARAM_TAG);
2814 $count = count(tag_find_tags($query, false));
2815 $tags = array();
2817 if ( $found_tags = tag_find_tags($query, true, $page * $perpage, $perpage) ) {
2818 $tags = array_values($found_tags);
2821 $baseurl = $CFG->wwwroot.'/tag/search.php?query='. rawurlencode($query);
2822 $output = '';
2824 // link "Add $query to my interests"
2825 $addtaglink = '';
2826 if (core_tag_tag::is_enabled('core', 'user') && !core_tag_tag::is_item_tagged_with('core', 'user', $USER->id, $query)) {
2827 $addtaglink = html_writer::link(new moodle_url('/tag/user.php', array('action' => 'addinterest', 'sesskey' => sesskey(),
2828 'tag' => $query)), get_string('addtagtomyinterests', 'tag', s($query)));
2831 if ( !empty($tags) ) { // there are results to display!!
2832 $output .= $OUTPUT->heading(get_string('searchresultsfor', 'tag', htmlspecialchars($query)) ." : {$count}", 3, 'main');
2834 //print a link "Add $query to my interests"
2835 if (!empty($addtaglink)) {
2836 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2839 $nr_of_lis_per_ul = 6;
2840 $nr_of_uls = ceil( sizeof($tags) / $nr_of_lis_per_ul );
2842 $output .= '<ul id="tag-search-results">';
2843 for($i = 0; $i < $nr_of_uls; $i++) {
2844 foreach (array_slice($tags, $i * $nr_of_lis_per_ul, $nr_of_lis_per_ul) as $tag) {
2845 $output .= '<li>';
2846 $tag_link = html_writer::link(core_tag_tag::make_url($tag->tagcollid, $tag->rawname),
2847 core_tag_tag::make_display_name($tag));
2848 $output .= $tag_link;
2849 $output .= '</li>';
2852 $output .= '</ul>';
2853 $output .= '<div>&nbsp;</div>'; // <-- small layout hack in order to look good in Firefox
2855 $output .= $OUTPUT->paging_bar($count, $page, $perpage, $baseurl);
2857 else { //no results were found!!
2858 $output .= $OUTPUT->heading(get_string('noresultsfor', 'tag', htmlspecialchars($query)), 3, 'main');
2860 //print a link "Add $query to my interests"
2861 if (!empty($addtaglink)) {
2862 $output .= $OUTPUT->box($addtaglink, 'box', 'tag-management-box');
2866 if ($return) {
2867 return $output;
2869 else {
2870 echo $output;
2875 * Prints a table of the users tagged with the tag passed as argument
2877 * @deprecated since 3.1
2878 * @param stdClass $tagobject the tag we wish to return data for
2879 * @param int $limitfrom (optional, required if $limitnum is set) prints users starting at this point.
2880 * @param int $limitnum (optional, required if $limitfrom is set) prints this many users.
2881 * @param bool $return if true return html string
2882 * @return string|null a HTML string or null if this function does the output
2884 function tag_print_tagged_users_table($tagobject, $limitfrom='', $limitnum='', $return=false) {
2886 debugging('Function tag_print_tagged_users_table() is deprecated without replacement. ' .
2887 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2889 //List of users with this tag
2890 $tagobject = core_tag_tag::get($tagobject->id);
2891 $userlist = $tagobject->get_tagged_items('core', 'user', $limitfrom, $limitnum);
2893 $output = tag_print_user_list($userlist, true);
2895 if ($return) {
2896 return $output;
2898 else {
2899 echo $output;
2904 * Prints an individual user box
2906 * @deprecated since 3.1
2907 * @param user_object $user (contains the following fields: id, firstname, lastname and picture)
2908 * @param bool $return if true return html string
2909 * @return string|null a HTML string or null if this function does the output
2911 function tag_print_user_box($user, $return=false) {
2912 global $CFG, $OUTPUT;
2914 debugging('Function tag_print_user_box() is deprecated without replacement. ' .
2915 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2917 $usercontext = context_user::instance($user->id);
2918 $profilelink = '';
2920 if ($usercontext and (has_capability('moodle/user:viewdetails', $usercontext) || has_coursecontact_role($user->id))) {
2921 $profilelink = $CFG->wwwroot .'/user/view.php?id='. $user->id;
2924 $output = $OUTPUT->box_start('user-box', 'user'. $user->id);
2925 $fullname = fullname($user);
2926 $alt = '';
2928 if (!empty($profilelink)) {
2929 $output .= '<a href="'. $profilelink .'">';
2930 $alt = $fullname;
2933 $output .= $OUTPUT->user_picture($user, array('size'=>100));
2934 $output .= '<br />';
2936 if (!empty($profilelink)) {
2937 $output .= '</a>';
2940 //truncate name if it's too big
2941 if (core_text::strlen($fullname) > 26) {
2942 $fullname = core_text::substr($fullname, 0, 26) .'...';
2945 $output .= '<strong>'. $fullname .'</strong>';
2946 $output .= $OUTPUT->box_end();
2948 if ($return) {
2949 return $output;
2951 else {
2952 echo $output;
2957 * Prints a list of users
2959 * @deprecated since 3.1
2960 * @param array $userlist an array of user objects
2961 * @param bool $return if true return html string, otherwise output the result
2962 * @return string|null a HTML string or null if this function does the output
2964 function tag_print_user_list($userlist, $return=false) {
2966 debugging('Function tag_print_user_list() is deprecated without replacement. ' .
2967 'See core_user_renderer for similar code.', DEBUG_DEVELOPER);
2969 $output = '<div><ul class="inline-list">';
2971 foreach ($userlist as $user){
2972 $output .= '<li>'. tag_print_user_box($user, true) ."</li>\n";
2974 $output .= "</ul></div>\n";
2976 if ($return) {
2977 return $output;
2979 else {
2980 echo $output;
2985 * Function that returns the name that should be displayed for a specific tag
2987 * @package core_tag
2988 * @category tag
2989 * @deprecated since 3.1
2990 * @param stdClass|core_tag_tag $tagobject a line out of tag table, as returned by the adobd functions
2991 * @param int $html TAG_RETURN_HTML (default) will return htmlspecialchars encoded string, TAG_RETURN_TEXT will not encode.
2992 * @return string
2994 function tag_display_name($tagobject, $html=TAG_RETURN_HTML) {
2995 debugging('Function tag_display_name() is deprecated. Use core_tag_tag::make_display_name().', DEBUG_DEVELOPER);
2996 if (!isset($tagobject->name)) {
2997 return '';
2999 return core_tag_tag::make_display_name($tagobject, $html != TAG_RETURN_TEXT);
3003 * Function that normalizes a list of tag names.
3005 * @package core_tag
3006 * @deprecated since 3.1
3007 * @param array/string $rawtags array of tags, or a single tag.
3008 * @param int $case case to use for returned value (default: lower case). Either TAG_CASE_LOWER (default) or TAG_CASE_ORIGINAL
3009 * @return array lowercased normalized tags, indexed by the normalized tag, in the same order as the original array.
3010 * (Eg: 'Banana' => 'banana').
3012 function tag_normalize($rawtags, $case = TAG_CASE_LOWER) {
3013 debugging('Function tag_normalize() is deprecated. Use core_tag_tag::normalize().', DEBUG_DEVELOPER);
3015 if ( !is_array($rawtags) ) {
3016 $rawtags = array($rawtags);
3019 return core_tag_tag::normalize($rawtags, $case == TAG_CASE_LOWER);
3023 * Get a comma-separated list of tags related to another tag.
3025 * @package core_tag
3026 * @deprecated since 3.1
3027 * @param array $related_tags the array returned by tag_get_related_tags
3028 * @param int $html either TAG_RETURN_HTML (default) or TAG_RETURN_TEXT : return html links, or just text.
3029 * @return string comma-separated list
3031 function tag_get_related_tags_csv($related_tags, $html=TAG_RETURN_HTML) {
3032 global $OUTPUT;
3033 debugging('Method tag_get_related_tags_csv() is deprecated. Consider '
3034 . 'looping through array or using $OUTPUT->tag_list(core_tag_tag::get_item_tags())',
3035 DEBUG_DEVELOPER);
3036 if ($html != TAG_RETURN_TEXT) {
3037 return $OUTPUT->tag_list($related_tags, '');
3040 $tagsnames = array();
3041 foreach ($related_tags as $tag) {
3042 $tagsnames[] = core_tag_tag::make_display_name($tag, false);
3044 return implode(', ', $tagsnames);
3048 * Used to require that the return value from a function is an array.
3049 * Only used in the deprecated function {@link tag_get_id()}
3050 * @deprecated since 3.1
3052 define('TAG_RETURN_ARRAY', 0);
3054 * Used to require that the return value from a function is an object.
3055 * Only used in the deprecated function {@link tag_get_id()}
3056 * @deprecated since 3.1
3058 define('TAG_RETURN_OBJECT', 1);
3060 * Use to specify that HTML free text 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_TEXT', 2);
3067 * Use to specify that encoded HTML is expected to be returned from a function.
3068 * Only used in deprecated functions {@link tag_get_tags_csv()}, {@link tag_display_name()},
3069 * {@link tag_get_related_tags_csv()}
3070 * @deprecated since 3.1
3072 define('TAG_RETURN_HTML', 3);
3075 * Used to specify that we wish a lowercased string to be returned
3076 * Only used in deprecated function {@link tag_normalize()}
3077 * @deprecated since 3.1
3079 define('TAG_CASE_LOWER', 0);
3081 * Used to specify that we do not wish the case of the returned string to change
3082 * Only used in deprecated function {@link tag_normalize()}
3083 * @deprecated since 3.1
3085 define('TAG_CASE_ORIGINAL', 1);
3088 * Used to specify that we want all related tags returned, no matter how they are related.
3089 * Only used in deprecated function {@link tag_get_related_tags()}
3090 * @deprecated since 3.1
3092 define('TAG_RELATED_ALL', 0);
3094 * Used to specify that we only want back tags that were manually related.
3095 * Only used in deprecated function {@link tag_get_related_tags()}
3096 * @deprecated since 3.1
3098 define('TAG_RELATED_MANUAL', 1);
3100 * Used to specify that we only want back tags where the relationship was automatically correlated.
3101 * Only used in deprecated function {@link tag_get_related_tags()}
3102 * @deprecated since 3.1
3104 define('TAG_RELATED_CORRELATED', 2);
3107 * Set the tags assigned to a record. This overwrites the current tags.
3109 * This function is meant to be fed the string coming up from the user interface, which contains all tags assigned to a record.
3111 * Due to API change $component and $contextid are now required. Instead of
3112 * calling this function you can use {@link core_tag_tag::set_item_tags()} or
3113 * {@link core_tag_tag::set_related_tags()}
3115 * @package core_tag
3116 * @deprecated since 3.1
3117 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, 'tag' for tags, etc.)
3118 * @param int $itemid the id of the record to tag
3119 * @param array $tags the array of tags to set on the record. If given an empty array, all tags will be removed.
3120 * @param string|null $component the component that was tagged
3121 * @param int|null $contextid the context id of where this tag was assigned
3122 * @return bool|null
3124 function tag_set($itemtype, $itemid, $tags, $component = null, $contextid = null) {
3125 debugging('Function tag_set() is deprecated. Use ' .
3126 ' core_tag_tag::set_item_tags() instead', DEBUG_DEVELOPER);
3128 if ($itemtype === 'tag') {
3129 return core_tag_tag::get($itemid, '*', MUST_EXIST)->set_related_tags($tags);
3130 } else {
3131 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3132 return core_tag_tag::set_item_tags($component, $itemtype, $itemid, $context, $tags);
3137 * Adds a tag to a record, without overwriting the current tags.
3139 * This function remains here for backward compatiblity. It is recommended to use
3140 * {@link core_tag_tag::add_item_tag()} or {@link core_tag_tag::add_related_tags()} instead
3142 * @package core_tag
3143 * @deprecated since 3.1
3144 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3145 * @param int $itemid the id of the record to tag
3146 * @param string $tag the tag to add
3147 * @param string|null $component the component that was tagged
3148 * @param int|null $contextid the context id of where this tag was assigned
3149 * @return bool|null
3151 function tag_set_add($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3152 debugging('Function tag_set_add() is deprecated. Use ' .
3153 ' core_tag_tag::add_item_tag() instead', DEBUG_DEVELOPER);
3155 if ($itemtype === 'tag') {
3156 return core_tag_tag::get($itemid, '*', MUST_EXIST)->add_related_tags(array($tag));
3157 } else {
3158 $context = $contextid ? context::instance_by_id($contextid) : context_system::instance();
3159 return core_tag_tag::add_item_tag($component, $itemtype, $itemid, $context, $tag);
3164 * Removes a tag from a record, without overwriting other current tags.
3166 * This function remains here for backward compatiblity. It is recommended to use
3167 * {@link core_tag_tag::remove_item_tag()} instead
3169 * @package core_tag
3170 * @deprecated since 3.1
3171 * @param string $itemtype the type of record to tag ('post' for blogs, 'user' for users, etc.)
3172 * @param int $itemid the id of the record to tag
3173 * @param string $tag the tag to delete
3174 * @param string|null $component the component that was tagged
3175 * @param int|null $contextid the context id of where this tag was assigned
3176 * @return bool|null
3178 function tag_set_delete($itemtype, $itemid, $tag, $component = null, $contextid = null) {
3179 debugging('Function tag_set_delete() is deprecated. Use ' .
3180 ' core_tag_tag::remove_item_tag() instead', DEBUG_DEVELOPER);
3181 return core_tag_tag::remove_item_tag($component, $itemtype, $itemid, $tag);
3185 * Simple function to just return a single tag object when you know the name or something
3187 * See also {@link core_tag_tag::get()} and {@link core_tag_tag::get_by_name()}
3189 * @package core_tag
3190 * @deprecated since 3.1
3191 * @param string $field which field do we use to identify the tag: id, name or rawname
3192 * @param string $value the required value of the aforementioned field
3193 * @param string $returnfields which fields do we want returned. This is a comma seperated string containing any combination of
3194 * 'id', 'name', 'rawname' or '*' to include all fields.
3195 * @return mixed tag object
3197 function tag_get($field, $value, $returnfields='id, name, rawname, tagcollid') {
3198 global $DB;
3199 debugging('Function tag_get() is deprecated. Use ' .
3200 ' core_tag_tag::get() or core_tag_tag::get_by_name()',
3201 DEBUG_DEVELOPER);
3202 if ($field === 'id') {
3203 $tag = core_tag_tag::get((int)$value, $returnfields);
3204 } else if ($field === 'name') {
3205 $tag = core_tag_tag::get_by_name(0, $value, $returnfields);
3206 } else {
3207 $params = array($field => $value);
3208 return $DB->get_record('tag', $params, $returnfields);
3210 if ($tag) {
3211 return $tag->to_object();
3213 return null;
3217 * Returns tags related to a tag
3219 * Related tags of a tag come from two sources:
3220 * - manually added related tags, which are tag_instance entries for that tag
3221 * - correlated tags, which are calculated
3223 * @package core_tag
3224 * @deprecated since 3.1
3225 * @param string $tagid is a single **normalized** tag name or the id of a tag
3226 * @param int $type the function will return either manually (TAG_RELATED_MANUAL) related tags or correlated
3227 * (TAG_RELATED_CORRELATED) tags. Default is TAG_RELATED_ALL, which returns everything.
3228 * @param int $limitnum (optional) return a subset comprising this many records, the default is 10
3229 * @return array an array of tag objects
3231 function tag_get_related_tags($tagid, $type=TAG_RELATED_ALL, $limitnum=10) {
3232 debugging('Method tag_get_related_tags() is deprecated, '
3233 . 'use core_tag_tag::get_correlated_tags(), core_tag_tag::get_related_tags() or '
3234 . 'core_tag_tag::get_manual_related_tags()', DEBUG_DEVELOPER);
3235 $result = array();
3236 if ($tag = core_tag_tag::get($tagid)) {
3237 if ($type == TAG_RELATED_CORRELATED) {
3238 $tags = $tag->get_correlated_tags();
3239 } else if ($type == TAG_RELATED_MANUAL) {
3240 $tags = $tag->get_manual_related_tags();
3241 } else {
3242 $tags = $tag->get_related_tags();
3244 $tags = array_slice($tags, 0, $limitnum);
3245 foreach ($tags as $id => $tag) {
3246 $result[$id] = $tag->to_object();
3249 return $result;
3253 * Delete one or more tag, and all their instances if there are any left.
3255 * @package core_tag
3256 * @deprecated since 3.1
3257 * @param mixed $tagids one tagid (int), or one array of tagids to delete
3258 * @return bool true on success, false otherwise
3260 function tag_delete($tagids) {
3261 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_tags()',
3262 DEBUG_DEVELOPER);
3263 return core_tag_tag::delete_tags($tagids);
3267 * Deletes all the tag instances given a component and an optional contextid.
3269 * @deprecated since 3.1
3270 * @param string $component
3271 * @param int $contextid if null, then we delete all tag instances for the $component
3273 function tag_delete_instances($component, $contextid = null) {
3274 debugging('Method tag_delete() is deprecated, use core_tag_tag::delete_instances()',
3275 DEBUG_DEVELOPER);
3276 core_tag_tag::delete_instances($component, null, $contextid);
3280 * Clean up the tag tables, making sure all tagged object still exists.
3282 * This should normally not be necessary, but in case related tags are not deleted when the tagged record is removed, this should be
3283 * 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
3284 * call: don't run at peak time.
3286 * @package core_tag
3287 * @deprecated since 3.1
3289 function tag_cleanup() {
3290 debugging('Method tag_cleanup() is deprecated, use \core\task\tag_cron_task::cleanup()',
3291 DEBUG_DEVELOPER);
3293 $task = new \core\task\tag_cron_task();
3294 return $task->cleanup();
3298 * This function will delete numerous tag instances efficiently.
3299 * This removes tag instances only. It doesn't check to see if it is the last use of a tag.
3301 * @deprecated since 3.1
3302 * @param array $instances An array of tag instance objects with the addition of the tagname and tagrawname
3303 * (used for recording a delete event).
3305 function tag_bulk_delete_instances($instances) {
3306 debugging('Method tag_bulk_delete_instances() is deprecated, '
3307 . 'use \core\task\tag_cron_task::bulk_delete_instances()',
3308 DEBUG_DEVELOPER);
3310 $task = new \core\task\tag_cron_task();
3311 return $task->bulk_delete_instances($instances);
3315 * Calculates and stores the correlated tags of all tags. The correlations are stored in the 'tag_correlation' table.
3317 * Two tags are correlated if they appear together a lot. Ex.: Users tagged with "computers" will probably also be tagged with "algorithms".
3319 * The rationale for the 'tag_correlation' table is performance. It works as a cache for a potentially heavy load query done at the
3320 * 'tag_instance' table. So, the 'tag_correlation' table stores redundant information derived from the 'tag_instance' table.
3322 * @package core_tag
3323 * @deprecated since 3.1
3324 * @param int $mincorrelation Only tags with more than $mincorrelation correlations will be identified.
3326 function tag_compute_correlations($mincorrelation = 2) {
3327 debugging('Method tag_compute_correlations() is deprecated, '
3328 . 'use \core\task\tag_cron_task::compute_correlations()',
3329 DEBUG_DEVELOPER);
3331 $task = new \core\task\tag_cron_task();
3332 return $task->compute_correlations($mincorrelation);
3336 * This function processes a tag correlation and makes changes in the database as required.
3338 * The tag correlation object needs have both a tagid property and a correlatedtags property that is an array.
3340 * @package core_tag
3341 * @deprecated since 3.1
3342 * @param stdClass $tagcorrelation
3343 * @return int/bool The id of the tag correlation that was just processed or false.
3345 function tag_process_computed_correlation(stdClass $tagcorrelation) {
3346 debugging('Method tag_process_computed_correlation() is deprecated, '
3347 . 'use \core\task\tag_cron_task::process_computed_correlation()',
3348 DEBUG_DEVELOPER);
3350 $task = new \core\task\tag_cron_task();
3351 return $task->process_computed_correlation($tagcorrelation);
3355 * Tasks that should be performed at cron time
3357 * @package core_tag
3358 * @deprecated since 3.1
3360 function tag_cron() {
3361 debugging('Method tag_cron() is deprecated, use \core\task\tag_cron_task::execute()',
3362 DEBUG_DEVELOPER);
3364 $task = new \core\task\tag_cron_task();
3365 $task->execute();
3369 * Search for tags with names that match some text
3371 * @package core_tag
3372 * @deprecated since 3.1
3373 * @param string $text escaped string that the tag names will be matched against
3374 * @param bool $ordered If true, tags are ordered by their popularity. If false, no ordering.
3375 * @param int/string $limitfrom (optional, required if $limitnum is set) return a subset of records, starting at this point.
3376 * @param int/string $limitnum (optional, required if $limitfrom is set) return a subset comprising this many records.
3377 * @param int $tagcollid
3378 * @return array/boolean an array of objects, or false if no records were found or an error occured.
3380 function tag_find_tags($text, $ordered=true, $limitfrom='', $limitnum='', $tagcollid = null) {
3381 debugging('Method tag_find_tags() is deprecated without replacement', DEBUG_DEVELOPER);
3382 global $DB;
3384 $text = core_text::strtolower(clean_param($text, PARAM_TAG));
3386 list($sql, $params) = $DB->get_in_or_equal($tagcollid ? array($tagcollid) :
3387 array_keys(core_tag_collection::get_collections(true)));
3388 array_unshift($params, "%{$text}%");
3390 if ($ordered) {
3391 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid, COUNT(ti.id) AS count
3392 FROM {tag} tg LEFT JOIN {tag_instance} ti ON tg.id = ti.tagid
3393 WHERE tg.name LIKE ? AND tg.tagcollid $sql
3394 GROUP BY tg.id, tg.name, tg.rawname
3395 ORDER BY count DESC";
3396 } else {
3397 $query = "SELECT tg.id, tg.name, tg.rawname, tg.tagcollid
3398 FROM {tag} tg
3399 WHERE tg.name LIKE ? AND tg.tagcollid $sql";
3401 return $DB->get_records_sql($query, $params, $limitfrom , $limitnum);
3405 * Get the name of a tag
3407 * @package core_tag
3408 * @deprecated since 3.1
3409 * @param mixed $tagids the id of the tag, or an array of ids
3410 * @return mixed string name of one tag, or id-indexed array of strings
3412 function tag_get_name($tagids) {
3413 debugging('Method tag_get_name() is deprecated without replacement', DEBUG_DEVELOPER);
3414 global $DB;
3416 if (!is_array($tagids)) {
3417 if ($tag = $DB->get_record('tag', array('id'=>$tagids))) {
3418 return $tag->name;
3420 return false;
3423 $tag_names = array();
3424 foreach($DB->get_records_list('tag', 'id', $tagids) as $tag) {
3425 $tag_names[$tag->id] = $tag->name;
3428 return $tag_names;
3432 * Returns the correlated tags of a tag, retrieved from the tag_correlation table. Make sure cron runs, otherwise the table will be
3433 * empty and this function won't return anything.
3435 * Correlated tags are calculated in cron based on existing tag instances.
3437 * @package core_tag
3438 * @deprecated since 3.1
3439 * @param int $tagid is a single tag id
3440 * @param int $notused this argument is no longer used
3441 * @return array an array of tag objects or an empty if no correlated tags are found
3443 function tag_get_correlated($tagid, $notused = null) {
3444 debugging('Method tag_get_correlated() is deprecated, '
3445 . 'use core_tag_tag::get_correlated_tags()', DEBUG_DEVELOPER);
3446 $result = array();
3447 if ($tag = core_tag_tag::get($tagid)) {
3448 $tags = $tag->get_correlated_tags(true);
3449 // Convert to objects for backward-compatibility.
3450 foreach ($tags as $id => $tag) {
3451 $result[$id] = $tag->to_object();
3454 return $result;
3458 * This function is used by print_tag_cloud, to usort() the tags in the cloud. See php.net/usort for the parameters documentation.
3459 * This was originally in blocks/blog_tags/block_blog_tags.php, named blog_tags_sort().
3461 * @package core_tag
3462 * @deprecated since 3.1
3463 * @param string $a Tag name to compare against $b
3464 * @param string $b Tag name to compare against $a
3465 * @return int The result of the comparison/validation 1, 0 or -1
3467 function tag_cloud_sort($a, $b) {
3468 debugging('Method tag_cloud_sort() is deprecated, similar method can be found in core_tag_collection::cloud_sort()', DEBUG_DEVELOPER);
3469 global $CFG;
3471 if (empty($CFG->tagsort)) {
3472 $tagsort = 'name'; // by default, sort by name
3473 } else {
3474 $tagsort = $CFG->tagsort;
3477 if (is_numeric($a->$tagsort)) {
3478 return ($a->$tagsort == $b->$tagsort) ? 0 : ($a->$tagsort > $b->$tagsort) ? 1 : -1;
3479 } elseif (is_string($a->$tagsort)) {
3480 return strcmp($a->$tagsort, $b->$tagsort);
3481 } else {
3482 return 0;
3487 * Loads the events definitions for the component (from file). If no
3488 * events are defined for the component, we simply return an empty array.
3490 * @access protected To be used from eventslib only
3491 * @deprecated since Moodle 3.1
3492 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3493 * @return array Array of capabilities or empty array if not exists
3495 function events_load_def($component) {
3496 global $CFG;
3497 if ($component === 'unittest') {
3498 $defpath = $CFG->dirroot.'/lib/tests/fixtures/events.php';
3499 } else {
3500 $defpath = core_component::get_component_directory($component).'/db/events.php';
3503 $handlers = array();
3505 if (file_exists($defpath)) {
3506 require($defpath);
3509 // make sure the definitions are valid and complete; tell devs what is wrong
3510 foreach ($handlers as $eventname => $handler) {
3511 if ($eventname === 'reset') {
3512 debugging("'reset' can not be used as event name.");
3513 unset($handlers['reset']);
3514 continue;
3516 if (!is_array($handler)) {
3517 debugging("Handler of '$eventname' must be specified as array'");
3518 unset($handlers[$eventname]);
3519 continue;
3521 if (!isset($handler['handlerfile'])) {
3522 debugging("Handler of '$eventname' must include 'handlerfile' key'");
3523 unset($handlers[$eventname]);
3524 continue;
3526 if (!isset($handler['handlerfunction'])) {
3527 debugging("Handler of '$eventname' must include 'handlerfunction' key'");
3528 unset($handlers[$eventname]);
3529 continue;
3531 if (!isset($handler['schedule'])) {
3532 $handler['schedule'] = 'instant';
3534 if ($handler['schedule'] !== 'instant' and $handler['schedule'] !== 'cron') {
3535 debugging("Handler of '$eventname' must include valid 'schedule' type (instant or cron)'");
3536 unset($handlers[$eventname]);
3537 continue;
3539 if (!isset($handler['internal'])) {
3540 $handler['internal'] = 1;
3542 $handlers[$eventname] = $handler;
3545 return $handlers;
3549 * Puts a handler on queue
3551 * @access protected To be used from eventslib only
3552 * @deprecated since Moodle 3.1
3553 * @param stdClass $handler event handler object from db
3554 * @param stdClass $event event data object
3555 * @param string $errormessage The error message indicating the problem
3556 * @return int id number of new queue handler
3558 function events_queue_handler($handler, $event, $errormessage) {
3559 global $DB;
3561 if ($qhandler = $DB->get_record('events_queue_handlers', array('queuedeventid'=>$event->id, 'handlerid'=>$handler->id))) {
3562 debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
3563 return $qhandler->id;
3566 // make a new queue handler
3567 $qhandler = new stdClass();
3568 $qhandler->queuedeventid = $event->id;
3569 $qhandler->handlerid = $handler->id;
3570 $qhandler->errormessage = $errormessage;
3571 $qhandler->timemodified = time();
3572 if ($handler->schedule === 'instant' and $handler->status == 1) {
3573 $qhandler->status = 1; //already one failed attempt to dispatch this event
3574 } else {
3575 $qhandler->status = 0;
3578 return $DB->insert_record('events_queue_handlers', $qhandler);
3582 * trigger a single event with a specified handler
3584 * @access protected To be used from eventslib only
3585 * @deprecated since Moodle 3.1
3586 * @param stdClass $handler This shoudl be a row from the events_handlers table.
3587 * @param stdClass $eventdata An object containing information about the event
3588 * @param string $errormessage error message indicating problem
3589 * @return bool|null True means event processed, false means retry event later; may throw exception, NULL means internal error
3591 function events_dispatch($handler, $eventdata, &$errormessage) {
3592 global $CFG;
3594 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3596 $function = unserialize($handler->handlerfunction);
3598 if (is_callable($function)) {
3599 // oki, no need for includes
3601 } else if (file_exists($CFG->dirroot.$handler->handlerfile)) {
3602 include_once($CFG->dirroot.$handler->handlerfile);
3604 } else {
3605 $errormessage = "Handler file of component $handler->component: $handler->handlerfile can not be found!";
3606 return null;
3609 // checks for handler validity
3610 if (is_callable($function)) {
3611 $result = call_user_func($function, $eventdata);
3612 if ($result === false) {
3613 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction requested resending of event!";
3614 return false;
3616 return true;
3618 } else {
3619 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction not callable function or class method!";
3620 return null;
3625 * given a queued handler, call the respective event handler to process the event
3627 * @access protected To be used from eventslib only
3628 * @deprecated since Moodle 3.1
3629 * @param stdClass $qhandler events_queued_handler row from db
3630 * @return boolean true means event processed, false means retry later, NULL means fatal failure
3632 function events_process_queued_handler($qhandler) {
3633 global $DB;
3635 // get handler
3636 if (!$handler = $DB->get_record('events_handlers', array('id'=>$qhandler->handlerid))) {
3637 debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
3638 //irrecoverable error, remove broken queue handler
3639 events_dequeue($qhandler);
3640 return NULL;
3643 // get event object
3644 if (!$event = $DB->get_record('events_queue', array('id'=>$qhandler->queuedeventid))) {
3645 // can't proceed with no event object - might happen when two crons running at the same time
3646 debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
3647 //irrecoverable error, remove broken queue handler
3648 events_dequeue($qhandler);
3649 return NULL;
3652 // call the function specified by the handler
3653 try {
3654 $errormessage = 'Unknown error';
3655 if (events_dispatch($handler, unserialize(base64_decode($event->eventdata)), $errormessage)) {
3656 //everything ok
3657 events_dequeue($qhandler);
3658 return true;
3660 } catch (Exception $e) {
3661 // the problem here is that we do not want one broken handler to stop all others,
3662 // cron handlers are very tricky because the needed data might have been deleted before the cron execution
3663 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction threw exception :" .
3664 $e->getMessage() . "\n" . format_backtrace($e->getTrace(), true);
3665 if (!empty($e->debuginfo)) {
3666 $errormessage .= $e->debuginfo;
3670 //dispatching failed
3671 $qh = new stdClass();
3672 $qh->id = $qhandler->id;
3673 $qh->errormessage = $errormessage;
3674 $qh->timemodified = time();
3675 $qh->status = $qhandler->status + 1;
3676 $DB->update_record('events_queue_handlers', $qh);
3678 debugging($errormessage);
3680 return false;
3684 * Updates all of the event definitions within the database.
3686 * Unfortunately this isn't as simple as removing them all and then readding
3687 * the updated event definitions. Chances are queued items are referencing the
3688 * existing definitions.
3690 * Note that the absence of the db/events.php event definition file
3691 * will cause any queued events for the component to be removed from
3692 * the database.
3694 * @category event
3695 * @deprecated since Moodle 3.1
3696 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3697 * @return boolean always returns true
3699 function events_update_definition($component='moodle') {
3700 global $DB;
3702 // load event definition from events.php
3703 $filehandlers = events_load_def($component);
3705 if ($filehandlers) {
3706 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3709 // load event definitions from db tables
3710 // if we detect an event being already stored, we discard from this array later
3711 // the remaining needs to be removed
3712 $cachedhandlers = events_get_cached($component);
3714 foreach ($filehandlers as $eventname => $filehandler) {
3715 if (!empty($cachedhandlers[$eventname])) {
3716 if ($cachedhandlers[$eventname]['handlerfile'] === $filehandler['handlerfile'] &&
3717 $cachedhandlers[$eventname]['handlerfunction'] === serialize($filehandler['handlerfunction']) &&
3718 $cachedhandlers[$eventname]['schedule'] === $filehandler['schedule'] &&
3719 $cachedhandlers[$eventname]['internal'] == $filehandler['internal']) {
3720 // exact same event handler already present in db, ignore this entry
3722 unset($cachedhandlers[$eventname]);
3723 continue;
3725 } else {
3726 // same event name matches, this event has been updated, update the datebase
3727 $handler = new stdClass();
3728 $handler->id = $cachedhandlers[$eventname]['id'];
3729 $handler->handlerfile = $filehandler['handlerfile'];
3730 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
3731 $handler->schedule = $filehandler['schedule'];
3732 $handler->internal = $filehandler['internal'];
3734 $DB->update_record('events_handlers', $handler);
3736 unset($cachedhandlers[$eventname]);
3737 continue;
3740 } else {
3741 // if we are here, this event handler is not present in db (new)
3742 // add it
3743 $handler = new stdClass();
3744 $handler->eventname = $eventname;
3745 $handler->component = $component;
3746 $handler->handlerfile = $filehandler['handlerfile'];
3747 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
3748 $handler->schedule = $filehandler['schedule'];
3749 $handler->status = 0;
3750 $handler->internal = $filehandler['internal'];
3752 $DB->insert_record('events_handlers', $handler);
3756 // clean up the left overs, the entries in cached events array at this points are deprecated event handlers
3757 // and should be removed, delete from db
3758 events_cleanup($component, $cachedhandlers);
3760 events_get_handlers('reset');
3762 return true;
3766 * Events cron will try to empty the events queue by processing all the queued events handlers
3768 * @access public Part of the public API
3769 * @deprecated since Moodle 3.1
3770 * @category event
3771 * @param string $eventname empty means all
3772 * @return int number of dispatched events
3774 function events_cron($eventname='') {
3775 global $DB;
3777 $failed = array();
3778 $processed = 0;
3780 if ($eventname) {
3781 $sql = "SELECT qh.*
3782 FROM {events_queue_handlers} qh, {events_handlers} h
3783 WHERE qh.handlerid = h.id AND h.eventname=?
3784 ORDER BY qh.id";
3785 $params = array($eventname);
3786 } else {
3787 $sql = "SELECT *
3788 FROM {events_queue_handlers}
3789 ORDER BY id";
3790 $params = array();
3793 $rs = $DB->get_recordset_sql($sql, $params);
3794 if ($rs->valid()) {
3795 debugging('Events API using $handlers array has been deprecated in favour of Events 2 API, please use it instead.', DEBUG_DEVELOPER);
3798 foreach ($rs as $qhandler) {
3799 if (isset($failed[$qhandler->handlerid])) {
3800 // do not try to dispatch any later events when one already asked for retry or ended with exception
3801 continue;
3803 $status = events_process_queued_handler($qhandler);
3804 if ($status === false) {
3805 // handler is asking for retry, do not send other events to this handler now
3806 $failed[$qhandler->handlerid] = $qhandler->handlerid;
3807 } else if ($status === NULL) {
3808 // means completely broken handler, event data was purged
3809 $failed[$qhandler->handlerid] = $qhandler->handlerid;
3810 } else {
3811 $processed++;
3814 $rs->close();
3816 // remove events that do not have any handlers waiting
3817 $sql = "SELECT eq.id
3818 FROM {events_queue} eq
3819 LEFT JOIN {events_queue_handlers} qh ON qh.queuedeventid = eq.id
3820 WHERE qh.id IS NULL";
3821 $rs = $DB->get_recordset_sql($sql);
3822 foreach ($rs as $event) {
3823 //debugging('Purging stale event '.$event->id);
3824 $DB->delete_records('events_queue', array('id'=>$event->id));
3826 $rs->close();
3828 return $processed;
3832 * Do not call directly, this is intended to be used from new event base only.
3834 * @private
3835 * @deprecated since Moodle 3.1
3836 * @param string $eventname name of the event
3837 * @param mixed $eventdata event data object
3838 * @return int number of failed events
3840 function events_trigger_legacy($eventname, $eventdata) {
3841 global $CFG, $USER, $DB;
3843 $failedcount = 0; // number of failed events.
3845 // pull out all registered event handlers
3846 if ($handlers = events_get_handlers($eventname)) {
3847 foreach ($handlers as $handler) {
3848 $errormessage = '';
3850 if ($handler->schedule === 'instant') {
3851 if ($handler->status) {
3852 //check if previous pending events processed
3853 if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id))) {
3854 // ok, queue is empty, lets reset the status back to 0 == ok
3855 $handler->status = 0;
3856 $DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id));
3857 // reset static handler cache
3858 events_get_handlers('reset');
3862 // dispatch the event only if instant schedule and status ok
3863 if ($handler->status or (!$handler->internal and $DB->is_transaction_started())) {
3864 // increment the error status counter
3865 $handler->status++;
3866 $DB->set_field('events_handlers', 'status', $handler->status, array('id'=>$handler->id));
3867 // reset static handler cache
3868 events_get_handlers('reset');
3870 } else {
3871 $errormessage = 'Unknown error';
3872 $result = events_dispatch($handler, $eventdata, $errormessage);
3873 if ($result === true) {
3874 // everything is fine - event dispatched
3875 continue;
3876 } else if ($result === false) {
3877 // retry later - set error count to 1 == send next instant into cron queue
3878 $DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id));
3879 // reset static handler cache
3880 events_get_handlers('reset');
3881 } else {
3882 // internal problem - ignore the event completely
3883 $failedcount ++;
3884 continue;
3888 // update the failed counter
3889 $failedcount ++;
3891 } else if ($handler->schedule === 'cron') {
3892 //ok - use queueing of events only
3894 } else {
3895 // unknown schedule - ignore event completely
3896 debugging("Unknown handler schedule type: $handler->schedule");
3897 $failedcount ++;
3898 continue;
3901 // if even type is not instant, or dispatch asked for retry, queue it
3902 $event = new stdClass();
3903 $event->userid = $USER->id;
3904 $event->eventdata = base64_encode(serialize($eventdata));
3905 $event->timecreated = time();
3906 if (debugging()) {
3907 $dump = '';
3908 $callers = debug_backtrace();
3909 foreach ($callers as $caller) {
3910 if (!isset($caller['line'])) {
3911 $caller['line'] = '?';
3913 if (!isset($caller['file'])) {
3914 $caller['file'] = '?';
3916 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
3917 if (isset($caller['function'])) {
3918 $dump .= ': call to ';
3919 if (isset($caller['class'])) {
3920 $dump .= $caller['class'] . $caller['type'];
3922 $dump .= $caller['function'] . '()';
3924 $dump .= "\n";
3926 $event->stackdump = $dump;
3927 } else {
3928 $event->stackdump = '';
3930 $event->id = $DB->insert_record('events_queue', $event);
3931 events_queue_handler($handler, $event, $errormessage);
3933 } else {
3934 // No handler found for this event name - this is ok!
3937 return $failedcount;
3941 * checks if an event is registered for this component
3943 * @access public Part of the public API
3944 * @deprecated since Moodle 3.1
3945 * @param string $eventname name of the event
3946 * @param string $component component name, can be mod/data or moodle
3947 * @return bool
3949 function events_is_registered($eventname, $component) {
3950 global $DB;
3952 debugging('events_is_registered() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
3953 ' please use it instead.', DEBUG_DEVELOPER);
3955 return $DB->record_exists('events_handlers', array('component'=>$component, 'eventname'=>$eventname));
3959 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
3961 * @access public Part of the public API
3962 * @deprecated since Moodle 3.1
3963 * @param string $eventname name of the event
3964 * @return int number of queued events
3966 function events_pending_count($eventname) {
3967 global $DB;
3969 debugging('events_pending_count() has been deprecated along with all Events 1 API in favour of Events 2 API,' .
3970 ' please use it instead.', DEBUG_DEVELOPER);
3972 $sql = "SELECT COUNT('x')
3973 FROM {events_queue_handlers} qh
3974 JOIN {events_handlers} h ON h.id = qh.handlerid
3975 WHERE h.eventname = ?";
3977 return $DB->count_records_sql($sql, array($eventname));
3981 * Emails admins about a clam outcome
3983 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
3984 * @param string $notice The body of the email to be sent.
3985 * @return void
3987 function clam_message_admins($notice) {
3988 debugging('clam_message_admins() is deprecated, please use message_admins() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
3990 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
3991 $antivirus->message_admins($notice);
3995 * Returns the string equivalent of a numeric clam error code
3997 * @deprecated since Moodle 3.0 - this is a part of clamav plugin now.
3998 * @param int $returncode The numeric error code in question.
3999 * @return string The definition of the error code
4001 function get_clam_error_code($returncode) {
4002 debugging('get_clam_error_code() is deprecated, please use get_clam_error_code() method of \antivirus_clamav\scanner class.', DEBUG_DEVELOPER);
4004 $antivirus = \core\antivirus\manager::get_antivirus('clamav');
4005 return $antivirus->get_clam_error_code($returncode);
4009 * Returns the rename action.
4011 * @deprecated since 3.1
4012 * @param cm_info $mod The module to produce editing buttons for
4013 * @param int $sr The section to link back to (used for creating the links)
4014 * @return The markup for the rename action, or an empty string if not available.
4016 function course_get_cm_rename_action(cm_info $mod, $sr = null) {
4017 global $COURSE, $OUTPUT;
4019 static $str;
4020 static $baseurl;
4022 debugging('Function course_get_cm_rename_action() is deprecated. Please use inplace_editable ' .
4023 'https://docs.moodle.org/dev/Inplace_editable', DEBUG_DEVELOPER);
4025 $modcontext = context_module::instance($mod->id);
4026 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
4028 if (!isset($str)) {
4029 $str = get_strings(array('edittitle'));
4032 if (!isset($baseurl)) {
4033 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
4036 if ($sr !== null) {
4037 $baseurl->param('sr', $sr);
4040 // AJAX edit title.
4041 if ($mod->has_view() && $hasmanageactivities && course_ajax_enabled($COURSE) &&
4042 (($mod->course == $COURSE->id) || ($mod->course == SITEID))) {
4043 // we will not display link if we are on some other-course page (where we should not see this module anyway)
4044 return html_writer::span(
4045 html_writer::link(
4046 new moodle_url($baseurl, array('update' => $mod->id)),
4047 $OUTPUT->pix_icon('t/editstring', '', 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
4048 array(
4049 'class' => 'editing_title',
4050 'data-action' => 'edittitle',
4051 'title' => $str->edittitle,
4056 return '';
4060 * This function returns the number of activities using the given scale in the given course.
4062 * @deprecated since Moodle 3.1
4063 * @param int $courseid The course ID to check.
4064 * @param int $scaleid The scale ID to check
4065 * @return int
4067 function course_scale_used($courseid, $scaleid) {
4068 global $CFG, $DB;
4070 debugging('course_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4071 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
4073 $return = 0;
4075 if (!empty($scaleid)) {
4076 if ($cms = get_course_mods($courseid)) {
4077 foreach ($cms as $cm) {
4078 // Check cm->name/lib.php exists.
4079 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
4080 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
4081 $functionname = $cm->modname.'_scale_used';
4082 if (function_exists($functionname)) {
4083 if ($functionname($cm->instance, $scaleid)) {
4084 $return++;
4091 // Check if any course grade item makes use of the scale.
4092 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
4094 // Check if any outcome in the course makes use of the scale.
4095 $return += $DB->count_records_sql("SELECT COUNT('x')
4096 FROM {grade_outcomes_courses} goc,
4097 {grade_outcomes} go
4098 WHERE go.id = goc.outcomeid
4099 AND go.scaleid = ? AND goc.courseid = ?",
4100 array($scaleid, $courseid));
4102 return $return;
4106 * This function returns the number of activities using scaleid in the entire site
4108 * @deprecated since Moodle 3.1
4109 * @param int $scaleid
4110 * @param array $courses
4111 * @return int
4113 function site_scale_used($scaleid, &$courses) {
4114 $return = 0;
4116 debugging('site_scale_used() is deprecated and never used, plugins can implement <modname>_scale_used_anywhere, '.
4117 'all implementations of <modname>_scale_used are now ignored', DEBUG_DEVELOPER);
4119 if (!is_array($courses) || count($courses) == 0) {
4120 $courses = get_courses("all", false, "c.id, c.shortname");
4123 if (!empty($scaleid)) {
4124 if (is_array($courses) && count($courses) > 0) {
4125 foreach ($courses as $course) {
4126 $return += course_scale_used($course->id, $scaleid);
4130 return $return;
4134 * @deprecated since Moodle 3.1. Use external_api::external_function_info().
4136 function external_function_info($function, $strictness=MUST_EXIST) {
4137 throw new coding_exception('external_function_info() can not be used any'.
4138 'more. Please use external_api::external_function_info() instead.');
4142 * Retrieves an array of records from a CSV file and places
4143 * them into a given table structure
4144 * This function is deprecated. Please use csv_import_reader() instead.
4146 * @deprecated since Moodle 3.2 MDL-55126
4147 * @todo MDL-55195 for final deprecation in Moodle 3.6
4148 * @see csv_import_reader::load_csv_content()
4149 * @global stdClass $CFG
4150 * @global moodle_database $DB
4151 * @param string $file The path to a CSV file
4152 * @param string $table The table to retrieve columns from
4153 * @return bool|array Returns an array of CSV records or false
4155 function get_records_csv($file, $table) {
4156 global $CFG, $DB;
4158 debugging('get_records_csv() is deprecated. Please use lib/csvlib.class.php csv_import_reader() instead.');
4160 if (!$metacolumns = $DB->get_columns($table)) {
4161 return false;
4164 if(!($handle = @fopen($file, 'r'))) {
4165 print_error('get_records_csv failed to open '.$file);
4168 $fieldnames = fgetcsv($handle, 4096);
4169 if(empty($fieldnames)) {
4170 fclose($handle);
4171 return false;
4174 $columns = array();
4176 foreach($metacolumns as $metacolumn) {
4177 $ord = array_search($metacolumn->name, $fieldnames);
4178 if(is_int($ord)) {
4179 $columns[$metacolumn->name] = $ord;
4183 $rows = array();
4185 while (($data = fgetcsv($handle, 4096)) !== false) {
4186 $item = new stdClass;
4187 foreach($columns as $name => $ord) {
4188 $item->$name = $data[$ord];
4190 $rows[] = $item;
4193 fclose($handle);
4194 return $rows;
4198 * Create a file with CSV contents
4199 * This function is deprecated. Please use download_as_dataformat() instead.
4201 * @deprecated since Moodle 3.2 MDL-55126
4202 * @todo MDL-55195 for final deprecation in Moodle 3.6
4203 * @see download_as_dataformat (lib/dataformatlib.php)
4204 * @global stdClass $CFG
4205 * @global moodle_database $DB
4206 * @param string $file The file to put the CSV content into
4207 * @param array $records An array of records to write to a CSV file
4208 * @param string $table The table to get columns from
4209 * @return bool success
4211 function put_records_csv($file, $records, $table = NULL) {
4212 global $CFG, $DB;
4214 debugging('put_records_csv() is deprecated. Please use lib/dataformatlib.php download_as_dataformat()');
4216 if (empty($records)) {
4217 return true;
4220 $metacolumns = NULL;
4221 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
4222 return false;
4225 echo "x";
4227 if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
4228 print_error('put_records_csv failed to open '.$file);
4231 $proto = reset($records);
4232 if(is_object($proto)) {
4233 $fields_records = array_keys(get_object_vars($proto));
4235 else if(is_array($proto)) {
4236 $fields_records = array_keys($proto);
4238 else {
4239 return false;
4241 echo "x";
4243 if(!empty($metacolumns)) {
4244 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
4245 $fields = array_intersect($fields_records, $fields_table);
4247 else {
4248 $fields = $fields_records;
4251 fwrite($fp, implode(',', $fields));
4252 fwrite($fp, "\r\n");
4254 foreach($records as $record) {
4255 $array = (array)$record;
4256 $values = array();
4257 foreach($fields as $field) {
4258 if(strpos($array[$field], ',')) {
4259 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
4261 else {
4262 $values[] = $array[$field];
4265 fwrite($fp, implode(',', $values)."\r\n");
4268 fclose($fp);
4269 @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
4270 return true;
4274 * Determines if the given value is a valid CSS colour.
4276 * A CSS colour can be one of the following:
4277 * - Hex colour: #AA66BB
4278 * - RGB colour: rgb(0-255, 0-255, 0-255)
4279 * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
4280 * - HSL colour: hsl(0-360, 0-100%, 0-100%)
4281 * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
4283 * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
4285 * @deprecated since Moodle 3.2
4286 * @todo MDL-56173 for final deprecation in Moodle 3.6
4287 * @param string $value The colour value to check
4288 * @return bool
4290 function css_is_colour($value) {
4291 debugging('css_is_colour() is deprecated without a replacement. Please copy the implementation '.
4292 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4294 $value = trim($value);
4296 $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
4297 $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
4298 $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4299 $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
4300 $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
4302 if (in_array(strtolower($value), array('inherit'))) {
4303 return true;
4304 } else if (preg_match($hex, $value)) {
4305 return true;
4306 } else if (in_array(strtolower($value), array_keys(css_optimiser::$htmlcolours))) {
4307 return true;
4308 } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4309 // It is an RGB colour.
4310 return true;
4311 } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
4312 // It is an RGBA colour.
4313 return true;
4314 } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4315 // It is an HSL colour.
4316 return true;
4317 } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
4318 // It is an HSLA colour.
4319 return true;
4321 // Doesn't look like a colour.
4322 return false;
4326 * Returns true is the passed value looks like a CSS width.
4327 * In order to pass this test the value must be purely numerical or end with a
4328 * valid CSS unit term.
4330 * @param string|int $value
4331 * @return boolean
4332 * @deprecated since Moodle 3.2
4333 * @todo MDL-56173 for final deprecation in Moodle 3.6
4335 function css_is_width($value) {
4336 debugging('css_is_width() is deprecated without a replacement. Please copy the implementation '.
4337 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4339 $value = trim($value);
4340 if (in_array(strtolower($value), array('auto', 'inherit'))) {
4341 return true;
4343 if ((string)$value === '0' || preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
4344 return true;
4346 return false;
4350 * A simple sorting function to sort two array values on the number of items they contain
4352 * @param array $a
4353 * @param array $b
4354 * @return int
4355 * @deprecated since Moodle 3.2
4356 * @todo MDL-56173 for final deprecation in Moodle 3.6
4358 function css_sort_by_count(array $a, array $b) {
4359 debugging('css_sort_by_count() is deprecated without a replacement. Please copy the implementation '.
4360 'into your plugin if you need this functionality.', DEBUG_DEVELOPER);
4362 $a = count($a);
4363 $b = count($b);
4364 if ($a == $b) {
4365 return 0;
4367 return ($a > $b) ? -1 : 1;
4371 * A basic CSS optimiser that strips out unwanted things and then processes CSS organising and cleaning styles.
4372 * @deprecated since Moodle 3.2
4373 * @todo MDL-56173 for final deprecation in Moodle 3.6
4375 class css_optimiser {
4377 * An array of the common HTML colours that are supported by most browsers.
4379 * This reference table is used to allow us to unify colours, and will aid
4380 * us in identifying buggy CSS using unsupported colours.
4382 * @var string[]
4383 * @deprecated since Moodle 3.2
4384 * @todo MDL-56173 for final deprecation in Moodle 3.6
4386 public static $htmlcolours = array(
4387 'aliceblue' => '#F0F8FF',
4388 'antiquewhite' => '#FAEBD7',
4389 'aqua' => '#00FFFF',
4390 'aquamarine' => '#7FFFD4',
4391 'azure' => '#F0FFFF',
4392 'beige' => '#F5F5DC',
4393 'bisque' => '#FFE4C4',
4394 'black' => '#000000',
4395 'blanchedalmond' => '#FFEBCD',
4396 'blue' => '#0000FF',
4397 'blueviolet' => '#8A2BE2',
4398 'brown' => '#A52A2A',
4399 'burlywood' => '#DEB887',
4400 'cadetblue' => '#5F9EA0',
4401 'chartreuse' => '#7FFF00',
4402 'chocolate' => '#D2691E',
4403 'coral' => '#FF7F50',
4404 'cornflowerblue' => '#6495ED',
4405 'cornsilk' => '#FFF8DC',
4406 'crimson' => '#DC143C',
4407 'cyan' => '#00FFFF',
4408 'darkblue' => '#00008B',
4409 'darkcyan' => '#008B8B',
4410 'darkgoldenrod' => '#B8860B',
4411 'darkgray' => '#A9A9A9',
4412 'darkgrey' => '#A9A9A9',
4413 'darkgreen' => '#006400',
4414 'darkKhaki' => '#BDB76B',
4415 'darkmagenta' => '#8B008B',
4416 'darkolivegreen' => '#556B2F',
4417 'arkorange' => '#FF8C00',
4418 'darkorchid' => '#9932CC',
4419 'darkred' => '#8B0000',
4420 'darksalmon' => '#E9967A',
4421 'darkseagreen' => '#8FBC8F',
4422 'darkslateblue' => '#483D8B',
4423 'darkslategray' => '#2F4F4F',
4424 'darkslategrey' => '#2F4F4F',
4425 'darkturquoise' => '#00CED1',
4426 'darkviolet' => '#9400D3',
4427 'deeppink' => '#FF1493',
4428 'deepskyblue' => '#00BFFF',
4429 'dimgray' => '#696969',
4430 'dimgrey' => '#696969',
4431 'dodgerblue' => '#1E90FF',
4432 'firebrick' => '#B22222',
4433 'floralwhite' => '#FFFAF0',
4434 'forestgreen' => '#228B22',
4435 'fuchsia' => '#FF00FF',
4436 'gainsboro' => '#DCDCDC',
4437 'ghostwhite' => '#F8F8FF',
4438 'gold' => '#FFD700',
4439 'goldenrod' => '#DAA520',
4440 'gray' => '#808080',
4441 'grey' => '#808080',
4442 'green' => '#008000',
4443 'greenyellow' => '#ADFF2F',
4444 'honeydew' => '#F0FFF0',
4445 'hotpink' => '#FF69B4',
4446 'indianred ' => '#CD5C5C',
4447 'indigo ' => '#4B0082',
4448 'ivory' => '#FFFFF0',
4449 'khaki' => '#F0E68C',
4450 'lavender' => '#E6E6FA',
4451 'lavenderblush' => '#FFF0F5',
4452 'lawngreen' => '#7CFC00',
4453 'lemonchiffon' => '#FFFACD',
4454 'lightblue' => '#ADD8E6',
4455 'lightcoral' => '#F08080',
4456 'lightcyan' => '#E0FFFF',
4457 'lightgoldenrodyellow' => '#FAFAD2',
4458 'lightgray' => '#D3D3D3',
4459 'lightgrey' => '#D3D3D3',
4460 'lightgreen' => '#90EE90',
4461 'lightpink' => '#FFB6C1',
4462 'lightsalmon' => '#FFA07A',
4463 'lightseagreen' => '#20B2AA',
4464 'lightskyblue' => '#87CEFA',
4465 'lightslategray' => '#778899',
4466 'lightslategrey' => '#778899',
4467 'lightsteelblue' => '#B0C4DE',
4468 'lightyellow' => '#FFFFE0',
4469 'lime' => '#00FF00',
4470 'limegreen' => '#32CD32',
4471 'linen' => '#FAF0E6',
4472 'magenta' => '#FF00FF',
4473 'maroon' => '#800000',
4474 'mediumaquamarine' => '#66CDAA',
4475 'mediumblue' => '#0000CD',
4476 'mediumorchid' => '#BA55D3',
4477 'mediumpurple' => '#9370D8',
4478 'mediumseagreen' => '#3CB371',
4479 'mediumslateblue' => '#7B68EE',
4480 'mediumspringgreen' => '#00FA9A',
4481 'mediumturquoise' => '#48D1CC',
4482 'mediumvioletred' => '#C71585',
4483 'midnightblue' => '#191970',
4484 'mintcream' => '#F5FFFA',
4485 'mistyrose' => '#FFE4E1',
4486 'moccasin' => '#FFE4B5',
4487 'navajowhite' => '#FFDEAD',
4488 'navy' => '#000080',
4489 'oldlace' => '#FDF5E6',
4490 'olive' => '#808000',
4491 'olivedrab' => '#6B8E23',
4492 'orange' => '#FFA500',
4493 'orangered' => '#FF4500',
4494 'orchid' => '#DA70D6',
4495 'palegoldenrod' => '#EEE8AA',
4496 'palegreen' => '#98FB98',
4497 'paleturquoise' => '#AFEEEE',
4498 'palevioletred' => '#D87093',
4499 'papayawhip' => '#FFEFD5',
4500 'peachpuff' => '#FFDAB9',
4501 'peru' => '#CD853F',
4502 'pink' => '#FFC0CB',
4503 'plum' => '#DDA0DD',
4504 'powderblue' => '#B0E0E6',
4505 'purple' => '#800080',
4506 'red' => '#FF0000',
4507 'rosybrown' => '#BC8F8F',
4508 'royalblue' => '#4169E1',
4509 'saddlebrown' => '#8B4513',
4510 'salmon' => '#FA8072',
4511 'sandybrown' => '#F4A460',
4512 'seagreen' => '#2E8B57',
4513 'seashell' => '#FFF5EE',
4514 'sienna' => '#A0522D',
4515 'silver' => '#C0C0C0',
4516 'skyblue' => '#87CEEB',
4517 'slateblue' => '#6A5ACD',
4518 'slategray' => '#708090',
4519 'slategrey' => '#708090',
4520 'snow' => '#FFFAFA',
4521 'springgreen' => '#00FF7F',
4522 'steelblue' => '#4682B4',
4523 'tan' => '#D2B48C',
4524 'teal' => '#008080',
4525 'thistle' => '#D8BFD8',
4526 'tomato' => '#FF6347',
4527 'transparent' => 'transparent',
4528 'turquoise' => '#40E0D0',
4529 'violet' => '#EE82EE',
4530 'wheat' => '#F5DEB3',
4531 'white' => '#FFFFFF',
4532 'whitesmoke' => '#F5F5F5',
4533 'yellow' => '#FFFF00',
4534 'yellowgreen' => '#9ACD32'
4538 * Used to orocesses incoming CSS optimising it and then returning it. Now just returns
4539 * what is sent to it. Do not use.
4541 * @param string $css The raw CSS to optimise
4542 * @return string The optimised CSS
4543 * @deprecated since Moodle 3.2
4544 * @todo MDL-56173 for final deprecation in Moodle 3.6
4546 public function process($css) {
4547 debugging('class css_optimiser is deprecated and no longer does anything, '.
4548 'please consider using stylelint to optimise your css.', DEBUG_DEVELOPER);
4550 return $css;
4555 * Load the course contexts for all of the users courses
4557 * @deprecated since Moodle 3.2
4558 * @param array $courses array of course objects. The courses the user is enrolled in.
4559 * @return array of course contexts
4561 function message_get_course_contexts($courses) {
4562 debugging('message_get_course_contexts() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4564 $coursecontexts = array();
4566 foreach($courses as $course) {
4567 $coursecontexts[$course->id] = context_course::instance($course->id);
4570 return $coursecontexts;
4574 * strip off action parameters like 'removecontact'
4576 * @deprecated since Moodle 3.2
4577 * @param moodle_url/string $moodleurl a URL. Typically the current page URL.
4578 * @return string the URL minus parameters that perform actions (like adding/removing/blocking a contact).
4580 function message_remove_url_params($moodleurl) {
4581 debugging('message_remove_url_params() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4583 $newurl = new moodle_url($moodleurl);
4584 $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
4585 return $newurl->out();
4589 * Count the number of messages with a field having a specified value.
4590 * if $field is empty then return count of the whole array
4591 * if $field is non-existent then return 0
4593 * @deprecated since Moodle 3.2
4594 * @param array $messagearray array of message objects
4595 * @param string $field the field to inspect on the message objects
4596 * @param string $value the value to test the field against
4598 function message_count_messages($messagearray, $field='', $value='') {
4599 debugging('message_count_messages() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4601 if (!is_array($messagearray)) return 0;
4602 if ($field == '' or empty($messagearray)) return count($messagearray);
4604 $count = 0;
4605 foreach ($messagearray as $message) {
4606 $count += ($message->$field == $value) ? 1 : 0;
4608 return $count;
4612 * Count the number of users blocked by $user1
4614 * @deprecated since Moodle 3.2
4615 * @param object $user1 user object
4616 * @return int the number of blocked users
4618 function message_count_blocked_users($user1=null) {
4619 debugging('message_count_blocked_users() is deprecated, please use \core_message\api::count_blocked_users() instead.',
4620 DEBUG_DEVELOPER);
4622 return \core_message\api::count_blocked_users($user1);
4626 * Print a message contact link
4628 * @deprecated since Moodle 3.2
4629 * @param int $userid the ID of the user to apply to action to
4630 * @param string $linktype can be add, remove, block or unblock
4631 * @param bool $return if true return the link as a string. If false echo the link.
4632 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4633 * @param bool $text include text next to the icons?
4634 * @param bool $icon include a graphical icon?
4635 * @return string if $return is true otherwise bool
4637 function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false, $icon=true) {
4638 debugging('message_contact_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4640 global $OUTPUT, $PAGE;
4642 //hold onto the strings as we're probably creating a bunch of links
4643 static $str;
4645 if (empty($script)) {
4646 //strip off previous action params like 'removecontact'
4647 $script = message_remove_url_params($PAGE->url);
4650 if (empty($str->blockcontact)) {
4651 $str = new stdClass();
4652 $str->blockcontact = get_string('blockcontact', 'message');
4653 $str->unblockcontact = get_string('unblockcontact', 'message');
4654 $str->removecontact = get_string('removecontact', 'message');
4655 $str->addcontact = get_string('addcontact', 'message');
4658 $command = $linktype.'contact';
4659 $string = $str->{$command};
4661 $safealttext = s($string);
4663 $safestring = '';
4664 if (!empty($text)) {
4665 $safestring = $safealttext;
4668 $img = '';
4669 if ($icon) {
4670 $iconpath = null;
4671 switch ($linktype) {
4672 case 'block':
4673 $iconpath = 't/block';
4674 break;
4675 case 'unblock':
4676 $iconpath = 't/unblock';
4677 break;
4678 case 'remove':
4679 $iconpath = 't/removecontact';
4680 break;
4681 case 'add':
4682 default:
4683 $iconpath = 't/addcontact';
4686 $img = $OUTPUT->pix_icon($iconpath, $safealttext);
4689 $output = '<span class="'.$linktype.'contact">'.
4690 '<a href="'.$script.'&amp;'.$command.'='.$userid.
4691 '&amp;sesskey='.sesskey().'" title="'.$safealttext.'">'.
4692 $img.
4693 $safestring.'</a></span>';
4695 if ($return) {
4696 return $output;
4697 } else {
4698 echo $output;
4699 return true;
4704 * @deprecated since Moodle 3.2
4706 function message_get_recent_notifications($user, $limitfrom=0, $limitto=100) {
4707 throw new coding_exception('message_get_recent_notifications() can not be used any more.', DEBUG_DEVELOPER);
4711 * echo or return a link to take the user to the full message history between themselves and another user
4713 * @deprecated since Moodle 3.2
4714 * @param int $userid1 the ID of the user displayed on the left (usually the current user)
4715 * @param int $userid2 the ID of the other user
4716 * @param bool $return true to return the link as a string. False to echo the link.
4717 * @param string $keywords any keywords to highlight in the message history
4718 * @param string $position anchor name to jump to within the message history
4719 * @param string $linktext optionally specify the link text
4720 * @return string|bool. Returns a string if $return is true. Otherwise returns a boolean.
4722 function message_history_link($userid1, $userid2, $return=false, $keywords='', $position='', $linktext='') {
4723 debugging('message_history_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4725 global $OUTPUT, $PAGE;
4726 static $strmessagehistory;
4728 if (empty($strmessagehistory)) {
4729 $strmessagehistory = get_string('messagehistory', 'message');
4732 if ($position) {
4733 $position = "#$position";
4735 if ($keywords) {
4736 $keywords = "&search=".urlencode($keywords);
4739 if ($linktext == 'icon') { // Icon only
4740 $fulllink = $OUTPUT->pix_icon('t/messages', $strmessagehistory);
4741 } else if ($linktext == 'both') { // Icon and standard name
4742 $fulllink = $OUTPUT->pix_icon('t/messages', '');
4743 $fulllink .= '&nbsp;'.$strmessagehistory;
4744 } else if ($linktext) { // Custom name
4745 $fulllink = $linktext;
4746 } else { // Standard name only
4747 $fulllink = $strmessagehistory;
4750 $popupoptions = array(
4751 'height' => 500,
4752 'width' => 500,
4753 'menubar' => false,
4754 'location' => false,
4755 'status' => true,
4756 'scrollbars' => true,
4757 'resizable' => true);
4759 $link = new moodle_url('/message/index.php?history='.MESSAGE_HISTORY_ALL."&user1=$userid1&user2=$userid2$keywords$position");
4760 if ($PAGE->url && $PAGE->url->get_param('viewing')) {
4761 $link->param('viewing', $PAGE->url->get_param('viewing'));
4763 $action = null;
4764 $str = $OUTPUT->action_link($link, $fulllink, $action, array('title' => $strmessagehistory));
4766 $str = '<span class="history">'.$str.'</span>';
4768 if ($return) {
4769 return $str;
4770 } else {
4771 echo $str;
4772 return true;
4777 * @deprecated since Moodle 3.2
4779 function message_search($searchterms, $fromme=true, $tome=true, $courseid='none', $userid=0) {
4780 throw new coding_exception('message_search() can not be used any more.', DEBUG_DEVELOPER);
4784 * Given a message object that we already know has a long message
4785 * this function truncates the message nicely to the first
4786 * sane place between $CFG->forum_longpost and $CFG->forum_shortpost
4788 * @deprecated since Moodle 3.2
4789 * @param string $message the message
4790 * @param int $minlength the minimum length to trim the message to
4791 * @return string the shortened message
4793 function message_shorten_message($message, $minlength = 0) {
4794 debugging('message_shorten_message() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4796 $i = 0;
4797 $tag = false;
4798 $length = strlen($message);
4799 $count = 0;
4800 $stopzone = false;
4801 $truncate = 0;
4802 if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
4805 for ($i=0; $i<$length; $i++) {
4806 $char = $message[$i];
4808 switch ($char) {
4809 case "<":
4810 $tag = true;
4811 break;
4812 case ">":
4813 $tag = false;
4814 break;
4815 default:
4816 if (!$tag) {
4817 if ($stopzone) {
4818 if ($char == '.' or $char == ' ') {
4819 $truncate = $i+1;
4820 break 2;
4823 $count++;
4825 break;
4827 if (!$stopzone) {
4828 if ($count > $minlength) {
4829 $stopzone = true;
4834 if (!$truncate) {
4835 $truncate = $i;
4838 return substr($message, 0, $truncate);
4842 * Given a string and an array of keywords, this function looks
4843 * for the first keyword in the string, and then chops out a
4844 * small section from the text that shows that word in context.
4846 * @deprecated since Moodle 3.2
4847 * @param string $message the text to search
4848 * @param array $keywords array of keywords to find
4850 function message_get_fragment($message, $keywords) {
4851 debugging('message_get_fragment() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4853 $fullsize = 160;
4854 $halfsize = (int)($fullsize/2);
4856 $message = strip_tags($message);
4858 foreach ($keywords as $keyword) { // Just get the first one
4859 if ($keyword !== '') {
4860 break;
4863 if (empty($keyword)) { // None found, so just return start of message
4864 return message_shorten_message($message, 30);
4867 $leadin = $leadout = '';
4869 /// Find the start of the fragment
4870 $start = 0;
4871 $length = strlen($message);
4873 $pos = strpos($message, $keyword);
4874 if ($pos > $halfsize) {
4875 $start = $pos - $halfsize;
4876 $leadin = '...';
4878 /// Find the end of the fragment
4879 $end = $start + $fullsize;
4880 if ($end > $length) {
4881 $end = $length;
4882 } else {
4883 $leadout = '...';
4886 /// Pull out the fragment and format it
4888 $fragment = substr($message, $start, $end - $start);
4889 $fragment = $leadin.highlight(implode(' ',$keywords), $fragment).$leadout;
4890 return $fragment;
4894 * @deprecated since Moodle 3.2
4896 function message_get_history($user1, $user2, $limitnum=0, $viewingnewmessages=false) {
4897 throw new coding_exception('message_get_history() can not be used any more.', DEBUG_DEVELOPER);
4901 * Constructs the add/remove contact link to display next to other users
4903 * @deprecated since Moodle 3.2
4904 * @param bool $incontactlist is the user a contact
4905 * @param bool $isblocked is the user blocked
4906 * @param stdClass $contact contact object
4907 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4908 * @param bool $text include text next to the icons?
4909 * @param bool $icon include a graphical icon?
4910 * @return string
4912 function message_get_contact_add_remove_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
4913 debugging('message_get_contact_add_remove_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4915 $strcontact = '';
4917 if($incontactlist){
4918 $strcontact = message_contact_link($contact->id, 'remove', true, $script, $text, $icon);
4919 } else if ($isblocked) {
4920 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
4921 } else{
4922 $strcontact = message_contact_link($contact->id, 'add', true, $script, $text, $icon);
4925 return $strcontact;
4929 * Constructs the block contact link to display next to other users
4931 * @deprecated since Moodle 3.2
4932 * @param bool $incontactlist is the user a contact?
4933 * @param bool $isblocked is the user blocked?
4934 * @param stdClass $contact contact object
4935 * @param string $script the URL to send the user to when the link is clicked. If null, the current page.
4936 * @param bool $text include text next to the icons?
4937 * @param bool $icon include a graphical icon?
4938 * @return string
4940 function message_get_contact_block_link($incontactlist, $isblocked, $contact, $script=null, $text=false, $icon=true) {
4941 debugging('message_get_contact_block_link() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4943 $strblock = '';
4945 //commented out to allow the user to block a contact without having to remove them first
4946 /*if ($incontactlist) {
4947 //$strblock = '';
4948 } else*/
4949 if ($isblocked) {
4950 $strblock = message_contact_link($contact->id, 'unblock', true, $script, $text, $icon);
4951 } else{
4952 $strblock = message_contact_link($contact->id, 'block', true, $script, $text, $icon);
4955 return $strblock;
4959 * marks ALL messages being sent from $fromuserid to $touserid as read
4961 * @deprecated since Moodle 3.2
4962 * @param int $touserid the id of the message recipient
4963 * @param int $fromuserid the id of the message sender
4964 * @return void
4966 function message_mark_messages_read($touserid, $fromuserid) {
4967 debugging('message_mark_messages_read() is deprecated and is no longer used, please use
4968 \core_message\api::mark_all_messages_as_read() instead.', DEBUG_DEVELOPER);
4970 \core_message\api::mark_all_messages_as_read($touserid, $fromuserid);
4974 * Return a list of page types
4976 * @deprecated since Moodle 3.2
4977 * @param string $pagetype current page type
4978 * @param stdClass $parentcontext Block's parent context
4979 * @param stdClass $currentcontext Current context of block
4981 function message_page_type_list($pagetype, $parentcontext, $currentcontext) {
4982 debugging('message_page_type_list() is deprecated and is no longer used.', DEBUG_DEVELOPER);
4984 return array('messages-*'=>get_string('page-message-x', 'message'));
4988 * Determines if a user is permitted to send another user a private message.
4989 * If no sender is provided then it defaults to the logged in user.
4991 * @deprecated since Moodle 3.2
4992 * @param object $recipient User object.
4993 * @param object $sender User object.
4994 * @return bool true if user is permitted, false otherwise.
4996 function message_can_post_message($recipient, $sender = null) {
4997 debugging('message_can_post_message() is deprecated and is no longer used, please use
4998 \core_message\api::can_post_message() instead.', DEBUG_DEVELOPER);
5000 return \core_message\api::can_post_message($recipient, $sender);
5004 * Checks if the recipient is allowing messages from users that aren't a
5005 * contact. If not then it checks to make sure the sender is in the
5006 * recipient's contacts.
5008 * @deprecated since Moodle 3.2
5009 * @param object $recipient User object.
5010 * @param object $sender User object.
5011 * @return bool true if $sender is blocked, false otherwise.
5013 function message_is_user_non_contact_blocked($recipient, $sender = null) {
5014 debugging('message_is_user_non_contact_blocked() is deprecated and is no longer used, please use
5015 \core_message\api::is_user_non_contact_blocked() instead.', DEBUG_DEVELOPER);
5017 return \core_message\api::is_user_non_contact_blocked($recipient, $sender);
5021 * Checks if the recipient has specifically blocked the sending user.
5023 * Note: This function will always return false if the sender has the
5024 * readallmessages capability at the system context level.
5026 * @deprecated since Moodle 3.2
5027 * @param object $recipient User object.
5028 * @param object $sender User object.
5029 * @return bool true if $sender is blocked, false otherwise.
5031 function message_is_user_blocked($recipient, $sender = null) {
5032 debugging('message_is_user_blocked() is deprecated and is no longer used, please use
5033 \core_message\api::is_user_blocked() instead.', DEBUG_DEVELOPER);
5035 $senderid = null;
5036 if ($sender !== null && isset($sender->id)) {
5037 $senderid = $sender->id;
5039 return \core_message\api::is_user_blocked($recipient->id, $senderid);
5043 * Display logs.
5045 * @deprecated since 3.2
5047 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5048 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5049 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5051 global $CFG, $DB, $OUTPUT;
5053 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
5054 $modname, $modid, $modaction, $groupid)) {
5055 echo $OUTPUT->notification("No logs found!");
5056 echo $OUTPUT->footer();
5057 exit;
5060 $courses = array();
5062 if ($course->id == SITEID) {
5063 $courses[0] = '';
5064 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5065 foreach ($ccc as $cc) {
5066 $courses[$cc->id] = $cc->shortname;
5069 } else {
5070 $courses[$course->id] = $course->shortname;
5073 $totalcount = $logs['totalcount'];
5074 $ldcache = array();
5076 $strftimedatetime = get_string("strftimedatetime");
5078 echo "<div class=\"info\">\n";
5079 print_string("displayingrecords", "", $totalcount);
5080 echo "</div>\n";
5082 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5084 $table = new html_table();
5085 $table->classes = array('logtable','generaltable');
5086 $table->align = array('right', 'left', 'left');
5087 $table->head = array(
5088 get_string('time'),
5089 get_string('ip_address'),
5090 get_string('fullnameuser'),
5091 get_string('action'),
5092 get_string('info')
5094 $table->data = array();
5096 if ($course->id == SITEID) {
5097 array_unshift($table->align, 'left');
5098 array_unshift($table->head, get_string('course'));
5101 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
5102 if (empty($logs['logs'])) {
5103 $logs['logs'] = array();
5106 foreach ($logs['logs'] as $log) {
5108 if (isset($ldcache[$log->module][$log->action])) {
5109 $ld = $ldcache[$log->module][$log->action];
5110 } else {
5111 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5112 $ldcache[$log->module][$log->action] = $ld;
5114 if ($ld && is_numeric($log->info)) {
5115 // ugly hack to make sure fullname is shown correctly
5116 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
5117 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5118 } else {
5119 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5123 //Filter log->info
5124 $log->info = format_string($log->info);
5126 // If $log->url has been trimmed short by the db size restriction
5127 // code in add_to_log, keep a note so we don't add a link to a broken url
5128 $brokenurl=(core_text::strlen($log->url)==100 && core_text::substr($log->url,97)=='...');
5130 $row = array();
5131 if ($course->id == SITEID) {
5132 if (empty($log->course)) {
5133 $row[] = get_string('site');
5134 } else {
5135 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
5139 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
5141 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5142 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
5144 $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))));
5146 $displayaction="$log->module $log->action";
5147 if ($brokenurl) {
5148 $row[] = $displayaction;
5149 } else {
5150 $link = make_log_url($log->module,$log->url);
5151 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
5153 $row[] = $log->info;
5154 $table->data[] = $row;
5157 echo html_writer::table($table);
5158 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5162 * Display MNET logs.
5164 * @deprecated since 3.2
5166 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
5167 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
5168 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5170 global $CFG, $DB, $OUTPUT;
5172 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
5173 $modname, $modid, $modaction, $groupid)) {
5174 echo $OUTPUT->notification("No logs found!");
5175 echo $OUTPUT->footer();
5176 exit;
5179 if ($course->id == SITEID) {
5180 $courses[0] = '';
5181 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
5182 foreach ($ccc as $cc) {
5183 $courses[$cc->id] = $cc->shortname;
5188 $totalcount = $logs['totalcount'];
5189 $ldcache = array();
5191 $strftimedatetime = get_string("strftimedatetime");
5193 echo "<div class=\"info\">\n";
5194 print_string("displayingrecords", "", $totalcount);
5195 echo "</div>\n";
5197 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5199 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
5200 echo "<tr>";
5201 if ($course->id == SITEID) {
5202 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
5204 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
5205 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
5206 echo "<th class=\"c3 header\">".get_string('fullnameuser')."</th>\n";
5207 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
5208 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
5209 echo "</tr>\n";
5211 if (empty($logs['logs'])) {
5212 echo "</table>\n";
5213 return;
5216 $row = 1;
5217 foreach ($logs['logs'] as $log) {
5219 $log->info = $log->coursename;
5220 $row = ($row + 1) % 2;
5222 if (isset($ldcache[$log->module][$log->action])) {
5223 $ld = $ldcache[$log->module][$log->action];
5224 } else {
5225 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5226 $ldcache[$log->module][$log->action] = $ld;
5228 if (0 && $ld && !empty($log->info)) {
5229 // ugly hack to make sure fullname is shown correctly
5230 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5231 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5232 } else {
5233 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5237 //Filter log->info
5238 $log->info = format_string($log->info);
5240 echo '<tr class="r'.$row.'">';
5241 if ($course->id == SITEID) {
5242 $courseshortname = format_string($courses[$log->course], true, array('context' => context_course::instance(SITEID)));
5243 echo "<td class=\"r$row c0\" >\n";
5244 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courseshortname."</a>\n";
5245 echo "</td>\n";
5247 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
5248 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
5249 echo "<td class=\"r$row c2\" >\n";
5250 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
5251 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
5252 echo "</td>\n";
5253 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', context_course::instance($course->id)));
5254 echo "<td class=\"r$row c3\" >\n";
5255 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
5256 echo "</td>\n";
5257 echo "<td class=\"r$row c4\">\n";
5258 echo $log->action .': '.$log->module;
5259 echo "</td>\n";
5260 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
5261 echo "</tr>\n";
5263 echo "</table>\n";
5265 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
5269 * Display logs in CSV format.
5271 * @deprecated since 3.2
5273 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
5274 $modid, $modaction, $groupid) {
5275 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5277 global $DB, $CFG;
5279 require_once($CFG->libdir . '/csvlib.class.php');
5281 $csvexporter = new csv_export_writer('tab');
5283 $header = array();
5284 $header[] = get_string('course');
5285 $header[] = get_string('time');
5286 $header[] = get_string('ip_address');
5287 $header[] = get_string('fullnameuser');
5288 $header[] = get_string('action');
5289 $header[] = get_string('info');
5291 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5292 $modname, $modid, $modaction, $groupid)) {
5293 return false;
5296 $courses = array();
5298 if ($course->id == SITEID) {
5299 $courses[0] = '';
5300 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5301 foreach ($ccc as $cc) {
5302 $courses[$cc->id] = $cc->shortname;
5305 } else {
5306 $courses[$course->id] = $course->shortname;
5309 $count=0;
5310 $ldcache = array();
5311 $tt = getdate(time());
5312 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5314 $strftimedatetime = get_string("strftimedatetime");
5316 $csvexporter->set_filename('logs', '.txt');
5317 $title = array(get_string('savedat').userdate(time(), $strftimedatetime));
5318 $csvexporter->add_data($title);
5319 $csvexporter->add_data($header);
5321 if (empty($logs['logs'])) {
5322 return true;
5325 foreach ($logs['logs'] as $log) {
5326 if (isset($ldcache[$log->module][$log->action])) {
5327 $ld = $ldcache[$log->module][$log->action];
5328 } else {
5329 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5330 $ldcache[$log->module][$log->action] = $ld;
5332 if ($ld && is_numeric($log->info)) {
5333 // ugly hack to make sure fullname is shown correctly
5334 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5335 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5336 } else {
5337 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5341 //Filter log->info
5342 $log->info = format_string($log->info);
5343 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5345 $coursecontext = context_course::instance($course->id);
5346 $firstField = format_string($courses[$log->course], true, array('context' => $coursecontext));
5347 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5348 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5349 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action.' ('.$actionurl.')', $log->info);
5350 $csvexporter->add_data($row);
5352 $csvexporter->download_file();
5353 return true;
5357 * Display logs in XLS format.
5359 * @deprecated since 3.2
5361 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
5362 $modid, $modaction, $groupid) {
5363 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5365 global $CFG, $DB;
5367 require_once("$CFG->libdir/excellib.class.php");
5369 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5370 $modname, $modid, $modaction, $groupid)) {
5371 return false;
5374 $courses = array();
5376 if ($course->id == SITEID) {
5377 $courses[0] = '';
5378 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5379 foreach ($ccc as $cc) {
5380 $courses[$cc->id] = $cc->shortname;
5383 } else {
5384 $courses[$course->id] = $course->shortname;
5387 $count=0;
5388 $ldcache = array();
5389 $tt = getdate(time());
5390 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
5392 $strftimedatetime = get_string("strftimedatetime");
5394 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
5395 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5396 $filename .= '.xls';
5398 $workbook = new MoodleExcelWorkbook('-');
5399 $workbook->send($filename);
5401 $worksheet = array();
5402 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5403 get_string('fullnameuser'), get_string('action'), get_string('info'));
5405 // Creating worksheets
5406 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
5407 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5408 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5409 $worksheet[$wsnumber]->set_column(1, 1, 30);
5410 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5411 userdate(time(), $strftimedatetime));
5412 $col = 0;
5413 foreach ($headers as $item) {
5414 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
5415 $col++;
5419 if (empty($logs['logs'])) {
5420 $workbook->close();
5421 return true;
5424 $formatDate =& $workbook->add_format();
5425 $formatDate->set_num_format(get_string('log_excel_date_format'));
5427 $row = FIRSTUSEDEXCELROW;
5428 $wsnumber = 1;
5429 $myxls =& $worksheet[$wsnumber];
5430 foreach ($logs['logs'] as $log) {
5431 if (isset($ldcache[$log->module][$log->action])) {
5432 $ld = $ldcache[$log->module][$log->action];
5433 } else {
5434 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5435 $ldcache[$log->module][$log->action] = $ld;
5437 if ($ld && is_numeric($log->info)) {
5438 // ugly hack to make sure fullname is shown correctly
5439 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5440 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5441 } else {
5442 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5446 // Filter log->info
5447 $log->info = format_string($log->info);
5448 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5450 if ($nroPages>1) {
5451 if ($row > EXCELROWS) {
5452 $wsnumber++;
5453 $myxls =& $worksheet[$wsnumber];
5454 $row = FIRSTUSEDEXCELROW;
5458 $coursecontext = context_course::instance($course->id);
5460 $myxls->write($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)), '');
5461 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
5462 $myxls->write($row, 2, $log->ip, '');
5463 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5464 $myxls->write($row, 3, $fullname, '');
5465 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5466 $myxls->write($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')', '');
5467 $myxls->write($row, 5, $log->info, '');
5469 $row++;
5472 $workbook->close();
5473 return true;
5477 * Display logs in ODS format.
5479 * @deprecated since 3.2
5481 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
5482 $modid, $modaction, $groupid) {
5483 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5485 global $CFG, $DB;
5487 require_once("$CFG->libdir/odslib.class.php");
5489 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
5490 $modname, $modid, $modaction, $groupid)) {
5491 return false;
5494 $courses = array();
5496 if ($course->id == SITEID) {
5497 $courses[0] = '';
5498 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
5499 foreach ($ccc as $cc) {
5500 $courses[$cc->id] = $cc->shortname;
5503 } else {
5504 $courses[$course->id] = $course->shortname;
5507 $ldcache = array();
5509 $strftimedatetime = get_string("strftimedatetime");
5511 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
5512 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
5513 $filename .= '.ods';
5515 $workbook = new MoodleODSWorkbook('-');
5516 $workbook->send($filename);
5518 $worksheet = array();
5519 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
5520 get_string('fullnameuser'), get_string('action'), get_string('info'));
5522 // Creating worksheets
5523 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
5524 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
5525 $worksheet[$wsnumber] = $workbook->add_worksheet($sheettitle);
5526 $worksheet[$wsnumber]->set_column(1, 1, 30);
5527 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
5528 userdate(time(), $strftimedatetime));
5529 $col = 0;
5530 foreach ($headers as $item) {
5531 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
5532 $col++;
5536 if (empty($logs['logs'])) {
5537 $workbook->close();
5538 return true;
5541 $formatDate =& $workbook->add_format();
5542 $formatDate->set_num_format(get_string('log_excel_date_format'));
5544 $row = FIRSTUSEDEXCELROW;
5545 $wsnumber = 1;
5546 $myxls =& $worksheet[$wsnumber];
5547 foreach ($logs['logs'] as $log) {
5548 if (isset($ldcache[$log->module][$log->action])) {
5549 $ld = $ldcache[$log->module][$log->action];
5550 } else {
5551 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
5552 $ldcache[$log->module][$log->action] = $ld;
5554 if ($ld && is_numeric($log->info)) {
5555 // ugly hack to make sure fullname is shown correctly
5556 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
5557 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
5558 } else {
5559 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
5563 // Filter log->info
5564 $log->info = format_string($log->info);
5565 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
5567 if ($nroPages>1) {
5568 if ($row > EXCELROWS) {
5569 $wsnumber++;
5570 $myxls =& $worksheet[$wsnumber];
5571 $row = FIRSTUSEDEXCELROW;
5575 $coursecontext = context_course::instance($course->id);
5577 $myxls->write_string($row, 0, format_string($courses[$log->course], true, array('context' => $coursecontext)));
5578 $myxls->write_date($row, 1, $log->time);
5579 $myxls->write_string($row, 2, $log->ip);
5580 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', $coursecontext));
5581 $myxls->write_string($row, 3, $fullname);
5582 $actionurl = $CFG->wwwroot. make_log_url($log->module,$log->url);
5583 $myxls->write_string($row, 4, $log->module.' '.$log->action.' ('.$actionurl.')');
5584 $myxls->write_string($row, 5, $log->info);
5586 $row++;
5589 $workbook->close();
5590 return true;
5594 * Build an array of logs.
5596 * @deprecated since 3.2
5598 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
5599 $modname="", $modid=0, $modaction="", $groupid=0) {
5600 global $DB, $SESSION, $USER;
5602 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5603 // It is assumed that $date is the GMT time of midnight for that day,
5604 // and so the next 86400 seconds worth of logs are printed.
5606 // Setup for group handling.
5608 // If the group mode is separate, and this user does not have editing privileges,
5609 // then only the user's group can be viewed.
5610 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
5611 if (isset($SESSION->currentgroup[$course->id])) {
5612 $groupid = $SESSION->currentgroup[$course->id];
5613 } else {
5614 $groupid = groups_get_all_groups($course->id, $USER->id);
5615 if (is_array($groupid)) {
5616 $groupid = array_shift(array_keys($groupid));
5617 $SESSION->currentgroup[$course->id] = $groupid;
5618 } else {
5619 $groupid = 0;
5623 // If this course doesn't have groups, no groupid can be specified.
5624 else if (!$course->groupmode) {
5625 $groupid = 0;
5628 $joins = array();
5629 $params = array();
5631 if ($course->id != SITEID || $modid != 0) {
5632 $joins[] = "l.course = :courseid";
5633 $params['courseid'] = $course->id;
5636 if ($modname) {
5637 $joins[] = "l.module = :modname";
5638 $params['modname'] = $modname;
5641 if ('site_errors' === $modid) {
5642 $joins[] = "( l.action='error' OR l.action='infected' )";
5643 } else if ($modid) {
5644 $joins[] = "l.cmid = :modid";
5645 $params['modid'] = $modid;
5648 if ($modaction) {
5649 $firstletter = substr($modaction, 0, 1);
5650 if ($firstletter == '-') {
5651 $joins[] = $DB->sql_like('l.action', ':modaction', false, true, true);
5652 $params['modaction'] = '%'.substr($modaction, 1).'%';
5653 } else {
5654 $joins[] = $DB->sql_like('l.action', ':modaction', false);
5655 $params['modaction'] = '%'.$modaction.'%';
5660 /// Getting all members of a group.
5661 if ($groupid and !$user) {
5662 if ($gusers = groups_get_members($groupid)) {
5663 $gusers = array_keys($gusers);
5664 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
5665 } else {
5666 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
5669 else if ($user) {
5670 $joins[] = "l.userid = :userid";
5671 $params['userid'] = $user;
5674 if ($date) {
5675 $enddate = $date + 86400;
5676 $joins[] = "l.time > :date AND l.time < :enddate";
5677 $params['date'] = $date;
5678 $params['enddate'] = $enddate;
5681 $selector = implode(' AND ', $joins);
5683 $totalcount = 0; // Initialise
5684 $result = array();
5685 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
5686 $result['totalcount'] = $totalcount;
5687 return $result;
5691 * Select all log records for a given course and user.
5693 * @deprecated since 3.2
5694 * @param int $userid The id of the user as found in the 'user' table.
5695 * @param int $courseid The id of the course as found in the 'course' table.
5696 * @param string $coursestart unix timestamp representing course start date and time.
5697 * @return array
5699 function get_logs_usercourse($userid, $courseid, $coursestart) {
5700 global $DB;
5702 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5704 $params = array();
5706 $courseselect = '';
5707 if ($courseid) {
5708 $courseselect = "AND course = :courseid";
5709 $params['courseid'] = $courseid;
5711 $params['userid'] = $userid;
5712 // We have to sanitize this param ourselves here instead of relying on DB.
5713 // Postgres complains if you use name parameter or column alias in GROUP BY.
5714 // See MDL-27696 and 51c3e85 for details.
5715 $coursestart = (int)$coursestart;
5717 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
5718 FROM {log}
5719 WHERE userid = :userid
5720 AND time > $coursestart $courseselect
5721 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
5725 * Select all log records for a given course, user, and day.
5727 * @deprecated since 3.2
5728 * @param int $userid The id of the user as found in the 'user' table.
5729 * @param int $courseid The id of the course as found in the 'course' table.
5730 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
5731 * @return array
5733 function get_logs_userday($userid, $courseid, $daystart) {
5734 global $DB;
5736 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5738 $params = array('userid'=>$userid);
5740 $courseselect = '';
5741 if ($courseid) {
5742 $courseselect = "AND course = :courseid";
5743 $params['courseid'] = $courseid;
5745 // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
5746 $daystart = (int) $daystart;
5748 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
5749 FROM {log}
5750 WHERE userid = :userid
5751 AND time > $daystart $courseselect
5752 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
5756 * Select all log records based on SQL criteria.
5758 * @deprecated since 3.2
5759 * @param string $select SQL select criteria
5760 * @param array $params named sql type params
5761 * @param string $order SQL order by clause to sort the records returned
5762 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
5763 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
5764 * @param int $totalcount Passed in by reference.
5765 * @return array
5767 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
5768 global $DB;
5770 debugging(__FUNCTION__ . '() is deprecated. Please use the report_log framework instead.', DEBUG_DEVELOPER);
5772 if ($order) {
5773 $order = "ORDER BY $order";
5776 if ($select) {
5777 $select = "WHERE $select";
5780 $sql = "SELECT COUNT(*)
5781 FROM {log} l
5782 $select";
5784 $totalcount = $DB->count_records_sql($sql, $params);
5785 $allnames = get_all_user_name_fields(true, 'u');
5786 $sql = "SELECT l.*, $allnames, u.picture
5787 FROM {log} l
5788 LEFT JOIN {user} u ON l.userid = u.id
5789 $select
5790 $order";
5792 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5796 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
5798 * @deprecated since Moodle 3.2 MDL-53048
5800 function prevent_form_autofill_password() {
5801 debugging('prevent_form_autofill_password has been deprecated and is no longer in use.', DEBUG_DEVELOPER);
5802 return '';
5806 * @deprecated since Moodle 3.3 MDL-57370
5808 function message_get_recent_conversations($userorid, $limitfrom = 0, $limitto = 100) {
5809 throw new coding_exception('message_get_recent_conversations() can not be used any more. ' .
5810 'Please use \core_message\api::get_conversations() instead.', DEBUG_DEVELOPER);
5814 * Display calendar preference button.
5816 * @param stdClass $course course object
5817 * @deprecated since Moodle 3.2
5818 * @return string return preference button in html
5820 function calendar_preferences_button(stdClass $course) {
5821 debugging('This should no longer be used, the calendar preferences are now linked to the user preferences page.');
5823 global $OUTPUT;
5825 // Guests have no preferences.
5826 if (!isloggedin() || isguestuser()) {
5827 return '';
5830 return $OUTPUT->single_button(new moodle_url('/user/calendar.php'), get_string("preferences", "calendar"));
5834 * Return the name of the weekday
5836 * @deprecated since 3.3
5837 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5838 * @param string $englishname
5839 * @return string of the weekeday
5841 function calendar_wday_name($englishname) {
5842 debugging(__FUNCTION__ . '() is deprecated and no longer used in core.', DEBUG_DEVELOPER);
5843 return get_string(strtolower($englishname), 'calendar');
5847 * Get the upcoming event block.
5849 * @deprecated since 3.3
5850 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5851 * @param array $events list of events
5852 * @param moodle_url|string $linkhref link to event referer
5853 * @param boolean $showcourselink whether links to courses should be shown
5854 * @return string|null $content html block content
5856 function calendar_get_block_upcoming($events, $linkhref = null, $showcourselink = false) {
5857 global $CFG;
5859 debugging(
5860 __FUNCTION__ . '() has been deprecated. ' .
5861 'Please see block_calendar_upcoming::get_content() for the correct API usage.',
5862 DEBUG_DEVELOPER
5865 require_once($CFG->dirroot . '/blocks/moodleblock.class.php');
5866 require_once($CFG->dirroot . '/blocks/calendar_upcoming/block_calendar_upcoming.php');
5867 return block_calendar_upcoming::get_upcoming_content($events, $linkhref, $showcourselink);
5871 * Display month selector options.
5873 * @deprecated since 3.3
5874 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5875 * @param string $name for the select element
5876 * @param string|array $selected options for select elements
5878 function calendar_print_month_selector($name, $selected) {
5879 debugging(__FUNCTION__ . '() is deprecated and no longer used in core.', DEBUG_DEVELOPER);
5880 $months = array();
5881 for ($i = 1; $i <= 12; $i++) {
5882 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
5884 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
5885 echo html_writer::select($months, $name, $selected, false);
5889 * Update calendar subscriptions.
5891 * @deprecated since 3.3
5892 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57617.
5893 * @return bool
5895 function calendar_cron() {
5896 debugging(__FUNCTION__ . '() is deprecated and should not be used. Please use the core\task\calendar_cron_task instead.',
5897 DEBUG_DEVELOPER);
5899 global $CFG, $DB;
5901 require_once($CFG->dirroot . '/calendar/lib.php');
5902 // In order to execute this we need bennu.
5903 require_once($CFG->libdir.'/bennu/bennu.inc.php');
5905 mtrace('Updating calendar subscriptions:');
5906 cron_trace_time_and_memory();
5908 $time = time();
5909 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0
5910 AND lastupdated + pollinterval < ?', array($time));
5911 foreach ($subscriptions as $sub) {
5912 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
5913 try {
5914 $log = calendar_update_subscription_events($sub->id);
5915 mtrace(trim(strip_tags($log)));
5916 } catch (moodle_exception $ex) {
5917 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
5921 mtrace('Finished updating calendar subscriptions.');
5923 return true;
5927 * Previous internal API, it was not supposed to be used anywhere.
5929 * @access private
5930 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
5931 * @param int $userid the id of the user
5932 * @param context_course $coursecontext course context
5933 * @param array $accessdata accessdata array (modified)
5934 * @return void modifies $accessdata parameter
5936 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
5937 throw new coding_exception('load_course_context() is removed. Do not use private functions or data structures.');
5941 * Previous internal API, it was not supposed to be used anywhere.
5943 * @access private
5944 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
5945 * @param int $roleid the id of the user
5946 * @param context $context needs path!
5947 * @param array $accessdata accessdata array (is modified)
5948 * @return array
5950 function load_role_access_by_context($roleid, context $context, &$accessdata) {
5951 throw new coding_exception('load_role_access_by_context() is removed. Do not use private functions or data structures.');
5955 * Previous internal API, it was not supposed to be used anywhere.
5957 * @access private
5958 * @deprecated since Moodle 3.4 and removed immediately. MDL-49398.
5959 * @return void
5961 function dedupe_user_access() {
5962 throw new coding_exception('dedupe_user_access() is removed. Do not use private functions or data structures.');
5966 * Previous internal API, it was not supposed to be used anywhere.
5967 * Return a nested array showing role assignments
5968 * and all relevant role capabilities for the user.
5970 * [ra] => [/path][roleid]=roleid
5971 * [rdef] => ["$contextpath:$roleid"][capability]=permission
5973 * @access private
5974 * @deprecated since Moodle 3.4. MDL-49398.
5975 * @param int $userid - the id of the user
5976 * @return array access info array
5978 function get_user_access_sitewide($userid) {
5979 debugging('get_user_access_sitewide() is deprecated. Do not use private functions or data structures.', DEBUG_DEVELOPER);
5981 $accessdata = get_user_accessdata($userid);
5982 $accessdata['rdef'] = array();
5983 $roles = array();
5985 foreach ($accessdata['ra'] as $path => $pathroles) {
5986 $roles = array_merge($pathroles, $roles);
5989 $rdefs = get_role_definitions($roles);
5991 foreach ($rdefs as $roleid => $rdef) {
5992 foreach ($rdef as $path => $caps) {
5993 $accessdata['rdef']["$path:$roleid"] = $caps;
5997 return $accessdata;
6001 * Generates the HTML for a miniature calendar.
6003 * @param array $courses list of course to list events from
6004 * @param array $groups list of group
6005 * @param array $users user's info
6006 * @param int|bool $calmonth calendar month in numeric, default is set to false
6007 * @param int|bool $calyear calendar month in numeric, default is set to false
6008 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
6009 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
6010 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
6011 * and $calyear to support multiple calendars
6012 * @return string $content return html table for mini calendar
6013 * @deprecated since Moodle 3.4. MDL-59333
6015 function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
6016 $courseid = false, $time = 0) {
6017 global $PAGE;
6019 debugging('calendar_get_mini() has been deprecated. Please update your code to use calendar_get_view.',
6020 DEBUG_DEVELOPER);
6022 if (!empty($calmonth) && !empty($calyear)) {
6023 // Do this check for backwards compatibility.
6024 // The core should be passing a timestamp rather than month and year.
6025 // If a month and year are passed they will be in Gregorian.
6026 // Ensure it is a valid date, else we will just set it to the current timestamp.
6027 if (checkdate($calmonth, 1, $calyear)) {
6028 $time = make_timestamp($calyear, $calmonth, 1);
6029 } else {
6030 $time = time();
6032 } else if (empty($time)) {
6033 // Get the current date in the calendar type being used.
6034 $time = time();
6037 if ($courseid == SITEID) {
6038 $course = get_site();
6039 } else {
6040 $course = get_course($courseid);
6042 $calendar = new calendar_information(0, 0, 0, $time);
6043 $calendar->prepare_for_view($course, $courses);
6045 $renderer = $PAGE->get_renderer('core_calendar');
6046 list($data, $template) = calendar_get_view($calendar, 'mini');
6047 return $renderer->render_from_template($template, $data);
6051 * Gets the calendar upcoming event.
6053 * @param array $courses array of courses
6054 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
6055 * @param array|int|bool $users array of users, user id or boolean for all/no user events
6056 * @param int $daysinfuture number of days in the future we 'll look
6057 * @param int $maxevents maximum number of events
6058 * @param int $fromtime start time
6059 * @return array $output array of upcoming events
6060 * @deprecated since Moodle 3.4. MDL-59333
6062 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
6063 debugging(
6064 'calendar_get_upcoming() has been deprecated. ' .
6065 'Please see block_calendar_upcoming::get_content() for the correct API usage.',
6066 DEBUG_DEVELOPER
6069 global $COURSE;
6071 $display = new \stdClass;
6072 $display->range = $daysinfuture; // How many days in the future we 'll look.
6073 $display->maxevents = $maxevents;
6075 $output = array();
6077 $processed = 0;
6078 $now = time(); // We 'll need this later.
6079 $usermidnighttoday = usergetmidnight($now);
6081 if ($fromtime) {
6082 $display->tstart = $fromtime;
6083 } else {
6084 $display->tstart = $usermidnighttoday;
6087 // This works correctly with respect to the user's DST, but it is accurate
6088 // only because $fromtime is always the exact midnight of some day!
6089 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
6091 // Get the events matching our criteria.
6092 $events = calendar_get_legacy_events($display->tstart, $display->tend, $users, $groups, $courses);
6094 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
6095 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
6096 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
6097 // arguments to this function.
6098 $hrefparams = array();
6099 if (!empty($courses)) {
6100 $courses = array_diff($courses, array(SITEID));
6101 if (count($courses) == 1) {
6102 $hrefparams['course'] = reset($courses);
6106 if ($events !== false) {
6107 foreach ($events as $event) {
6108 if (!empty($event->modulename)) {
6109 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
6110 if (empty($instances[$event->instance]->uservisible)) {
6111 continue;
6115 if ($processed >= $display->maxevents) {
6116 break;
6119 $event->time = calendar_format_event_time($event, $now, $hrefparams);
6120 $output[] = $event;
6121 $processed++;
6125 return $output;
6129 * Creates a record in the role_allow_override table
6131 * @param int $sroleid source roleid
6132 * @param int $troleid target roleid
6133 * @return void
6134 * @deprecated since Moodle 3.4. MDL-50666
6136 function allow_override($sroleid, $troleid) {
6137 debugging('allow_override() has been deprecated. Please update your code to use core_role_set_override_allowed.',
6138 DEBUG_DEVELOPER);
6140 core_role_set_override_allowed($sroleid, $troleid);
6144 * Creates a record in the role_allow_assign table
6146 * @param int $fromroleid source roleid
6147 * @param int $targetroleid target roleid
6148 * @return void
6149 * @deprecated since Moodle 3.4. MDL-50666
6151 function allow_assign($fromroleid, $targetroleid) {
6152 debugging('allow_assign() has been deprecated. Please update your code to use core_role_set_assign_allowed.',
6153 DEBUG_DEVELOPER);
6155 core_role_set_assign_allowed($fromroleid, $targetroleid);
6159 * Creates a record in the role_allow_switch table
6161 * @param int $fromroleid source roleid
6162 * @param int $targetroleid target roleid
6163 * @return void
6164 * @deprecated since Moodle 3.4. MDL-50666
6166 function allow_switch($fromroleid, $targetroleid) {
6167 debugging('allow_switch() has been deprecated. Please update your code to use core_role_set_switch_allowed.',
6168 DEBUG_DEVELOPER);
6170 core_role_set_switch_allowed($fromroleid, $targetroleid);
6174 * Organise categories into a single parent category (called the 'Top' category) per context.
6176 * @param array $categories List of question categories in the format of ["$categoryid,$contextid" => $category].
6177 * @param array $pcontexts List of context ids.
6178 * @return array
6179 * @deprecated since Moodle 3.5. MDL-61132
6181 function question_add_tops($categories, $pcontexts) {
6182 debugging('question_add_tops() has been deprecated. You may want to pass $top = true to get_categories_for_contexts().',
6183 DEBUG_DEVELOPER);
6185 $topcats = array();
6186 foreach ($pcontexts as $contextid) {
6187 $topcat = question_get_top_category($contextid, true);
6188 $context = context::instance_by_id($contextid);
6190 $newcat = new stdClass();
6191 $newcat->id = "{$topcat->id},$contextid";
6192 $newcat->name = get_string('topfor', 'question', $context->get_context_name(false));
6193 $newcat->parent = 0;
6194 $newcat->contextid = $contextid;
6195 $topcats["{$topcat->id},$contextid"] = $newcat;
6197 // Put topcats in at beginning of array - they'll be sorted into different contexts later.
6198 return array_merge($topcats, $categories);
6202 * Checks if the question category is the highest-level category in the context that can be edited, and has no siblings.
6204 * @param int $categoryid a category id.
6205 * @return bool
6206 * @deprecated since Moodle 3.5. MDL-61132
6208 function question_is_only_toplevel_category_in_context($categoryid) {
6209 debugging('question_is_only_toplevel_category_in_context() has been deprecated. '
6210 . 'Please update your code to use question_is_only_child_of_top_category_in_context() instead.',
6211 DEBUG_DEVELOPER);
6213 return question_is_only_child_of_top_category_in_context($categoryid);
6217 * Moves messages from a particular user from the message table (unread messages) to message_read
6218 * This is typically only used when a user is deleted
6220 * @param object $userid User id
6221 * @return boolean success
6222 * @deprecated since Moodle 3.5
6224 function message_move_userfrom_unread2read($userid) {
6225 debugging('message_move_userfrom_unread2read() is deprecated and is no longer used.', DEBUG_DEVELOPER);
6227 global $DB;
6229 // Move all unread messages from message table to message_read.
6230 if ($messages = $DB->get_records_select('message', 'useridfrom = ?', array($userid), 'timecreated')) {
6231 foreach ($messages as $message) {
6232 message_mark_message_read($message, 0); // Set timeread to 0 as the message was never read.
6235 return true;
6239 * Retrieve users blocked by $user1
6241 * @param object $user1 the user whose messages are being viewed
6242 * @param object $user2 the user $user1 is talking to. If they are being blocked
6243 * they will have a variable called 'isblocked' added to their user object
6244 * @return array the users blocked by $user1
6245 * @deprecated since Moodle 3.5
6247 function message_get_blocked_users($user1=null, $user2=null) {
6248 debugging('message_get_blocked_users() is deprecated, please use \core_message\api::get_blocked_users() instead.',
6249 DEBUG_DEVELOPER);
6251 global $USER;
6253 if (empty($user1)) {
6254 $user1 = new stdClass();
6255 $user1->id = $USER->id;
6258 return \core_message\api::get_blocked_users($user1->id);
6262 * Retrieve $user1's contacts (online, offline and strangers)
6264 * @param object $user1 the user whose messages are being viewed
6265 * @param object $user2 the user $user1 is talking to. If they are a contact
6266 * they will have a variable called 'iscontact' added to their user object
6267 * @return array containing 3 arrays. array($onlinecontacts, $offlinecontacts, $strangers)
6268 * @deprecated since Moodle 3.5
6270 function message_get_contacts($user1=null, $user2=null) {
6271 debugging('message_get_contacts() is deprecated and is no longer used.', DEBUG_DEVELOPER);
6273 global $DB, $CFG, $USER;
6275 if (empty($user1)) {
6276 $user1 = $USER;
6279 if (!empty($user2)) {
6280 $user2->iscontact = false;
6283 $timetoshowusers = 300; // Seconds default.
6284 if (isset($CFG->block_online_users_timetosee)) {
6285 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
6288 // Rime which a user is counting as being active since.
6289 $timefrom = time() - $timetoshowusers;
6291 // People in our contactlist who are online.
6292 $onlinecontacts = array();
6293 // People in our contactlist who are offline.
6294 $offlinecontacts = array();
6295 // People who are not in our contactlist but have sent us a message.
6296 $strangers = array();
6298 // Get all in our contact list who are not blocked in our and count messages we have waiting from each of them.
6299 $rs = \core_message\api::get_contacts_with_unread_message_count($user1->id);
6300 foreach ($rs as $rd) {
6301 if ($rd->lastaccess >= $timefrom) {
6302 // They have been active recently, so are counted online.
6303 $onlinecontacts[] = $rd;
6305 } else {
6306 $offlinecontacts[] = $rd;
6309 if (!empty($user2) && $user2->id == $rd->id) {
6310 $user2->iscontact = true;
6314 // Get messages from anyone who isn't in our contact list and count the number of messages we have from each of them.
6315 $rs = \core_message\api::get_non_contacts_with_unread_message_count($user1->id);
6316 // Add user id as array index, so supportuser and noreply user don't get duplicated (if they are real users).
6317 foreach ($rs as $rd) {
6318 $strangers[$rd->id] = $rd;
6321 // Add noreply user and support user to the list, if they don't exist.
6322 $supportuser = core_user::get_support_user();
6323 if (!isset($strangers[$supportuser->id]) && !$supportuser->deleted) {
6324 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
6325 if ($supportuser->messagecount > 0) {
6326 $strangers[$supportuser->id] = $supportuser;
6330 $noreplyuser = core_user::get_noreply_user();
6331 if (!isset($strangers[$noreplyuser->id]) && !$noreplyuser->deleted) {
6332 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
6333 if ($noreplyuser->messagecount > 0) {
6334 $strangers[$noreplyuser->id] = $noreplyuser;
6338 return array($onlinecontacts, $offlinecontacts, $strangers);
6342 * Mark a single message as read
6344 * @param stdClass $message An object with an object property ie $message->id which is an id in the message table
6345 * @param int $timeread the timestamp for when the message should be marked read. Usually time().
6346 * @param bool $messageworkingempty Is the message_working table already confirmed empty for this message?
6347 * @return int the ID of the message in the messags table
6348 * @deprecated since Moodle 3.5
6350 function message_mark_message_read($message, $timeread, $messageworkingempty=false) {
6351 debugging('message_mark_message_read() is deprecated, please use \core_message\api::mark_message_as_read()
6352 or \core_message\api::mark_notification_as_read().', DEBUG_DEVELOPER);
6354 if (!empty($message->notification)) {
6355 \core_message\api::mark_notification_as_read($message, $timeread);
6356 } else {
6357 \core_message\api::mark_message_as_read($message->useridto, $message, $timeread);
6360 return $message->id;
6365 * Checks if a user can delete a message.
6367 * @param stdClass $message the message to delete
6368 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
6369 * but will still seem as if it was by the user)
6370 * @return bool Returns true if a user can delete the message, false otherwise.
6371 * @deprecated since Moodle 3.5
6373 function message_can_delete_message($message, $userid) {
6374 debugging('message_can_delete_message() is deprecated, please use \core_message\api::can_delete_message() instead.',
6375 DEBUG_DEVELOPER);
6377 return \core_message\api::can_delete_message($userid, $message->id);
6381 * Deletes a message.
6383 * This function does not verify any permissions.
6385 * @param stdClass $message the message to delete
6386 * @param string $userid the user id of who we want to delete the message for (this may be done by the admin
6387 * but will still seem as if it was by the user)
6388 * @return bool
6389 * @deprecated since Moodle 3.5
6391 function message_delete_message($message, $userid) {
6392 debugging('message_delete_message() is deprecated, please use \core_message\api::delete_message() instead.',
6393 DEBUG_DEVELOPER);
6395 return \core_message\api::delete_message($userid, $message->id);